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. WHERE c.id = '.$courseId.'
  3327. GROUP BY user_id
  3328. HAVING DATE_SUB( "' . $now . '", INTERVAL '.$since.' DAY) > max_date ';
  3329. if ($since == 'never') {
  3330. $sql = 'SELECT course_user.user_id
  3331. FROM '.$table_course_rel_user.' course_user
  3332. LEFT JOIN '. $tbl_track_login.' stats_login
  3333. ON course_user.user_id = stats_login.user_id AND
  3334. relation_type<>'.COURSE_RELATION_TYPE_RRHH.'
  3335. INNER JOIN '.$tableCourse.' c
  3336. ON (c.id = stats_login.c_id)
  3337. '.$inner.'
  3338. WHERE
  3339. course_user.c_id = '.$courseId.' AND
  3340. stats_login.login_course_date IS NULL
  3341. GROUP BY course_user.user_id';
  3342. }
  3343. $rs = Database::query($sql);
  3344. $inactive_users = array();
  3345. while($user = Database::fetch_array($rs)) {
  3346. $inactive_users[] = $user['user_id'];
  3347. }
  3348. return $inactive_users;
  3349. }
  3350. /**
  3351. * Get count login per student
  3352. * @param int $student_id Student id
  3353. * @param int $courseId
  3354. * @param int $session_id Session id (optional)
  3355. * @return int count login
  3356. */
  3357. public static function count_login_per_student($student_id, $courseId, $session_id = 0)
  3358. {
  3359. $student_id = intval($student_id);
  3360. $courseId = intval($courseId);
  3361. $session_id = intval($session_id);
  3362. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  3363. $sql = 'SELECT '.$student_id.'
  3364. FROM ' . $table . '
  3365. WHERE
  3366. access_user_id=' . $student_id . ' AND
  3367. c_id="' . $courseId . '" AND
  3368. access_session_id = "'.$session_id.'" ';
  3369. $rs = Database::query($sql);
  3370. $nb_login = Database::num_rows($rs);
  3371. return $nb_login;
  3372. }
  3373. /**
  3374. * Get students followed by a human resources manager
  3375. * @param int Drh id
  3376. * @return array Student list
  3377. */
  3378. public static function get_student_followed_by_drh($hr_dept_id)
  3379. {
  3380. $hr_dept_id = intval($hr_dept_id);
  3381. $a_students = array();
  3382. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  3383. $sql = 'SELECT DISTINCT user_id FROM '.$tbl_user.' as user
  3384. WHERE hr_dept_id='.$hr_dept_id;
  3385. $rs = Database::query($sql);
  3386. while($user = Database :: fetch_array($rs)) {
  3387. $a_students[$user['user_id']] = $user['user_id'];
  3388. }
  3389. return $a_students;
  3390. }
  3391. /**
  3392. * get count clicks about tools most used by course
  3393. * @param int $courseId
  3394. * @param int Session id (optional),
  3395. * if param $session_id is null(default) it'll return results
  3396. * including sessions, 0 = session is not filtered
  3397. * @return array tools data
  3398. */
  3399. public static function get_tools_most_used_by_course($courseId, $session_id = null)
  3400. {
  3401. $courseId = intval($courseId);
  3402. $data = array();
  3403. $TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  3404. $condition_session = '';
  3405. if (isset($session_id)) {
  3406. $session_id = intval($session_id);
  3407. $condition_session = ' AND access_session_id = '. $session_id;
  3408. }
  3409. $sql = "SELECT
  3410. access_tool,
  3411. COUNT(DISTINCT access_user_id),
  3412. count(access_tool) as count_access_tool
  3413. FROM $TABLETRACK_ACCESS
  3414. WHERE
  3415. access_tool IS NOT NULL AND
  3416. access_tool != '' AND
  3417. c_id = '$courseId'
  3418. $condition_session
  3419. GROUP BY access_tool
  3420. ORDER BY count_access_tool DESC
  3421. LIMIT 0, 3";
  3422. $rs = Database::query($sql);
  3423. if (Database::num_rows($rs) > 0) {
  3424. while ($row = Database::fetch_array($rs)) {
  3425. $data[] = $row;
  3426. }
  3427. }
  3428. return $data;
  3429. }
  3430. /**
  3431. * Get total clicks
  3432. * 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,
  3433. * BUT NO ROW MATCH THE CONDITION, IT SHOULD BE FINE TO USE IT WHEN YOU USE USER DEFINED DATES AND NO CHAMILO DATES
  3434. * @param int User Id
  3435. * @param int Course Id
  3436. * @param int Session Id (optional), if param $session_id is null(default) it'll return results including sessions, 0 = session is not filtered
  3437. * @param string Date from
  3438. * @param string Date to
  3439. * @return array Data
  3440. * @author César Perales cesar.perales@beeznest.com 2014-01-16
  3441. */
  3442. public static function get_total_clicks($userId, $courseId, $sessionId = 0, $date_from = '', $date_to = '')
  3443. {
  3444. $course = api_get_course_info_by_id($courseId);
  3445. $tables = array(
  3446. TABLE_STATISTIC_TRACK_E_LASTACCESS => array(
  3447. 'course' => 'c_id',
  3448. 'session' => 'access_session_id',
  3449. 'user' => 'access_user_id',
  3450. 'start_date'=> 'access_date',
  3451. ),
  3452. TABLE_STATISTIC_TRACK_E_ACCESS => array(
  3453. 'course' => 'c_id',
  3454. 'session' => 'access_session_id',
  3455. 'user' => 'access_user_id',
  3456. 'start_date'=> 'access_date',
  3457. ),
  3458. #TABLE_STATISTIC_TRACK_E_LOGIN, array(,, 'login_date', 'logout_date');
  3459. TABLE_STATISTIC_TRACK_E_DOWNLOADS => array(
  3460. 'course' => 'c_id',
  3461. 'session' => 'down_session_id',
  3462. 'user' => 'down_user_id',
  3463. 'start_date'=> 'down_date',
  3464. ),
  3465. TABLE_STATISTIC_TRACK_E_LINKS => array(
  3466. 'course' => 'c_id',
  3467. 'session' => 'links_session_id',
  3468. 'user' => 'links_user_id',
  3469. 'start_date'=> 'links_date',
  3470. ),
  3471. TABLE_STATISTIC_TRACK_E_ONLINE => array(
  3472. 'course' => 'c_id',
  3473. 'session' => 'session_id',
  3474. 'user' => 'login_user_id',
  3475. 'start_date'=> 'login_date',
  3476. ),
  3477. #TABLE_STATISTIC_TRACK_E_HOTPOTATOES,
  3478. /*TABLE_STATISTIC_TRACK_E_COURSE_ACCESS => array(
  3479. 'course' => 'c_id',
  3480. 'session' => 'session_id',
  3481. 'user' => 'user_id',
  3482. 'start_date'=> 'login_course_date',
  3483. 'end_date' => 'logout_course_date',
  3484. ),*/
  3485. TABLE_STATISTIC_TRACK_E_EXERCISES => array(
  3486. 'course' => 'c_id',
  3487. 'session' => 'session_id',
  3488. 'user' => 'exe_user_id',
  3489. 'start_date'=> 'exe_date',
  3490. ),
  3491. TABLE_STATISTIC_TRACK_E_ATTEMPT => array(
  3492. 'course' => 'c_id',
  3493. 'session' => 'session_id',
  3494. 'user' => 'user_id',
  3495. 'start_date'=> 'tms',
  3496. ),
  3497. #TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING,
  3498. #TABLE_STATISTIC_TRACK_E_DEFAULT,
  3499. TABLE_STATISTIC_TRACK_E_UPLOADS => array(
  3500. 'course' => 'c_id',
  3501. 'session' => 'upload_session_id',
  3502. 'user' => 'upload_user_id',
  3503. 'start_date'=> 'upload_date',
  3504. ),
  3505. );
  3506. foreach ($tables as $tableName => $fields) {
  3507. //If session is defined, add it to query
  3508. $where = '';
  3509. if (isset($sessionId) && !empty($sessionId)) {
  3510. $sessionField = $fields['session'];
  3511. $where .= " AND $sessionField = $sessionId";
  3512. }
  3513. //filter by date
  3514. if (!empty($date_from) && !empty($date_to)) {
  3515. $fieldStartDate = $fields['start_date'];
  3516. if (!isset($fields['end_date'])) {
  3517. $where .= sprintf(" AND ($fieldStartDate BETWEEN '%s' AND '%s' )", $date_from, $date_to) ;
  3518. } else {
  3519. $fieldEndDate = $fields['end_date'];
  3520. $where .= sprintf(" AND fieldStartDate >= '%s'
  3521. AND $fieldEndDate <= '%s'", $date_from, $date_to);
  3522. }
  3523. }
  3524. //query
  3525. $sql = "SELECT %s as user, count(*) as total
  3526. FROM %s
  3527. WHERE %s = '%s'
  3528. AND %s = %s
  3529. $where
  3530. GROUP BY %s";
  3531. $sql = sprintf($sql,
  3532. $fields['user'], //user field
  3533. $tableName, //FROM
  3534. $fields['course'], //course condition
  3535. $course['real_id'], //course condition
  3536. $fields['user'], //user condition
  3537. $userId, //user condition
  3538. $fields['user'] //GROUP BY
  3539. );
  3540. $rs = Database::query($sql);
  3541. //iterate query
  3542. if (Database::num_rows($rs) > 0) {
  3543. while ($row = Database::fetch_array($rs)) {
  3544. $data[$row['user']] = (isset($data[$row['user']])) ? $data[$row['user']] + $row[total]: $row['total'];
  3545. }
  3546. }
  3547. }
  3548. return $data;
  3549. }
  3550. /**
  3551. * get documents most downloaded by course
  3552. * @param string Course code
  3553. * @param int Session id (optional),
  3554. * if param $session_id is null(default) it'll return results including
  3555. * sessions, 0 = session is not filtered
  3556. * @param int Limit (optional, default = 0, 0 = without limit)
  3557. * @return array documents downloaded
  3558. */
  3559. public static function get_documents_most_downloaded_by_course($course_code, $session_id = null, $limit = 0)
  3560. {
  3561. //protect data
  3562. $courseId = api_get_course_int_id($course_code);
  3563. $data = array();
  3564. $TABLETRACK_DOWNLOADS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  3565. $condition_session = '';
  3566. if (isset($session_id)) {
  3567. $session_id = intval($session_id);
  3568. $condition_session = ' AND down_session_id = '. $session_id;
  3569. }
  3570. $sql = "SELECT down_doc_path, COUNT(DISTINCT down_user_id), COUNT(down_doc_path) as count_down
  3571. FROM $TABLETRACK_DOWNLOADS
  3572. WHERE c_id = $courseId
  3573. $condition_session
  3574. GROUP BY down_doc_path
  3575. ORDER BY count_down DESC
  3576. LIMIT 0, $limit";
  3577. $rs = Database::query($sql);
  3578. if (Database::num_rows($rs) > 0) {
  3579. while ($row = Database::fetch_array($rs)) {
  3580. $data[] = $row;
  3581. }
  3582. }
  3583. return $data;
  3584. }
  3585. /**
  3586. * get links most visited by course
  3587. * @param string Course code
  3588. * @param int Session id (optional),
  3589. * if param $session_id is null(default) it'll
  3590. * return results including sessions, 0 = session is not filtered
  3591. * @return array links most visited
  3592. */
  3593. public static function get_links_most_visited_by_course($course_code, $session_id = null)
  3594. {
  3595. $course_code = Database::escape_string($course_code);
  3596. $course_info = api_get_course_info($course_code);
  3597. $course_id = $course_info['real_id'];
  3598. $data = array();
  3599. $TABLETRACK_LINKS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
  3600. $TABLECOURSE_LINKS = Database::get_course_table(TABLE_LINK);
  3601. $condition_session = '';
  3602. if (isset($session_id)) {
  3603. $session_id = intval($session_id);
  3604. $condition_session = ' AND cl.session_id = '.$session_id;
  3605. }
  3606. $sql = "SELECT cl.title, cl.url,count(DISTINCT sl.links_user_id), count(cl.title) as count_visits
  3607. FROM $TABLETRACK_LINKS AS sl, $TABLECOURSE_LINKS AS cl
  3608. WHERE
  3609. cl.c_id = $course_id AND
  3610. sl.links_link_id = cl.id AND
  3611. sl.c_id = $course_id
  3612. $condition_session
  3613. GROUP BY cl.title, cl.url
  3614. ORDER BY count_visits DESC
  3615. LIMIT 0, 3";
  3616. $rs = Database::query($sql);
  3617. if (Database::num_rows($rs) > 0) {
  3618. while ($row = Database::fetch_array($rs)) {
  3619. $data[] = $row;
  3620. }
  3621. }
  3622. return $data;
  3623. }
  3624. /**
  3625. * Shows the user progress (when clicking in the Progress tab)
  3626. *
  3627. * @param int $user_id
  3628. * @param int $session_id
  3629. * @param string $extra_params
  3630. * @param bool $show_courses
  3631. * @param bool $showAllSessions
  3632. *
  3633. * @return string
  3634. */
  3635. public static function show_user_progress(
  3636. $user_id,
  3637. $session_id = 0,
  3638. $extra_params = '',
  3639. $show_courses = true,
  3640. $showAllSessions = true
  3641. ) {
  3642. $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  3643. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  3644. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  3645. $tbl_access_rel_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3646. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3647. $tbl_access_rel_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3648. $user_id = intval($user_id);
  3649. $session_id = intval($session_id);
  3650. if (api_is_multiple_url_enabled()) {
  3651. $sql = "SELECT c.code, title
  3652. FROM $tbl_course_user cu
  3653. INNER JOIN $tbl_course c
  3654. ON (cu.c_id = c.id)
  3655. INNER JOIN $tbl_access_rel_course a
  3656. ON (a.c_id = c.id)
  3657. WHERE
  3658. cu.user_id = $user_id AND
  3659. relation_type<> ".COURSE_RELATION_TYPE_RRHH." AND
  3660. access_url_id = ".api_get_current_access_url_id()."
  3661. ORDER BY title";
  3662. } else {
  3663. $sql = "SELECT c.code, title
  3664. FROM $tbl_course_user u
  3665. INNER JOIN $tbl_course c ON (c_id = c.id)
  3666. WHERE
  3667. u.user_id= $user_id AND
  3668. relation_type<>".COURSE_RELATION_TYPE_RRHH."
  3669. ORDER BY title";
  3670. }
  3671. $rs = Database::query($sql);
  3672. $courses = $course_in_session = $temp_course_in_session = array();
  3673. while ($row = Database :: fetch_array($rs, 'ASSOC')) {
  3674. $courses[$row['code']] = $row['title'];
  3675. }
  3676. $orderBy = " ORDER BY name ";
  3677. $extraInnerJoin = null;
  3678. if (SessionManager::orderCourseIsEnabled() && !empty($session_id)) {
  3679. $orderBy = " ORDER BY s.id, position ";
  3680. $tableSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3681. $extraInnerJoin = " INNER JOIN $tableSessionRelCourse src
  3682. ON (cu.c_id = src.c_id AND src.session_id = $session_id) ";
  3683. }
  3684. $sessionCondition = '';
  3685. if (!empty($session_id)) {
  3686. $sessionCondition = " AND s.id = $session_id";
  3687. }
  3688. // Get the list of sessions where the user is subscribed as student
  3689. if (api_is_multiple_url_enabled()) {
  3690. $sql = "SELECT DISTINCT c.code, s.id as session_id, name
  3691. FROM $tbl_session_course_user cu
  3692. INNER JOIN $tbl_access_rel_session a
  3693. ON (a.session_id = cu.session_id)
  3694. INNER JOIN $tbl_session s
  3695. ON (s.id = a.session_id)
  3696. INNER JOIN $tbl_course c
  3697. ON (c.id = cu.c_id)
  3698. $extraInnerJoin
  3699. WHERE
  3700. cu.user_id = $user_id AND
  3701. access_url_id = ".api_get_current_access_url_id()."
  3702. $sessionCondition
  3703. $orderBy ";
  3704. } else {
  3705. $sql = "SELECT DISTINCT c.code, s.id as session_id, name
  3706. FROM $tbl_session_course_user cu
  3707. INNER JOIN $tbl_session s
  3708. ON (s.id = cu.session_id)
  3709. INNER JOIN $tbl_course c
  3710. ON (c.id = cu.c_id)
  3711. $extraInnerJoin
  3712. WHERE
  3713. cu.user_id = $user_id
  3714. $sessionCondition
  3715. $orderBy ";
  3716. }
  3717. $rs = Database::query($sql);
  3718. $simple_session_array = array();
  3719. while ($row = Database :: fetch_array($rs)) {
  3720. $course_info = CourseManager::get_course_information($row['code']);
  3721. $temp_course_in_session[$row['session_id']]['course_list'][$course_info['real_id']] = $course_info;
  3722. $temp_course_in_session[$row['session_id']]['name'] = $row['name'];
  3723. $simple_session_array[$row['session_id']] = $row['name'];
  3724. }
  3725. foreach ($simple_session_array as $my_session_id => $session_name) {
  3726. $course_list = $temp_course_in_session[$my_session_id]['course_list'];
  3727. $my_course_data = array();
  3728. foreach ($course_list as $course_data) {
  3729. $my_course_data[$course_data['id']] = $course_data['title'];
  3730. }
  3731. if (empty($session_id)) {
  3732. $my_course_data = utf8_sort($my_course_data);
  3733. }
  3734. $final_course_data = array();
  3735. foreach($my_course_data as $course_id => $value) {
  3736. $final_course_data[$course_id] = $course_list[$course_id];
  3737. }
  3738. $course_in_session[$my_session_id]['course_list'] = $final_course_data;
  3739. $course_in_session[$my_session_id]['name'] = $session_name;
  3740. }
  3741. $html = '';
  3742. // Course list
  3743. if ($show_courses) {
  3744. if (!empty($courses)) {
  3745. $html .= Display::page_subheader(
  3746. Display::return_icon('course.png', get_lang('MyCourses'), array(), ICON_SIZE_SMALL).' '.get_lang('MyCourses')
  3747. );
  3748. $html .= '<table class="data_table" width="100%">';
  3749. $html .= '<tr>
  3750. '.Display::tag('th', get_lang('Course'), array('width'=>'300px')).'
  3751. '.Display::tag('th', get_lang('TimeSpentInTheCourse'), array('class'=>'head')).'
  3752. '.Display::tag('th', get_lang('Progress'), array('class'=>'head')).'
  3753. '.Display::tag('th', get_lang('Score').Display::return_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array('align' => 'absmiddle', 'hspace' => '3px')),array('class'=>'head')).'
  3754. '.Display::tag('th', get_lang('LastConnexion'), array('class'=>'head')).'
  3755. '.Display::tag('th', get_lang('Details'), array('class'=>'head')).'
  3756. </tr>';
  3757. foreach ($courses as $course_code => $course_title) {
  3758. $courseInfo = api_get_course_info($course_code);
  3759. $courseId = $courseInfo['real_id'];
  3760. $total_time_login = Tracking :: get_time_spent_on_the_course(
  3761. $user_id,
  3762. $courseId
  3763. );
  3764. $time = api_time_to_hms($total_time_login);
  3765. $progress = Tracking :: get_avg_student_progress(
  3766. $user_id,
  3767. $course_code
  3768. );
  3769. $percentage_score = Tracking :: get_avg_student_score(
  3770. $user_id,
  3771. $course_code,
  3772. array()
  3773. );
  3774. $last_connection = Tracking :: get_last_connection_date_on_the_course(
  3775. $user_id,
  3776. $courseInfo
  3777. );
  3778. if (is_null($progress)) {
  3779. $progress = '0%';
  3780. } else {
  3781. $progress = $progress.'%';
  3782. }
  3783. if (isset($_GET['course']) &&
  3784. $course_code == $_GET['course'] &&
  3785. empty($_GET['session_id'])
  3786. ) {
  3787. $html .= '<tr class="row_odd" style="background-color:#FBF09D">';
  3788. } else {
  3789. $html .= '<tr class="row_even">';
  3790. }
  3791. $url = api_get_course_url($course_code, $session_id);
  3792. $course_url = Display::url($course_title, $url, array('target'=>SESSION_LINK_TARGET));
  3793. $html .= '<td>'.$course_url.'</td>';
  3794. $html .= '<td align="center">'.$time.'</td>';
  3795. $html .= '<td align="center">'.$progress.'</td>';
  3796. $html .= '<td align="center">';
  3797. if (is_numeric($percentage_score)) {
  3798. $html .= $percentage_score.'%';
  3799. } else {
  3800. $html .= '0%';
  3801. }
  3802. $html .= '</td>';
  3803. $html .= '<td align="center">'.$last_connection.'</td>';
  3804. $html .= '<td align="center">';
  3805. if (isset($_GET['course']) &&
  3806. $course_code == $_GET['course'] &&
  3807. empty($_GET['session_id'])
  3808. ) {
  3809. $html .= '<a href="#">';
  3810. $html .= Display::return_icon('2rightarrow_na.png', get_lang('Details'));
  3811. } else {
  3812. $html .= '<a href="'.api_get_self().'?course='.$course_code.$extra_params.'">';
  3813. $html .= Display::return_icon('2rightarrow.png', get_lang('Details'));
  3814. }
  3815. $html .= '</a>';
  3816. $html .= '</td></tr>';
  3817. }
  3818. $html .= '</table>';
  3819. }
  3820. }
  3821. // Session list
  3822. if (!empty($course_in_session)) {
  3823. $main_session_graph = '';
  3824. //Load graphics only when calling to an specific session
  3825. $session_graph = array();
  3826. $all_exercise_graph_name_list = array();
  3827. $my_results = array();
  3828. $all_exercise_graph_list = array();
  3829. $all_exercise_start_time = array();
  3830. foreach ($course_in_session as $my_session_id => $session_data) {
  3831. $course_list = $session_data['course_list'];
  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(
  3911. Display::return_icon('session.png', get_lang('Sessions'), array(), ICON_SIZE_SMALL) . ' ' . get_lang('Sessions')
  3912. );
  3913. $html .= '<table class="data_table" width="100%">';
  3914. $html .= '<tr>
  3915. '.Display::tag('th', get_lang('Session'), array('width'=>'300px')).'
  3916. '.Display::tag('th', get_lang('PublishedExercises'), array('width'=>'300px')).'
  3917. '.Display::tag('th', get_lang('NewExercises'), array('class'=>'head')).'
  3918. '.Display::tag('th', get_lang('AverageExerciseResult'), array('class'=>'head')).'
  3919. '.Display::tag('th', get_lang('Details'), array('class'=>'head')).'
  3920. </tr>';
  3921. foreach ($course_in_session as $my_session_id => $session_data) {
  3922. $course_list = $session_data['course_list'];
  3923. $session_name = $session_data['name'];
  3924. if ($showAllSessions == false) {
  3925. if (isset($session_id) && !empty($session_id)) {
  3926. if ($session_id != $my_session_id) {
  3927. continue;
  3928. }
  3929. }
  3930. }
  3931. $all_exercises = 0;
  3932. $all_unanswered_exercises_by_user = 0;
  3933. $all_average = 0;
  3934. $stats_array = array();
  3935. foreach ($course_list as $course_data) {
  3936. //All exercises in the course @todo change for a real count
  3937. $exercises = ExerciseLib::get_all_exercises($course_data, $my_session_id);
  3938. $count_exercises = 0;
  3939. if (is_array($exercises) && !empty($exercises)) {
  3940. $count_exercises = count($exercises);
  3941. }
  3942. // Count of user results
  3943. $done_exercises = null;
  3944. $courseInfo = api_get_course_info($course_data['code']);
  3945. $answered_exercises = 0;
  3946. if (!empty($exercises)) {
  3947. foreach ($exercises as $exercise_item) {
  3948. $attempts = Event::count_exercise_attempts_by_user(
  3949. api_get_user_id(),
  3950. $exercise_item['id'],
  3951. $courseInfo['real_id'],
  3952. $my_session_id
  3953. );
  3954. if ($attempts > 1) {
  3955. $answered_exercises++;
  3956. }
  3957. }
  3958. }
  3959. // Average
  3960. $average = ExerciseLib::get_average_score_by_course($courseInfo['real_id'], $my_session_id);
  3961. $all_exercises += $count_exercises;
  3962. $all_unanswered_exercises_by_user += $count_exercises - $answered_exercises;
  3963. $all_average += $average;
  3964. }
  3965. $all_average = $all_average / count($course_list);
  3966. if (isset($_GET['session_id']) && $my_session_id == $_GET['session_id']) {
  3967. $html .= '<tr style="background-color:#FBF09D">';
  3968. } else {
  3969. $html .= '<tr>';
  3970. }
  3971. $url = api_get_path(WEB_CODE_PATH)."session/index.php?session_id={$my_session_id}";
  3972. $html .= Display::tag('td', Display::url($session_name, $url, array('target'=>SESSION_LINK_TARGET)));
  3973. $html .= Display::tag('td', $all_exercises);
  3974. $html .= Display::tag('td', $all_unanswered_exercises_by_user);
  3975. //$html .= Display::tag('td', $all_done_exercise);
  3976. $html .= Display::tag('td', ExerciseLib::convert_to_percentage($all_average));
  3977. if (isset($_GET['session_id']) && $my_session_id == $_GET['session_id']) {
  3978. $icon = Display::url(Display::return_icon('2rightarrow_na.png', get_lang('Details')), '?session_id='.$my_session_id);
  3979. } else {
  3980. $icon = Display::url(Display::return_icon('2rightarrow.png', get_lang('Details')), '?session_id='.$my_session_id);
  3981. }
  3982. $html .= Display::tag('td', $icon);
  3983. $html .= '</tr>';
  3984. }
  3985. $html .= '</table><br />';
  3986. $html .= Display::div($main_session_graph, array('id'=>'session_graph','class'=>'chart-session', 'style'=>'position:relative; text-align: center;') );
  3987. // Checking selected session.
  3988. if (isset($_GET['session_id'])) {
  3989. $session_id_from_get = intval($_GET['session_id']);
  3990. $session_data = $course_in_session[$session_id_from_get];
  3991. $course_list = $session_data['course_list'];
  3992. $html .= Display::tag('h3',$session_data['name'].' - '.get_lang('CourseList'));
  3993. $html .= '<table class="data_table" width="100%">';
  3994. //'.Display::tag('th', get_lang('DoneExercises'), array('class'=>'head')).'
  3995. $html .= '
  3996. <tr>
  3997. <th width="300px">'.get_lang('Course').'</th>
  3998. '.Display::tag('th', get_lang('PublishedExercises'), array('class'=>'head')).'
  3999. '.Display::tag('th', get_lang('NewExercises'), array('class'=>'head')).'
  4000. '.Display::tag('th', get_lang('MyAverage'), array('class'=>'head')).'
  4001. '.Display::tag('th', get_lang('AverageExerciseResult'), array('class'=>'head')).'
  4002. '.Display::tag('th', get_lang('TimeSpentInTheCourse'), array('class'=>'head')).'
  4003. '.Display::tag('th', get_lang('LPProgress') , array('class'=>'head')).'
  4004. '.Display::tag('th', get_lang('Score').Display::return_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px')), array('class'=>'head')).'
  4005. '.Display::tag('th', get_lang('LastConnexion'), array('class'=>'head')).'
  4006. '.Display::tag('th', get_lang('Details'), array('class'=>'head')).'
  4007. </tr>';
  4008. foreach ($course_list as $course_data) {
  4009. $course_code = $course_data['code'];
  4010. $course_title = $course_data['title'];
  4011. $courseInfo = api_get_course_info($course_code);
  4012. $courseId = $courseInfo['real_id'];
  4013. // All exercises in the course @todo change for a real count
  4014. $exercises = ExerciseLib::get_all_exercises($course_data, $session_id_from_get);
  4015. $count_exercises = 0;
  4016. if (!empty($exercises)) {
  4017. $count_exercises = count($exercises);
  4018. }
  4019. $answered_exercises = 0;
  4020. foreach($exercises as $exercise_item) {
  4021. $attempts = Event::count_exercise_attempts_by_user(
  4022. api_get_user_id(),
  4023. $exercise_item['id'],
  4024. $courseId,
  4025. $session_id_from_get
  4026. );
  4027. if ($attempts > 1) {
  4028. $answered_exercises++;
  4029. }
  4030. }
  4031. $unanswered_exercises = $count_exercises - $answered_exercises;
  4032. // Average
  4033. $average = ExerciseLib::get_average_score_by_course($courseId, $session_id_from_get);
  4034. $my_average = ExerciseLib::get_average_score_by_course_by_user(api_get_user_id(), $courseId, $session_id_from_get);
  4035. $stats_array[$course_code] = array(
  4036. 'exercises' => $count_exercises,
  4037. 'unanswered_exercises_by_user' => $unanswered_exercises,
  4038. 'done_exercises' => $done_exercises,
  4039. 'average' => $average,
  4040. 'my_average' => $my_average
  4041. );
  4042. $last_connection = Tracking:: get_last_connection_date_on_the_course(
  4043. $user_id,
  4044. $courseInfo,
  4045. $session_id_from_get
  4046. );
  4047. $progress = Tracking::get_avg_student_progress(
  4048. $user_id,
  4049. $course_code,
  4050. array(),
  4051. $session_id_from_get
  4052. );
  4053. $total_time_login = Tracking:: get_time_spent_on_the_course(
  4054. $user_id,
  4055. $courseId,
  4056. $session_id_from_get
  4057. );
  4058. $time = api_time_to_hms($total_time_login);
  4059. $percentage_score = Tracking::get_avg_student_score(
  4060. $user_id,
  4061. $course_code,
  4062. array(),
  4063. $session_id_from_get
  4064. );
  4065. $courseCodeFromGet = isset($_GET['course']) ? $_GET['course'] : null;
  4066. if ($course_code == $courseCodeFromGet && $_GET['session_id'] == $session_id_from_get) {
  4067. $html .= '<tr class="row_odd" style="background-color:#FBF09D" >';
  4068. } else {
  4069. $html .= '<tr class="row_even">';
  4070. }
  4071. $url = api_get_course_url($course_code, $session_id_from_get);
  4072. $course_url = Display::url($course_title, $url, array('target' => SESSION_LINK_TARGET));
  4073. $html .= Display::tag('td', $course_url);
  4074. $html .= Display::tag('td', $stats_array[$course_code]['exercises']);
  4075. $html .= Display::tag('td', $stats_array[$course_code]['unanswered_exercises_by_user']);
  4076. //$html .= Display::tag('td', $stats_array[$course_code]['done_exercises']);
  4077. $html .= Display::tag('td', ExerciseLib::convert_to_percentage($stats_array[$course_code]['my_average']));
  4078. $html .= Display::tag('td', $stats_array[$course_code]['average'] == 0 ? '-' : '('.ExerciseLib::convert_to_percentage($stats_array[$course_code]['average']).')');
  4079. $html .= Display::tag('td', $time, array('align'=>'center'));
  4080. if (is_numeric($progress)) {
  4081. $progress = $progress.'%';
  4082. } else {
  4083. $progress = '0%';
  4084. }
  4085. // Progress
  4086. $html .= Display::tag('td', $progress, array('align'=>'center'));
  4087. if (is_numeric($percentage_score)) {
  4088. $percentage_score = $percentage_score.'%';
  4089. } else {
  4090. $percentage_score = '0%';
  4091. }
  4092. //Score
  4093. $html .= Display::tag('td', $percentage_score, array('align'=>'center'));
  4094. $html .= Display::tag('td', $last_connection, array('align'=>'center'));
  4095. if ($course_code == $courseCodeFromGet && $_GET['session_id'] == $session_id_from_get) {
  4096. $details = '<a href="#">';
  4097. $details .=Display::return_icon('2rightarrow_na.png', get_lang('Details'));
  4098. } else {
  4099. $details = '<a href="'.api_get_self().'?course='.$course_code.'&session_id='.$session_id_from_get.$extra_params.'">';
  4100. $details .= Display::return_icon('2rightarrow.png', get_lang('Details'));
  4101. }
  4102. $details .= '</a>';
  4103. $html .= Display::tag('td', $details, array('align'=>'center'));
  4104. $html .= '</tr>';
  4105. }
  4106. $html .= '</table>';
  4107. }
  4108. }
  4109. return $html;
  4110. }
  4111. /**
  4112. * Shows the user detail progress (when clicking in the details link)
  4113. * @param int $user_id
  4114. * @param string $course_code
  4115. * @param int $session_id
  4116. * @return string html code
  4117. */
  4118. public static function show_course_detail($user_id, $course_code, $session_id)
  4119. {
  4120. $html = '';
  4121. if (isset($course_code)) {
  4122. $user_id = intval($user_id);
  4123. $session_id = intval($session_id);
  4124. $course = Database::escape_string($course_code);
  4125. $course_info = CourseManager::get_course_information($course);
  4126. $html .= Display::page_subheader($course_info['title']);
  4127. $html .= '<table class="data_table" width="100%">';
  4128. //Course details
  4129. $html .= '
  4130. <tr>
  4131. <th class="head" style="color:#000">'.get_lang('Exercises').'</th>
  4132. <th class="head" style="color:#000">'.get_lang('Attempts').'</th>
  4133. <th class="head" style="color:#000">'.get_lang('BestAttempt').'</th>
  4134. <th class="head" style="color:#000">'.get_lang('Ranking').'</th>
  4135. <th class="head" style="color:#000">'.get_lang('BestResultInCourse').'</th>
  4136. <th class="head" style="color:#000">'.get_lang('Statistics').' '.Display :: return_icon('info3.gif', get_lang('OnlyBestResultsPerStudent'), array('align' => 'absmiddle', 'hspace' => '3px')).'</th>
  4137. </tr>';
  4138. if (empty($session_id)) {
  4139. $user_list = CourseManager::get_user_list_from_course_code(
  4140. $course,
  4141. $session_id,
  4142. null,
  4143. null,
  4144. STUDENT
  4145. );
  4146. } else {
  4147. $user_list = CourseManager::get_user_list_from_course_code(
  4148. $course,
  4149. $session_id,
  4150. null,
  4151. null,
  4152. 0
  4153. );
  4154. }
  4155. // Show exercise results of invisible exercises? see BT#4091
  4156. $exercise_list = ExerciseLib::get_all_exercises(
  4157. $course_info,
  4158. $session_id,
  4159. false,
  4160. null,
  4161. false,
  4162. 2
  4163. );
  4164. $to_graph_exercise_result = array();
  4165. if (!empty($exercise_list)) {
  4166. $score = $weighting = $exe_id = 0;
  4167. foreach ($exercise_list as $exercices) {
  4168. $exercise_obj = new Exercise($course_info['real_id']);
  4169. $exercise_obj->read($exercices['id']);
  4170. $visible_return = $exercise_obj->is_visible();
  4171. $score = $weighting = $attempts = 0;
  4172. // Getting count of attempts by user
  4173. $attempts = Event::count_exercise_attempts_by_user(
  4174. api_get_user_id(),
  4175. $exercices['id'],
  4176. $course_info['real_id'],
  4177. $session_id
  4178. );
  4179. $html .= '<tr class="row_even">';
  4180. $url = api_get_path(WEB_CODE_PATH)."exercice/overview.php?cidReq={$course_info['code']}&id_session=$session_id&exerciseId={$exercices['id']}";
  4181. if ($visible_return['value'] == true) {
  4182. $exercices['title'] = Display::url(
  4183. $exercices['title'],
  4184. $url,
  4185. array('target' => SESSION_LINK_TARGET)
  4186. );
  4187. }
  4188. $html .= Display::tag('td', $exercices['title']);
  4189. // Exercise configuration show results or show only score
  4190. if ($exercices['results_disabled'] == 0 || $exercices['results_disabled'] == 2) {
  4191. //For graphics
  4192. $best_exercise_stats = Event::get_best_exercise_results_by_user(
  4193. $exercices['id'],
  4194. $course_info['real_id'],
  4195. $session_id
  4196. );
  4197. $to_graph_exercise_result[$exercices['id']] = array(
  4198. 'title' => $exercices['title'],
  4199. 'data' => $best_exercise_stats
  4200. );
  4201. $latest_attempt_url = '';
  4202. $best_score = $position = $percentage_score_result = '-';
  4203. $graph = $normal_graph = null;
  4204. // Getting best results
  4205. $best_score_data = ExerciseLib::get_best_attempt_in_course(
  4206. $exercices['id'],
  4207. $course_info['real_id'],
  4208. $session_id
  4209. );
  4210. $best_score = '';
  4211. if (!empty($best_score_data)) {
  4212. $best_score = ExerciseLib::show_score(
  4213. $best_score_data['exe_result'],
  4214. $best_score_data['exe_weighting']
  4215. );
  4216. }
  4217. if ($attempts > 0) {
  4218. $exercise_stat = ExerciseLib::get_best_attempt_by_user(
  4219. api_get_user_id(),
  4220. $exercices['id'],
  4221. $course_info['real_id'],
  4222. $session_id
  4223. );
  4224. if (!empty($exercise_stat)) {
  4225. // Always getting the BEST attempt
  4226. $score = $exercise_stat['exe_result'];
  4227. $weighting = $exercise_stat['exe_weighting'];
  4228. $exe_id = $exercise_stat['exe_id'];
  4229. $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;
  4230. $percentage_score_result = Display::url(ExerciseLib::show_score($score, $weighting), $latest_attempt_url);
  4231. $my_score = 0;
  4232. if (!empty($weighting) && intval($weighting) != 0) {
  4233. $my_score = $score/$weighting;
  4234. }
  4235. //@todo this function slows the page
  4236. $position = ExerciseLib::get_exercise_result_ranking($my_score, $exe_id, $exercices['id'], $course_info['code'], $session_id, $user_list);
  4237. $graph = self::generate_exercise_result_thumbnail_graph($to_graph_exercise_result[$exercices['id']]);
  4238. $normal_graph = self::generate_exercise_result_graph($to_graph_exercise_result[$exercices['id']]);
  4239. }
  4240. }
  4241. $html .= Display::div(
  4242. $normal_graph,
  4243. array('id'=>'main_graph_'.$exercices['id'],'class'=>'dialog', 'style'=>'display:none')
  4244. );
  4245. if (empty($graph)) {
  4246. $graph = '-';
  4247. } else {
  4248. $graph = Display::url(
  4249. '<img src="' . $graph . '" >',
  4250. $normal_graph,
  4251. array(
  4252. 'id' => $exercices['id'],
  4253. 'class' => 'expand-image',
  4254. )
  4255. );
  4256. }
  4257. $html .= Display::tag('td', $attempts, array('align'=>'center'));
  4258. $html .= Display::tag('td', $percentage_score_result, array('align'=>'center'));
  4259. $html .= Display::tag('td', $position, array('align'=>'center'));
  4260. $html .= Display::tag('td', $best_score, array('align'=>'center'));
  4261. $html .= Display::tag('td', $graph, array('align'=>'center'));
  4262. //$html .= Display::tag('td', $latest_attempt_url, array('align'=>'center', 'width'=>'25'));
  4263. } else {
  4264. // Exercise configuration NO results
  4265. $html .= Display::tag('td', $attempts, 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. $html .= Display::tag('td', '-', array('align'=>'center'));
  4270. }
  4271. $html .= '</tr>';
  4272. }
  4273. } else {
  4274. $html .= '<tr><td colspan="5" align="center">'.get_lang('NoEx').'</td></tr>';
  4275. }
  4276. $html .= '</table>';
  4277. // LP table results
  4278. $html .='<table class="data_table">';
  4279. $html .= Display::tag('th', get_lang('Learnpaths'), array('class'=>'head', 'style'=>'color:#000'));
  4280. $html .= Display::tag('th', get_lang('LatencyTimeSpent'), array('class'=>'head', 'style'=>'color:#000'));
  4281. $html .= Display::tag('th', get_lang('Progress'), array('class'=>'head', 'style'=>'color:#000'));
  4282. $html .= Display::tag('th', get_lang('Score'), array('class'=>'head', 'style'=>'color:#000'));
  4283. $html .= Display::tag('th', get_lang('LastConnexion'), array('class'=>'head', 'style'=>'color:#000'));
  4284. $html .= '</tr>';
  4285. $list = new LearnpathList(
  4286. api_get_user_id(),
  4287. $course_info['code'],
  4288. $session_id,
  4289. 'publicated_on ASC',
  4290. true,
  4291. null,
  4292. true
  4293. );
  4294. $lp_list = $list->get_flat_list();
  4295. if (!empty($lp_list) > 0) {
  4296. foreach ($lp_list as $lp_id => $learnpath) {
  4297. $progress = Tracking::get_avg_student_progress($user_id, $course, array($lp_id), $session_id);
  4298. $last_connection_in_lp = Tracking::get_last_connection_time_in_lp($user_id, $course, $lp_id, $session_id);
  4299. $time_spent_in_lp = Tracking::get_time_spent_in_lp($user_id, $course, array($lp_id), $session_id);
  4300. $percentage_score = Tracking::get_avg_student_score($user_id, $course, array($lp_id), $session_id);
  4301. if (is_numeric($percentage_score)) {
  4302. $percentage_score = $percentage_score.'%';
  4303. } else {
  4304. $percentage_score = '0%';
  4305. }
  4306. $time_spent_in_lp = api_time_to_hms($time_spent_in_lp);
  4307. $html .= '<tr class="row_even">';
  4308. $url = api_get_path(WEB_CODE_PATH)."newscorm/lp_controller.php?cidReq={$course_code}&id_session=$session_id&lp_id=$lp_id&action=view";
  4309. if ($learnpath['lp_visibility'] == 0) {
  4310. $html .= Display::tag('td', $learnpath['lp_name']);
  4311. } else {
  4312. $html .= Display::tag('td', Display::url($learnpath['lp_name'], $url, array('target'=>SESSION_LINK_TARGET)));
  4313. }
  4314. $html .= Display::tag('td', $time_spent_in_lp, array('align'=>'center'));
  4315. if (is_numeric($progress)) {
  4316. $progress = $progress.'%';
  4317. }
  4318. $html .= Display::tag('td', $progress, array('align'=>'center'));
  4319. $html .= Display::tag('td', $percentage_score);
  4320. $last_connection = '-';
  4321. if (!empty($last_connection_in_lp)) {
  4322. $last_connection = api_convert_and_format_date($last_connection_in_lp, DATE_TIME_FORMAT_LONG);
  4323. }
  4324. $html .= Display::tag('td', $last_connection, array('align'=>'center','width'=>'180px'));
  4325. $html .= "</tr>";
  4326. }
  4327. } else {
  4328. $html .= '<tr>
  4329. <td colspan="4" align="center">
  4330. '.get_lang('NoLearnpath').'
  4331. </td>
  4332. </tr>';
  4333. }
  4334. $html .='</table>';
  4335. }
  4336. return $html;
  4337. }
  4338. /**
  4339. * Generates an histogram
  4340. * @param array list of exercise names
  4341. * @param array my results 0 to 100
  4342. * @param array average scores 0-100
  4343. * @return string
  4344. */
  4345. static function generate_session_exercise_graph($names, $my_results, $average)
  4346. {
  4347. /* Create and populate the pData object */
  4348. $myData = new pData();
  4349. $myData->addPoints($names, 'Labels');
  4350. $myData->addPoints($my_results, 'Serie1');
  4351. $myData->addPoints($average, 'Serie2');
  4352. $myData->setSerieWeight('Serie1', 1);
  4353. $myData->setSerieTicks('Serie2', 4);
  4354. $myData->setSerieDescription('Labels', 'Months');
  4355. $myData->setAbscissa('Labels');
  4356. $myData->setSerieDescription('Serie1', get_lang('MyResults'));
  4357. $myData->setSerieDescription('Serie2', get_lang('AverageScore'));
  4358. $myData->setAxisUnit(0, '%');
  4359. $myData->loadPalette(api_get_path(SYS_CODE_PATH) . 'palettes/pchart/default.color', true);
  4360. // Cache definition
  4361. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  4362. $myCache = new pCache(array('CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)));
  4363. $chartHash = $myCache->getHash($myData);
  4364. if ($myCache->isInCache($chartHash)) {
  4365. //if we already created the img
  4366. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4367. $myCache->saveFromCache($chartHash, $imgPath);
  4368. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4369. } else {
  4370. /* Define width, height and angle */
  4371. $mainWidth = 860;
  4372. $mainHeight = 500;
  4373. $angle = 50;
  4374. /* Create the pChart object */
  4375. $myPicture = new pImage($mainWidth, $mainHeight, $myData);
  4376. /* Turn of Antialiasing */
  4377. $myPicture->Antialias = false;
  4378. /* Draw the background */
  4379. $settings = array('R' => 255, 'G' => 255, 'B' => 255);
  4380. $myPicture->drawFilledRectangle(0, 0, $mainWidth, $mainHeight, $settings);
  4381. /* Add a border to the picture */
  4382. $myPicture->drawRectangle(
  4383. 0,
  4384. 0,
  4385. $mainWidth - 1,
  4386. $mainHeight - 1,
  4387. array('R' => 0, 'G' => 0, 'B' => 0)
  4388. );
  4389. /* Set the default font */
  4390. $myPicture->setFontProperties(
  4391. array(
  4392. 'FontName' => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf',
  4393. 'FontSize' => 10)
  4394. );
  4395. /* Write the chart title */
  4396. $myPicture->drawText(
  4397. $mainWidth / 2,
  4398. 30,
  4399. get_lang('ExercisesInTimeProgressChart'),
  4400. array(
  4401. 'FontSize' => 12,
  4402. 'Align' => TEXT_ALIGN_BOTTOMMIDDLE
  4403. )
  4404. );
  4405. /* Set the default font */
  4406. $myPicture->setFontProperties(
  4407. array(
  4408. 'FontName' => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf',
  4409. 'FontSize' => 6
  4410. )
  4411. );
  4412. /* Define the chart area */
  4413. $myPicture->setGraphArea(60, 60, $mainWidth - 60, $mainHeight - 150);
  4414. /* Draw the scale */
  4415. $scaleSettings = array(
  4416. 'XMargin' => 10,
  4417. 'YMargin' => 10,
  4418. 'Floating' => true,
  4419. 'GridR' => 200,
  4420. 'GridG' => 200,
  4421. 'GridB' => 200,
  4422. 'DrawSubTicks' => true,
  4423. 'CycleBackground' => true,
  4424. 'LabelRotation' => $angle,
  4425. 'Mode' => SCALE_MODE_ADDALL_START0,
  4426. );
  4427. $myPicture->drawScale($scaleSettings);
  4428. /* Turn on Antialiasing */
  4429. $myPicture->Antialias = true;
  4430. /* Enable shadow computing */
  4431. $myPicture->setShadow(
  4432. true,
  4433. array(
  4434. 'X' => 1,
  4435. 'Y' => 1,
  4436. 'R' => 0,
  4437. 'G' => 0,
  4438. 'B' => 0,
  4439. 'Alpha' => 10
  4440. )
  4441. );
  4442. /* Draw the line chart */
  4443. $myPicture->setFontProperties(
  4444. array(
  4445. 'FontName' => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf',
  4446. 'FontSize' => 10
  4447. )
  4448. );
  4449. $myPicture->drawSplineChart();
  4450. $myPicture->drawPlotChart(
  4451. array(
  4452. 'DisplayValues' => true,
  4453. 'PlotBorder' => true,
  4454. 'BorderSize' => 1,
  4455. 'Surrounding' => -60,
  4456. 'BorderAlpha' => 80
  4457. )
  4458. );
  4459. /* Write the chart legend */
  4460. $myPicture->drawLegend(
  4461. $mainWidth / 2 + 50,
  4462. 50,
  4463. array(
  4464. 'Style' => LEGEND_BOX,
  4465. 'Mode' => LEGEND_HORIZONTAL,
  4466. 'FontR' => 0,
  4467. 'FontG' => 0,
  4468. 'FontB' => 0,
  4469. 'R' => 220,
  4470. 'G' => 220,
  4471. 'B' => 220,
  4472. 'Alpha' => 100
  4473. )
  4474. );
  4475. $myCache->writeToCache($chartHash, $myPicture);
  4476. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4477. $myCache->saveFromCache($chartHash, $imgPath);
  4478. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4479. }
  4480. $html = '<img src="' . $imgPath . '">';
  4481. return $html;
  4482. }
  4483. /**
  4484. *
  4485. * Returns a thumbnail of the function generate_exercise_result_graph
  4486. * @param array $attempts
  4487. */
  4488. static function generate_exercise_result_thumbnail_graph($attempts)
  4489. {
  4490. //$exercise_title = $attempts['title'];
  4491. $attempts = $attempts['data'];
  4492. $my_exercise_result_array = $exercise_result = array();
  4493. if (empty($attempts)) {
  4494. return null;
  4495. }
  4496. foreach ($attempts as $attempt) {
  4497. if (api_get_user_id() == $attempt['exe_user_id']) {
  4498. if ($attempt['exe_weighting'] != 0 ) {
  4499. $my_exercise_result_array[]= $attempt['exe_result']/$attempt['exe_weighting'];
  4500. }
  4501. } else {
  4502. if ($attempt['exe_weighting'] != 0 ) {
  4503. $exercise_result[]= $attempt['exe_result']/$attempt['exe_weighting'];
  4504. }
  4505. }
  4506. }
  4507. //Getting best result
  4508. rsort($my_exercise_result_array);
  4509. $my_exercise_result = 0;
  4510. if (isset($my_exercise_result_array[0])) {
  4511. $my_exercise_result = $my_exercise_result_array[0] *100;
  4512. }
  4513. $max = 100;
  4514. $pieces = 5 ;
  4515. $part = round($max / $pieces);
  4516. $x_axis = array();
  4517. $final_array = array();
  4518. $my_final_array = array();
  4519. for ($i=1; $i <=$pieces; $i++) {
  4520. $sum = 1;
  4521. if ($i == 1) {
  4522. $sum = 0;
  4523. }
  4524. $min = ($i-1)*$part + $sum;
  4525. $max = ($i)*$part;
  4526. $x_axis[]= $min." - ".$max;
  4527. $count = 0;
  4528. foreach($exercise_result as $result) {
  4529. $percentage = $result*100;
  4530. //echo $percentage.' - '.$min.' - '.$max."<br />";
  4531. if ($percentage >= $min && $percentage <= $max) {
  4532. //echo ' is > ';
  4533. $count++;
  4534. }
  4535. }
  4536. //echo '<br />';
  4537. $final_array[]= $count;
  4538. if ($my_exercise_result >= $min && $my_exercise_result <= $max) {
  4539. $my_final_array[] = 1;
  4540. } else {
  4541. $my_final_array[] = 0;
  4542. }
  4543. }
  4544. //Fix to remove the data of the user with my data
  4545. for($i = 0; $i<=count($my_final_array); $i++) {
  4546. if (!empty($my_final_array[$i])) {
  4547. $my_final_array[$i] = $final_array[$i] + 1; //Add my result
  4548. $final_array[$i] = 0;
  4549. }
  4550. }
  4551. // Dataset definition
  4552. $dataSet = new pData();
  4553. $dataSet->addPoints($final_array, 'Serie1');
  4554. $dataSet->addPoints($my_final_array, 'Serie2');
  4555. $dataSet->normalize(100, "%");
  4556. $dataSet->loadPalette(api_get_path(SYS_CODE_PATH) . 'palettes/pchart/default.color', true);
  4557. // Cache definition
  4558. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  4559. $myCache = new pCache(array('CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)));
  4560. $chartHash = $myCache->getHash($dataSet);
  4561. if ($myCache->isInCache($chartHash)) {
  4562. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4563. $myCache->saveFromCache($chartHash, $imgPath);
  4564. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4565. } else {
  4566. /* Create the pChart object */
  4567. $widthSize = 80;
  4568. $heightSize = 35;
  4569. $fontSize = 2;
  4570. $myPicture = new pImage($widthSize, $heightSize, $dataSet);
  4571. /* Turn of Antialiasing */
  4572. $myPicture->Antialias = false;
  4573. /* Add a border to the picture */
  4574. $myPicture->drawRectangle(0, 0, $widthSize - 1, $heightSize - 1, array('R' => 0, 'G' => 0, 'B' => 0));
  4575. /* Set the default font */
  4576. $myPicture->setFontProperties(array('FontName' => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf', 'FontSize' => $fontSize));
  4577. /* Do not write the chart title */
  4578. /* Define the chart area */
  4579. $myPicture->setGraphArea(5, 5, $widthSize - 5, $heightSize - 5);
  4580. /* Draw the scale */
  4581. $scaleSettings = array(
  4582. 'GridR' => 200,
  4583. 'GridG' => 200,
  4584. 'GridB' => 200,
  4585. 'DrawSubTicks' => true,
  4586. 'CycleBackground' => true,
  4587. 'Mode' => SCALE_MODE_MANUAL,
  4588. 'ManualScale' => array(
  4589. '0' => array(
  4590. 'Min' => 0,
  4591. 'Max' => 100
  4592. )
  4593. )
  4594. );
  4595. $myPicture->drawScale($scaleSettings);
  4596. /* Turn on shadow computing */
  4597. $myPicture->setShadow(
  4598. true,
  4599. array(
  4600. 'X' => 1,
  4601. 'Y' => 1,
  4602. 'R' => 0,
  4603. 'G' => 0,
  4604. 'B' => 0,
  4605. 'Alpha' => 10
  4606. )
  4607. );
  4608. /* Draw the chart */
  4609. $myPicture->setShadow(
  4610. true,
  4611. array(
  4612. 'X' => 1,
  4613. 'Y' => 1,
  4614. 'R' => 0,
  4615. 'G' => 0,
  4616. 'B' => 0,
  4617. 'Alpha' => 10
  4618. )
  4619. );
  4620. $settings = array(
  4621. 'DisplayValues' => true,
  4622. 'DisplaySize' => $fontSize,
  4623. 'DisplayR' => 0,
  4624. 'DisplayG' => 0,
  4625. 'DisplayB' => 0,
  4626. 'DisplayOrientation' => ORIENTATION_HORIZONTAL,
  4627. 'Gradient' => false,
  4628. 'Surrounding' => 5,
  4629. 'InnerSurrounding' => 5
  4630. );
  4631. $myPicture->drawStackedBarChart($settings);
  4632. /* Save and write in cache */
  4633. $myCache->writeToCache($chartHash, $myPicture);
  4634. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4635. $myCache->saveFromCache($chartHash, $imgPath);
  4636. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4637. }
  4638. return $imgPath;
  4639. }
  4640. /**
  4641. * Generates a big graph with the number of best results
  4642. * @param array
  4643. */
  4644. static function generate_exercise_result_graph($attempts)
  4645. {
  4646. $exercise_title = strip_tags($attempts['title']);
  4647. $attempts = $attempts['data'];
  4648. $my_exercise_result_array = $exercise_result = array();
  4649. if (empty($attempts)) {
  4650. return null;
  4651. }
  4652. foreach ($attempts as $attempt) {
  4653. if (api_get_user_id() == $attempt['exe_user_id']) {
  4654. if ($attempt['exe_weighting'] != 0 ) {
  4655. $my_exercise_result_array[]= $attempt['exe_result']/$attempt['exe_weighting'];
  4656. }
  4657. } else {
  4658. if ($attempt['exe_weighting'] != 0 ) {
  4659. $exercise_result[]= $attempt['exe_result']/$attempt['exe_weighting'];
  4660. }
  4661. }
  4662. }
  4663. //Getting best result
  4664. rsort($my_exercise_result_array);
  4665. $my_exercise_result = 0;
  4666. if (isset($my_exercise_result_array[0])) {
  4667. $my_exercise_result = $my_exercise_result_array[0] *100;
  4668. }
  4669. $max = 100;
  4670. $pieces = 5 ;
  4671. $part = round($max / $pieces);
  4672. $x_axis = array();
  4673. $final_array = array();
  4674. $my_final_array = array();
  4675. for ($i=1; $i <=$pieces; $i++) {
  4676. $sum = 1;
  4677. if ($i == 1) {
  4678. $sum = 0;
  4679. }
  4680. $min = ($i-1)*$part + $sum;
  4681. $max = ($i)*$part;
  4682. $x_axis[]= $min." - ".$max;
  4683. $count = 0;
  4684. foreach($exercise_result as $result) {
  4685. $percentage = $result*100;
  4686. if ($percentage >= $min && $percentage <= $max) {
  4687. $count++;
  4688. }
  4689. }
  4690. $final_array[]= $count;
  4691. if ($my_exercise_result >= $min && $my_exercise_result <= $max) {
  4692. $my_final_array[] = 1;
  4693. } else {
  4694. $my_final_array[] = 0;
  4695. }
  4696. }
  4697. //Fix to remove the data of the user with my data
  4698. for($i = 0; $i<=count($my_final_array); $i++) {
  4699. if (!empty($my_final_array[$i])) {
  4700. $my_final_array[$i] = $final_array[$i] + 1; //Add my result
  4701. $final_array[$i] = 0;
  4702. }
  4703. }
  4704. // Dataset definition
  4705. $dataSet = new pData();
  4706. $dataSet->addPoints($final_array, 'Serie1');
  4707. $dataSet->addPoints($my_final_array, 'Serie2');
  4708. $dataSet->addPoints($x_axis, 'Serie3');
  4709. $dataSet->setSerieDescription('Serie1', get_lang('Score'));
  4710. $dataSet->setSerieDescription('Serie2', get_lang('MyResults'));
  4711. $dataSet->setAbscissa('Serie3');
  4712. $dataSet->setXAxisName(get_lang('Score'));
  4713. $dataSet->normalize(100, "%");
  4714. $dataSet->loadPalette(api_get_path(SYS_CODE_PATH) . 'palettes/pchart/default.color', true);
  4715. // Cache definition
  4716. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  4717. $myCache = new pCache(array('CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)));
  4718. $chartHash = $myCache->getHash($dataSet);
  4719. if ($myCache->isInCache($chartHash)) {
  4720. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4721. $myCache->saveFromCache($chartHash, $imgPath);
  4722. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4723. } else {
  4724. /* Create the pChart object */
  4725. $widthSize = 480;
  4726. $heightSize = 250;
  4727. $fontSize = 8;
  4728. $myPicture = new pImage($widthSize, $heightSize, $dataSet);
  4729. /* Turn of Antialiasing */
  4730. $myPicture->Antialias = false;
  4731. /* Add a border to the picture */
  4732. $myPicture->drawRectangle(0, 0, $widthSize - 1, $heightSize - 1, array('R' => 0, 'G' => 0, 'B' => 0));
  4733. /* Set the default font */
  4734. $myPicture->setFontProperties(array('FontName' => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf', 'FontSize' => 10));
  4735. /* Write the chart title */
  4736. $myPicture->drawText(
  4737. 250,
  4738. 20,
  4739. $exercise_title,
  4740. array(
  4741. 'FontSize' => 12,
  4742. 'Align' => TEXT_ALIGN_BOTTOMMIDDLE
  4743. )
  4744. );
  4745. /* Define the chart area */
  4746. $myPicture->setGraphArea(50, 50, $widthSize - 20, $heightSize - 30);
  4747. /* Draw the scale */
  4748. $scaleSettings = array(
  4749. 'GridR' => 200,
  4750. 'GridG' => 200,
  4751. 'GridB' => 200,
  4752. 'DrawSubTicks' => true,
  4753. 'CycleBackground' => true,
  4754. 'Mode' => SCALE_MODE_MANUAL,
  4755. 'ManualScale' => array(
  4756. '0' => array(
  4757. 'Min' => 0,
  4758. 'Max' => 100
  4759. )
  4760. )
  4761. );
  4762. $myPicture->drawScale($scaleSettings);
  4763. /* Turn on shadow computing */
  4764. $myPicture->setShadow(true, array('X' => 1, 'Y' => 1, 'R' => 0, 'G' => 0, 'B' => 0, 'Alpha' => 10));
  4765. /* Draw the chart */
  4766. $myPicture->setShadow(true, array('X' => 1, 'Y' => 1, 'R' => 0, 'G' => 0, 'B' => 0, 'Alpha' => 10));
  4767. $settings = array(
  4768. 'DisplayValues' => true,
  4769. 'DisplaySize' => $fontSize,
  4770. 'DisplayR' => 0,
  4771. 'DisplayG' => 0,
  4772. 'DisplayB' => 0,
  4773. 'DisplayOrientation' => ORIENTATION_HORIZONTAL,
  4774. 'Gradient' => false,
  4775. 'Surrounding' => 30,
  4776. 'InnerSurrounding' => 25
  4777. );
  4778. $myPicture->drawStackedBarChart($settings);
  4779. $legendSettings = array(
  4780. 'Mode' => LEGEND_HORIZONTAL,
  4781. 'Style' => LEGEND_NOBORDER,
  4782. );
  4783. $myPicture->drawLegend($widthSize / 2, 30, $legendSettings);
  4784. /* Write and save into cache */
  4785. $myCache->writeToCache($chartHash, $myPicture);
  4786. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4787. $myCache->saveFromCache($chartHash, $imgPath);
  4788. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4789. }
  4790. return $imgPath;
  4791. }
  4792. /**
  4793. * @param FormValidator $form
  4794. * @return mixed
  4795. */
  4796. public static function setUserSearchForm($form)
  4797. {
  4798. global $_configuration;
  4799. $form->addElement('text', 'keyword', get_lang('Keyword'));
  4800. $form->addElement(
  4801. 'select',
  4802. 'active',
  4803. get_lang('Status'),
  4804. array(1 => get_lang('Active'), 0 => get_lang('Inactive'))
  4805. );
  4806. $form->addElement(
  4807. 'select',
  4808. 'sleeping_days',
  4809. get_lang('InactiveDays'),
  4810. array(
  4811. '',
  4812. 1 => 1,
  4813. 5 => 5,
  4814. 15 => 15,
  4815. 30 => 30,
  4816. 60 => 60,
  4817. 90 => 90,
  4818. 120 => 120,
  4819. )
  4820. );
  4821. $form->addButtonSearch(get_lang('Search'));
  4822. return $form;
  4823. }
  4824. /**
  4825. * Get the progress of a exercise
  4826. * @param int $sessionId The session ID (session.id)
  4827. * @param int $courseId The course ID (course.id)
  4828. * @param int $exerciseId The quiz ID (c_quiz.id)
  4829. * @param int $answer The answer status (0 = incorrect, 1 = correct, 2 = both)
  4830. * @param array $options An array of options you can pass to the query (limit, where and order)
  4831. * @return array An array with the data of exercise(s) progress
  4832. */
  4833. public static function get_exercise_progress(
  4834. $sessionId = 0,
  4835. $courseId = 0,
  4836. $exerciseId = 0,
  4837. $date_from = null,
  4838. $date_to = null,
  4839. $options = array()
  4840. ) {
  4841. $sessionId = intval($sessionId);
  4842. $courseId = intval($courseId);
  4843. $exerciseId = intval($exerciseId);
  4844. $date_from = Database::escape_string($date_from);
  4845. $date_to = Database::escape_string($date_to);
  4846. /*
  4847. * This method gets the data by blocks, as previous attempts at one single
  4848. * query made it take ages. The logic of query division is described below
  4849. */
  4850. // Get tables names
  4851. $tuser = Database::get_main_table(TABLE_MAIN_USER);
  4852. $tquiz = Database::get_course_table(TABLE_QUIZ_TEST);
  4853. $tquiz_answer = Database::get_course_table(TABLE_QUIZ_ANSWER);
  4854. $tquiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  4855. $tquiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  4856. $ttrack_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  4857. $ttrack_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  4858. $sessions = array();
  4859. $courses = array();
  4860. // if session ID is defined but course ID is empty, get all the courses
  4861. // from that session
  4862. if (!empty($sessionId) && empty($courseId)) {
  4863. // $courses is an array of course int id as index and course details hash as value
  4864. $courses = SessionManager::get_course_list_by_session_id($sessionId);
  4865. $sessions[$sessionId] = api_get_session_info($sessionId);
  4866. } elseif (empty($sessionId) && !empty($courseId)) {
  4867. // if, to the contrary, course is defined but not sessions, get the sessions that include this course
  4868. // $sessions is an array like: [0] => ('id' => 3, 'name' => 'Session 35'), [1] => () etc;
  4869. $course = api_get_course_info_by_id($courseId);
  4870. $sessionsTemp = SessionManager::get_session_by_course($courseId);
  4871. $courses[$courseId] = $course;
  4872. foreach ($sessionsTemp as $sessionItem) {
  4873. $sessions[$sessionItem['id']] = $sessionItem;
  4874. }
  4875. } elseif (!empty($courseId) && !empty($sessionId)) {
  4876. //none is empty
  4877. $course = api_get_course_info_by_id($courseId);
  4878. $courses[$courseId] = array($course['code']);
  4879. $courses[$courseId]['code'] = $course['code'];
  4880. $sessions[$sessionId] = api_get_session_info($sessionId);
  4881. } else {
  4882. //both are empty, not enough data, return an empty array
  4883. return array();
  4884. }
  4885. // Now we have two arrays of courses and sessions with enough data to proceed
  4886. // If no course could be found, we shouldn't return anything.
  4887. // Sessions can be empty (then we only return the pure-course-context results)
  4888. if (count($courses) < 1) {
  4889. return array();
  4890. }
  4891. $data = array();
  4892. // The following loop is less expensive than what it seems:
  4893. // - if a course was defined, then we only loop through sessions
  4894. // - if a session was defined, then we only loop through courses
  4895. // - if a session and a course were defined, then we only loop once
  4896. foreach ($courses as $courseIdx => $courseData) {
  4897. $where = '';
  4898. $whereParams = array();
  4899. $whereSessionParams = '';
  4900. if (count($sessions > 0)) {
  4901. foreach ($sessions as $sessionIdx => $sessionData) {
  4902. if (!empty($sessionIdx)) {
  4903. $whereSessionParams .= $sessionIdx.',';
  4904. }
  4905. }
  4906. $whereSessionParams = substr($whereSessionParams,0,-1);
  4907. }
  4908. if (!empty($exerciseId)) {
  4909. $exerciseId = intval($exerciseId);
  4910. $where .= ' AND q.id = %d ';
  4911. $whereParams[] = $exerciseId;
  4912. }
  4913. /*
  4914. * This feature has been disabled for now, to avoid having to
  4915. * join two very large tables
  4916. //2 = show all questions (wrong and correct answered)
  4917. if ($answer != 2) {
  4918. $answer = intval($answer);
  4919. //$where .= ' AND qa.correct = %d';
  4920. //$whereParams[] = $answer;
  4921. }
  4922. */
  4923. $limit = '';
  4924. if (!empty($options['limit'])) {
  4925. $limit = " LIMIT ".$options['limit'];
  4926. }
  4927. if (!empty($options['where'])) {
  4928. $where .= ' AND '.Database::escape_string($options['where']);
  4929. }
  4930. $order = '';
  4931. if (!empty($options['order'])) {
  4932. $order = " ORDER BY ".$options['order'];
  4933. }
  4934. if (!empty($date_to) && !empty($date_from)) {
  4935. $where .= sprintf(" AND (te.start_date BETWEEN '%s 00:00:00' AND '%s 23:59:59')", $date_from, $date_to);
  4936. }
  4937. $sql = "SELECT
  4938. te.session_id,
  4939. ta.id as attempt_id,
  4940. te.exe_user_id as user_id,
  4941. te.exe_id as exercise_attempt_id,
  4942. ta.question_id,
  4943. ta.answer as answer_id,
  4944. ta.tms as time,
  4945. te.exe_exo_id as quiz_id,
  4946. CONCAT ('c', q.c_id, '_e', q.id) as exercise_id,
  4947. q.title as quiz_title,
  4948. qq.description as description
  4949. FROM $ttrack_exercises te
  4950. INNER JOIN $ttrack_attempt ta ON ta.exe_id = te.exe_id
  4951. INNER JOIN $tquiz q ON q.id = te.exe_exo_id
  4952. INNER JOIN $tquiz_rel_question rq ON rq.exercice_id = q.id AND rq.c_id = q.c_id
  4953. INNER JOIN $tquiz_question qq
  4954. ON
  4955. qq.id = rq.question_id AND
  4956. qq.c_id = rq.c_id AND
  4957. qq.position = rq.question_order AND
  4958. ta.question_id = rq.question_id
  4959. WHERE
  4960. te.c_id = $courseIdx ".(empty($whereSessionParams)?'':"AND te.session_id IN ($whereSessionParams)")."
  4961. AND q.c_id = $courseIdx
  4962. $where $order $limit";
  4963. $sql_query = vsprintf($sql, $whereParams);
  4964. // Now browse through the results and get the data
  4965. $rs = Database::query($sql_query);
  4966. $userIds = array();
  4967. $questionIds = array();
  4968. $answerIds = array();
  4969. while ($row = Database::fetch_array($rs)) {
  4970. //only show if exercise is visible
  4971. if (api_get_item_visibility($courseData, 'quiz', $row['exercise_id'])) {
  4972. $userIds[$row['user_id']] = $row['user_id'];
  4973. $questionIds[$row['question_id']] = $row['question_id'];
  4974. $answerIds[$row['question_id']][$row['answer_id']] = $row['answer_id'];
  4975. $row['session'] = $sessions[$row['session_id']];
  4976. $data[] = $row;
  4977. }
  4978. }
  4979. // Now fill questions data. Query all questions and answers for this test to avoid
  4980. $sqlQuestions = "SELECT tq.c_id, tq.id as question_id, tq.question, tqa.id_auto,
  4981. tqa.answer, tqa.correct, tq.position, tqa.id_auto as answer_id
  4982. FROM $tquiz_question tq, $tquiz_answer tqa
  4983. WHERE
  4984. tqa.question_id = tq.id AND
  4985. tqa.c_id = tq.c_id AND
  4986. tq.c_id = $courseIdx AND
  4987. tq.id IN (".implode(',', $questionIds).")";
  4988. $resQuestions = Database::query($sqlQuestions);
  4989. $answer = array();
  4990. $question = array();
  4991. while ($rowQuestion = Database::fetch_assoc($resQuestions)) {
  4992. $questionId = $rowQuestion['question_id'];
  4993. $answerId = $rowQuestion['answer_id'];
  4994. $answer[$questionId][$answerId] = array(
  4995. 'position' => $rowQuestion['position'],
  4996. 'question' => $rowQuestion['question'],
  4997. 'answer' => $rowQuestion['answer'],
  4998. 'correct' => $rowQuestion['correct']
  4999. );
  5000. $question[$questionId]['question'] = $rowQuestion['question'];
  5001. }
  5002. // Now fill users data
  5003. $sqlUsers = "SELECT user_id, username, lastname, firstname
  5004. FROM $tuser
  5005. WHERE user_id IN (".implode(',',$userIds).")";
  5006. $resUsers = Database::query($sqlUsers);
  5007. while ($rowUser = Database::fetch_assoc($resUsers)) {
  5008. $users[$rowUser['user_id']] = $rowUser;
  5009. }
  5010. foreach ($data as $id => $row) {
  5011. $rowQuestId = $row['question_id'];
  5012. $rowAnsId = $row['answer_id'];
  5013. $data[$id]['session'] = $sessions[$row['session_id']]['name'];
  5014. $data[$id]['firstname'] = $users[$row['user_id']]['firstname'];
  5015. $data[$id]['lastname'] = $users[$row['user_id']]['lastname'];
  5016. $data[$id]['username'] = $users[$row['user_id']]['username'];
  5017. $data[$id]['answer'] = $answer[$rowQuestId][$rowAnsId]['answer'];
  5018. $data[$id]['correct'] = ($answer[$rowQuestId][$rowAnsId]['correct'] == 0 ? get_lang('No') : get_lang('Yes'));
  5019. $data[$id]['question'] = $question[$rowQuestId]['question'];
  5020. $data[$id]['question_id'] = $rowQuestId;
  5021. $data[$id]['description'] = $row['description'];
  5022. }
  5023. /*
  5024. The minimum expected array structure at the end is:
  5025. attempt_id,
  5026. session name,
  5027. exercise_id,
  5028. quiz_title,
  5029. username,
  5030. lastname,
  5031. firstname,
  5032. time,
  5033. question_id,
  5034. question,
  5035. answer,
  5036. */
  5037. }
  5038. return $data;
  5039. }
  5040. }
  5041. /**
  5042. * @todo move into a proper file
  5043. * @package chamilo.tracking
  5044. */
  5045. class TrackingCourseLog
  5046. {
  5047. /**
  5048. * @return mixed
  5049. */
  5050. public static function count_item_resources()
  5051. {
  5052. $session_id = api_get_session_id();
  5053. $course_id = api_get_course_int_id();
  5054. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  5055. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  5056. $sql = "SELECT count(tool) AS total_number_of_items
  5057. FROM $table_item_property track_resource, $table_user user
  5058. WHERE
  5059. track_resource.c_id = $course_id AND
  5060. track_resource.insert_user_id = user.user_id AND
  5061. session_id " .(empty($session_id) ? ' IS NULL ' : " = $session_id ");
  5062. if (isset($_GET['keyword'])) {
  5063. $keyword = Database::escape_string(trim($_GET['keyword']));
  5064. $sql .= " AND (
  5065. user.username LIKE '%".$keyword."%' OR
  5066. lastedit_type LIKE '%".$keyword."%' OR
  5067. tool LIKE '%".$keyword."%'
  5068. )";
  5069. }
  5070. $sql .= " AND tool IN (
  5071. 'document',
  5072. 'learnpath',
  5073. 'quiz',
  5074. 'glossary',
  5075. 'link',
  5076. 'course_description',
  5077. 'announcement',
  5078. 'thematic',
  5079. 'thematic_advance',
  5080. 'thematic_plan'
  5081. )";
  5082. $res = Database::query($sql);
  5083. $obj = Database::fetch_object($res);
  5084. return $obj->total_number_of_items;
  5085. }
  5086. /**
  5087. * @param $from
  5088. * @param $number_of_items
  5089. * @param $column
  5090. * @param $direction
  5091. * @return array
  5092. */
  5093. public static function get_item_resources_data($from, $number_of_items, $column, $direction)
  5094. {
  5095. $session_id = api_get_session_id();
  5096. $course_id = api_get_course_int_id();
  5097. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  5098. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  5099. $table_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  5100. $session_id = intval($session_id);
  5101. $sql = "SELECT
  5102. tool as col0,
  5103. lastedit_type as col1,
  5104. ref as ref,
  5105. user.username as col3,
  5106. insert_date as col5,
  5107. visibility as col6,
  5108. user.user_id as user_id
  5109. FROM $table_item_property track_resource, $table_user user
  5110. WHERE
  5111. track_resource.c_id = $course_id AND
  5112. track_resource.insert_user_id = user.user_id AND
  5113. session_id " .(empty($session_id) ? ' IS NULL ' : " = $session_id ");
  5114. if (isset($_GET['keyword'])) {
  5115. $keyword = Database::escape_string(trim($_GET['keyword']));
  5116. $sql .= " AND (
  5117. user.username LIKE '%".$keyword."%' OR
  5118. lastedit_type LIKE '%".$keyword."%' OR
  5119. tool LIKE '%".$keyword."%'
  5120. ) ";
  5121. }
  5122. $sql .= " AND tool IN (
  5123. 'document',
  5124. 'learnpath',
  5125. 'quiz',
  5126. 'glossary',
  5127. 'link',
  5128. 'course_description',
  5129. 'announcement',
  5130. 'thematic',
  5131. 'thematic_advance',
  5132. 'thematic_plan'
  5133. )";
  5134. if ($column == 0) {
  5135. $column = '0';
  5136. }
  5137. if ($column != '' && $direction != '') {
  5138. if ($column != 2 && $column != 4) {
  5139. $sql .= " ORDER BY col$column $direction";
  5140. }
  5141. } else {
  5142. $sql .= " ORDER BY col5 DESC ";
  5143. }
  5144. $from = intval($from);
  5145. $number_of_items = intval($number_of_items);
  5146. $sql .= " LIMIT $from, $number_of_items ";
  5147. $res = Database::query($sql);
  5148. $resources = array();
  5149. $thematic_tools = array('thematic', 'thematic_advance', 'thematic_plan');
  5150. while ($row = Database::fetch_array($res)) {
  5151. $ref = $row['ref'];
  5152. $table_name = TrackingCourseLog::get_tool_name_table($row['col0']);
  5153. $table_tool = Database :: get_course_table($table_name['table_name']);
  5154. $id = $table_name['id_tool'];
  5155. $recorset = false;
  5156. if (in_array($row['col0'], array('thematic_plan', 'thematic_advance'))) {
  5157. $tbl_thematic = Database :: get_course_table(TABLE_THEMATIC);
  5158. $sql = "SELECT thematic_id FROM $table_tool
  5159. WHERE c_id = $course_id AND id = $ref";
  5160. $rs_thematic = Database::query($sql);
  5161. if (Database::num_rows($rs_thematic)) {
  5162. $row_thematic = Database::fetch_array($rs_thematic);
  5163. $thematic_id = $row_thematic['thematic_id'];
  5164. $sql = "SELECT session.id, session.name, user.username
  5165. FROM $tbl_thematic t, $table_session session, $table_user user
  5166. WHERE
  5167. t.c_id = $course_id AND
  5168. t.session_id = session.id AND
  5169. session.id_coach = user.user_id AND
  5170. t.id = $thematic_id";
  5171. $recorset = Database::query($sql);
  5172. }
  5173. } else {
  5174. $sql = "SELECT session.id, session.name, user.username
  5175. FROM $table_tool tool, $table_session session, $table_user user
  5176. WHERE
  5177. tool.c_id = $course_id AND
  5178. tool.session_id = session.id AND
  5179. session.id_coach = user.user_id AND
  5180. tool.$id = $ref";
  5181. $recorset = Database::query($sql);
  5182. }
  5183. if (!empty($recorset)) {
  5184. $obj = Database::fetch_object($recorset);
  5185. $name_session = '';
  5186. $coach_name = '';
  5187. if (!empty($obj)) {
  5188. $name_session = $obj->name;
  5189. $coach_name = $obj->username;
  5190. }
  5191. $url_tool = api_get_path(WEB_CODE_PATH).$table_name['link_tool'];
  5192. $row[0] = '';
  5193. if ($row['col6'] != 2) {
  5194. if (in_array($row['col0'], $thematic_tools)) {
  5195. $exp_thematic_tool = explode('_', $row['col0']);
  5196. $thematic_tool_title = '';
  5197. if (is_array($exp_thematic_tool)) {
  5198. foreach ($exp_thematic_tool as $exp) {
  5199. $thematic_tool_title .= api_ucfirst($exp);
  5200. }
  5201. } else {
  5202. $thematic_tool_title = api_ucfirst($row['col0']);
  5203. }
  5204. $row[0] = '<a href="'.$url_tool.'?'.api_get_cidreq().'&action=thematic_details">'.get_lang($thematic_tool_title).'</a>';
  5205. } else {
  5206. $row[0] = '<a href="'.$url_tool.'?'.api_get_cidreq().'">'.get_lang('Tool'.api_ucfirst($row['col0'])).'</a>';
  5207. }
  5208. } else {
  5209. $row[0] = api_ucfirst($row['col0']);
  5210. }
  5211. $row[1] = get_lang($row[1]);
  5212. $row[6] = api_convert_and_format_date($row['col5'], null, date_default_timezone_get());
  5213. $row[5] = '';
  5214. //@todo Improve this code please
  5215. switch ($table_name['table_name']) {
  5216. case 'document' :
  5217. $sql = "SELECT tool.title as title FROM $table_tool tool
  5218. WHERE c_id = $course_id AND id = $ref";
  5219. $rs_document = Database::query($sql);
  5220. $obj_document = Database::fetch_object($rs_document);
  5221. $row[5] = $obj_document->title;
  5222. break;
  5223. case 'announcement':
  5224. $sql = "SELECT title FROM $table_tool
  5225. WHERE c_id = $course_id AND id = $ref";
  5226. $rs_document = Database::query($sql);
  5227. $obj_document = Database::fetch_object($rs_document);
  5228. if ($obj_document) {
  5229. $row[5] = $obj_document->title;
  5230. }
  5231. break;
  5232. case 'glossary':
  5233. $sql = "SELECT name FROM $table_tool
  5234. WHERE c_id = $course_id AND glossary_id = $ref";
  5235. $rs_document = Database::query($sql);
  5236. $obj_document = Database::fetch_object($rs_document);
  5237. if ($obj_document) {
  5238. $row[5] = $obj_document->name;
  5239. }
  5240. break;
  5241. case 'lp':
  5242. $sql = "SELECT name
  5243. FROM $table_tool WHERE c_id = $course_id AND id = $ref";
  5244. $rs_document = Database::query($sql);
  5245. $obj_document = Database::fetch_object($rs_document);
  5246. $row[5] = $obj_document->name;
  5247. break;
  5248. case 'quiz':
  5249. $sql = "SELECT title FROM $table_tool
  5250. WHERE c_id = $course_id AND id = $ref";
  5251. $rs_document = Database::query($sql);
  5252. $obj_document = Database::fetch_object($rs_document);
  5253. if ($obj_document) {
  5254. $row[5] = $obj_document->title;
  5255. }
  5256. break;
  5257. case 'course_description':
  5258. $sql = "SELECT title FROM $table_tool
  5259. WHERE c_id = $course_id AND id = $ref";
  5260. $rs_document = Database::query($sql);
  5261. $obj_document = Database::fetch_object($rs_document);
  5262. if ($obj_document) {
  5263. $row[5] = $obj_document->title;
  5264. }
  5265. break;
  5266. case 'thematic':
  5267. $rs = Database::query("SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref");
  5268. if (Database::num_rows($rs) > 0) {
  5269. $obj = Database::fetch_object($rs);
  5270. $row[5] = $obj->title;
  5271. }
  5272. break;
  5273. case 'thematic_advance':
  5274. $rs = Database::query("SELECT content FROM $table_tool WHERE c_id = $course_id AND id = $ref");
  5275. if (Database::num_rows($rs) > 0) {
  5276. $obj = Database::fetch_object($rs);
  5277. $row[5] = $obj->content;
  5278. }
  5279. break;
  5280. case 'thematic_plan':
  5281. $rs = Database::query("SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref");
  5282. if (Database::num_rows($rs) > 0) {
  5283. $obj = Database::fetch_object($rs);
  5284. $row[5] = $obj->title;
  5285. }
  5286. break;
  5287. default:
  5288. break;
  5289. }
  5290. $row2 = $name_session;
  5291. if (!empty($coach_name)) {
  5292. $row2 .= '<br />'.get_lang('Coach').': '.$coach_name;
  5293. }
  5294. $row[2] = $row2;
  5295. if (!empty($row['col3'])) {
  5296. $userInfo = api_get_user_info($row['user_id']);
  5297. $row['col3'] = Display::url(
  5298. $row['col3'],
  5299. $userInfo['profile_url']
  5300. );
  5301. $row[3] = $row['col3'];
  5302. $ip = TrackingUserLog::get_ip_from_user_event($row['user_id'], $row['col5'], true);
  5303. if (empty($ip)) {
  5304. $ip = get_lang('Unknown');
  5305. }
  5306. $row[4] = $ip;
  5307. }
  5308. $resources[] = $row;
  5309. }
  5310. }
  5311. return $resources;
  5312. }
  5313. /**
  5314. * @param string $tool
  5315. *
  5316. * @return array
  5317. */
  5318. public static function get_tool_name_table($tool)
  5319. {
  5320. switch ($tool) {
  5321. case 'document':
  5322. $table_name = TABLE_DOCUMENT;
  5323. $link_tool = 'document/document.php';
  5324. $id_tool = 'id';
  5325. break;
  5326. case 'learnpath':
  5327. $table_name = TABLE_LP_MAIN;
  5328. $link_tool = 'newscorm/lp_controller.php';
  5329. $id_tool = 'id';
  5330. break;
  5331. case 'quiz':
  5332. $table_name = TABLE_QUIZ_TEST;
  5333. $link_tool = 'exercice/exercice.php';
  5334. $id_tool = 'id';
  5335. break;
  5336. case 'glossary':
  5337. $table_name = TABLE_GLOSSARY;
  5338. $link_tool = 'glossary/index.php';
  5339. $id_tool = 'glossary_id';
  5340. break;
  5341. case 'link':
  5342. $table_name = TABLE_LINK;
  5343. $link_tool = 'link/link.php';
  5344. $id_tool = 'id';
  5345. break;
  5346. case 'course_description':
  5347. $table_name = TABLE_COURSE_DESCRIPTION;
  5348. $link_tool = 'course_description/';
  5349. $id_tool = 'id';
  5350. break;
  5351. case 'announcement':
  5352. $table_name = TABLE_ANNOUNCEMENT;
  5353. $link_tool = 'announcements/announcements.php';
  5354. $id_tool = 'id';
  5355. break;
  5356. case 'thematic':
  5357. $table_name = TABLE_THEMATIC;
  5358. $link_tool = 'course_progress/index.php';
  5359. $id_tool = 'id';
  5360. break;
  5361. case 'thematic_advance':
  5362. $table_name = TABLE_THEMATIC_ADVANCE;
  5363. $link_tool = 'course_progress/index.php';
  5364. $id_tool = 'id';
  5365. break;
  5366. case 'thematic_plan':
  5367. $table_name = TABLE_THEMATIC_PLAN;
  5368. $link_tool = 'course_progress/index.php';
  5369. $id_tool = 'id';
  5370. break;
  5371. default:
  5372. $table_name = $tool;
  5373. break;
  5374. }
  5375. return array(
  5376. 'table_name' => $table_name,
  5377. 'link_tool' => $link_tool,
  5378. 'id_tool' => $id_tool
  5379. );
  5380. }
  5381. public static function display_additional_profile_fields()
  5382. {
  5383. // getting all the extra profile fields that are defined by the platform administrator
  5384. $extra_fields = UserManager :: get_extra_fields(0,50,5,'ASC');
  5385. // creating the form
  5386. $return = '<form action="courseLog.php" method="get" name="additional_profile_field_form" id="additional_profile_field_form">';
  5387. // the select field with the additional user profile fields (= this is where we select the field of which we want to see
  5388. // the information the users have entered or selected.
  5389. $return .= '<select name="additional_profile_field">';
  5390. $return .= '<option value="-">'.get_lang('SelectFieldToAdd').'</option>';
  5391. $extra_fields_to_show = 0;
  5392. foreach ($extra_fields as $key=>$field) {
  5393. // show only extra fields that are visible + and can be filtered, added by J.Montoya
  5394. if ($field[6]==1 && $field[8] == 1) {
  5395. if (isset($_GET['additional_profile_field']) && $field[0] == $_GET['additional_profile_field'] ) {
  5396. $selected = 'selected="selected"';
  5397. } else {
  5398. $selected = '';
  5399. }
  5400. $extra_fields_to_show++;
  5401. $return .= '<option value="'.$field[0].'" '.$selected.'>'.$field[3].'</option>';
  5402. }
  5403. }
  5404. $return .= '</select>';
  5405. // the form elements for the $_GET parameters (because the form is passed through GET
  5406. foreach ($_GET as $key=>$value){
  5407. if ($key <> 'additional_profile_field') {
  5408. $return .= '<input type="hidden" name="'.Security::remove_XSS($key).'" value="'.Security::remove_XSS($value).'" />';
  5409. }
  5410. }
  5411. // the submit button
  5412. $return .= '<button class="save" type="submit">'.get_lang('AddAdditionalProfileField').'</button>';
  5413. $return .= '</form>';
  5414. if ($extra_fields_to_show > 0) {
  5415. return $return;
  5416. } else {
  5417. return '';
  5418. }
  5419. }
  5420. /**
  5421. * This function gets all the information of a certrain ($field_id)
  5422. * additional profile field for a specific list of users is more efficent
  5423. * than get_addtional_profile_information_of_field() function
  5424. * It gets the information of all the users so that it can be displayed
  5425. * in the sortable table or in the csv or xls export
  5426. *
  5427. * @author Julio Montoya <gugli100@gmail.com>
  5428. * @param int field id
  5429. * @param array list of user ids
  5430. * @return array
  5431. * @since Nov 2009
  5432. * @version 1.8.6.2
  5433. */
  5434. public static function get_addtional_profile_information_of_field_by_user($field_id, $users)
  5435. {
  5436. // Database table definition
  5437. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  5438. $table_user_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  5439. $extraField = Database::get_main_table(TABLE_EXTRA_FIELD);
  5440. $result_extra_field = UserManager::get_extra_field_information($field_id);
  5441. if (!empty($users)) {
  5442. if ($result_extra_field['field_type'] == UserManager::USER_FIELD_TYPE_TAG ) {
  5443. foreach($users as $user_id) {
  5444. $user_result = UserManager::get_user_tags($user_id, $field_id);
  5445. $tag_list = array();
  5446. foreach($user_result as $item) {
  5447. $tag_list[] = $item['tag'];
  5448. }
  5449. $return[$user_id][] = implode(', ',$tag_list);
  5450. }
  5451. } else {
  5452. $new_user_array = array();
  5453. foreach ($users as $user_id) {
  5454. $new_user_array[]= "'".$user_id."'";
  5455. }
  5456. $users = implode(',',$new_user_array);
  5457. $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
  5458. // Selecting only the necessary information NOT ALL the user list
  5459. $sql = "SELECT user.user_id, v.value
  5460. FROM $table_user user
  5461. INNER JOIN $table_user_field_values v
  5462. ON (user.user_id = v.item_id)
  5463. INNER JOIN $extraField f
  5464. ON (f.id = v.field_id)
  5465. WHERE
  5466. f.extra_field_type = $extraFieldType AND
  5467. v.field_id=".intval($field_id)." AND
  5468. user.user_id IN ($users)";
  5469. $result = Database::query($sql);
  5470. while($row = Database::fetch_array($result)) {
  5471. // get option value for field type double select by id
  5472. if (!empty($row['value'])) {
  5473. if ($result_extra_field['field_type'] ==
  5474. ExtraField::FIELD_TYPE_DOUBLE_SELECT
  5475. ) {
  5476. $id_double_select = explode(';', $row['value']);
  5477. if (is_array($id_double_select)) {
  5478. $value1 = $result_extra_field['options'][$id_double_select[0]]['option_value'];
  5479. $value2 = $result_extra_field['options'][$id_double_select[1]]['option_value'];
  5480. $row['value'] = ($value1.';'.$value2);
  5481. }
  5482. }
  5483. }
  5484. // get other value from extra field
  5485. $return[$row['user_id']][] = $row['value'];
  5486. }
  5487. }
  5488. }
  5489. return $return;
  5490. }
  5491. /**
  5492. * count the number of students in this course (used for SortableTable)
  5493. * Deprecated
  5494. */
  5495. public function count_student_in_course()
  5496. {
  5497. global $nbStudents;
  5498. return $nbStudents;
  5499. }
  5500. public function sort_users($a, $b)
  5501. {
  5502. return strcmp(trim(api_strtolower($a[$_SESSION['tracking_column']])), trim(api_strtolower($b[$_SESSION['tracking_column']])));
  5503. }
  5504. public function sort_users_desc($a, $b)
  5505. {
  5506. return strcmp( trim(api_strtolower($b[$_SESSION['tracking_column']])), trim(api_strtolower($a[$_SESSION['tracking_column']])));
  5507. }
  5508. /**
  5509. * Get number of users for sortable with pagination
  5510. * @return int
  5511. */
  5512. public static function get_number_of_users()
  5513. {
  5514. global $user_ids;
  5515. return count($user_ids);
  5516. }
  5517. /**
  5518. * Get data for users list in sortable with pagination
  5519. * @param $from
  5520. * @param $number_of_items
  5521. * @param $column
  5522. * @param $direction
  5523. * @param $includeInvitedUsers boolean Whether include the invited users
  5524. * @return array
  5525. */
  5526. public static function get_user_data($from, $number_of_items, $column, $direction, $includeInvitedUsers = false)
  5527. {
  5528. global $user_ids, $course_code, $additional_user_profile_info, $export_csv, $is_western_name_order, $csv_content, $session_id;
  5529. $course_code = Database::escape_string($course_code);
  5530. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  5531. $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  5532. $access_url_id = api_get_current_access_url_id();
  5533. // get all users data from a course for sortable with limit
  5534. if (is_array($user_ids)) {
  5535. $user_ids = array_map('intval', $user_ids);
  5536. $condition_user = " WHERE user.user_id IN (".implode(',',$user_ids).") ";
  5537. } else {
  5538. $user_ids = intval($user_ids);
  5539. $condition_user = " WHERE user.user_id = $user_ids ";
  5540. }
  5541. if (!empty($_GET['user_keyword'])) {
  5542. $keyword = trim(Database::escape_string($_GET['user_keyword']));
  5543. $condition_user .= " AND (
  5544. user.firstname LIKE '%".$keyword."%' OR
  5545. user.lastname LIKE '%".$keyword."%' OR
  5546. user.username LIKE '%".$keyword."%' OR
  5547. user.email LIKE '%".$keyword."%'
  5548. ) ";
  5549. }
  5550. $url_table = null;
  5551. $url_condition = null;
  5552. if (api_is_multiple_url_enabled()) {
  5553. $url_table = ", ".$tbl_url_rel_user." as url_users";
  5554. $url_condition = " AND user.user_id = url_users.user_id AND access_url_id='$access_url_id'";
  5555. }
  5556. $invitedUsersCondition = '';
  5557. if (!$includeInvitedUsers) {
  5558. $invitedUsersCondition = " AND user.status != " . INVITEE;
  5559. }
  5560. $sql = "SELECT user.user_id as user_id,
  5561. user.official_code as col0,
  5562. user.lastname as col1,
  5563. user.firstname as col2,
  5564. user.username as col3
  5565. FROM $tbl_user as user $url_table
  5566. $condition_user $url_condition $invitedUsersCondition";
  5567. if (!in_array($direction, array('ASC','DESC'))) {
  5568. $direction = 'ASC';
  5569. }
  5570. $column = intval($column);
  5571. $from = intval($from);
  5572. $number_of_items = intval($number_of_items);
  5573. $sql .= " ORDER BY col$column $direction ";
  5574. $sql .= " LIMIT $from,$number_of_items";
  5575. $res = Database::query($sql);
  5576. $users = array();
  5577. $course_info = api_get_course_info($course_code);
  5578. $total_surveys = 0;
  5579. $total_exercises = ExerciseLib::get_all_exercises(
  5580. $course_info,
  5581. $session_id,
  5582. false,
  5583. null,
  5584. false,
  5585. 3
  5586. );
  5587. if (empty($session_id)) {
  5588. $survey_user_list = array();
  5589. $survey_list = SurveyManager::get_surveys($course_code, $session_id);
  5590. $total_surveys = count($survey_list);
  5591. foreach ($survey_list as $survey) {
  5592. $user_list = SurveyManager::get_people_who_filled_survey(
  5593. $survey['survey_id'],
  5594. false,
  5595. $course_info['real_id']
  5596. );
  5597. foreach ($user_list as $user_id) {
  5598. isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id]++ : $survey_user_list[$user_id] = 1;
  5599. }
  5600. }
  5601. }
  5602. while ($user = Database::fetch_array($res, 'ASSOC')) {
  5603. $courseInfo = api_get_course_info($course_code);
  5604. $courseId = $courseInfo['real_id'];
  5605. $user['official_code'] = $user['col0'];
  5606. $user['lastname'] = $user['col1'];
  5607. $user['firstname'] = $user['col2'];
  5608. $user['username'] = $user['col3'];
  5609. $user['time'] = api_time_to_hms(
  5610. Tracking::get_time_spent_on_the_course(
  5611. $user['user_id'],
  5612. $courseId,
  5613. $session_id
  5614. )
  5615. );
  5616. $avg_student_score = Tracking::get_avg_student_score(
  5617. $user['user_id'],
  5618. $course_code,
  5619. array(),
  5620. $session_id
  5621. );
  5622. $avg_student_progress = Tracking::get_avg_student_progress(
  5623. $user['user_id'],
  5624. $course_code,
  5625. array(),
  5626. $session_id
  5627. );
  5628. if (empty($avg_student_progress)) {
  5629. $avg_student_progress = 0;
  5630. }
  5631. $user['average_progress'] = $avg_student_progress.'%';
  5632. $total_user_exercise = Tracking::get_exercise_student_progress(
  5633. $total_exercises,
  5634. $user['user_id'],
  5635. $courseId,
  5636. $session_id
  5637. );
  5638. $user['exercise_progress'] = $total_user_exercise;
  5639. $total_user_exercise = Tracking::get_exercise_student_average_best_attempt(
  5640. $total_exercises,
  5641. $user['user_id'],
  5642. $courseId,
  5643. $session_id
  5644. );
  5645. $user['exercise_average_best_attempt'] = $total_user_exercise;
  5646. if (is_numeric($avg_student_score)) {
  5647. $user['student_score'] = $avg_student_score.'%';
  5648. } else {
  5649. $user['student_score'] = $avg_student_score;
  5650. }
  5651. $user['count_assignments'] = Tracking::count_student_assignments(
  5652. $user['user_id'],
  5653. $course_code,
  5654. $session_id
  5655. );
  5656. $user['count_messages'] = Tracking::count_student_messages(
  5657. $user['user_id'],
  5658. $course_code,
  5659. $session_id
  5660. );
  5661. $user['first_connection'] = Tracking::get_first_connection_date_on_the_course(
  5662. $user['user_id'],
  5663. $courseId,
  5664. $session_id
  5665. );
  5666. $user['last_connection'] = Tracking::get_last_connection_date_on_the_course(
  5667. $user['user_id'],
  5668. $courseInfo,
  5669. $session_id
  5670. );
  5671. // we need to display an additional profile field
  5672. $user['additional'] = '';
  5673. if (isset($_GET['additional_profile_field']) && is_numeric($_GET['additional_profile_field'])) {
  5674. if (isset($additional_user_profile_info[$user['user_id']]) &&
  5675. is_array($additional_user_profile_info[$user['user_id']])
  5676. ) {
  5677. $user['additional'] = implode(', ', $additional_user_profile_info[$user['user_id']]);
  5678. }
  5679. }
  5680. if (empty($session_id)) {
  5681. $user['survey'] = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0) .' / '.$total_surveys;
  5682. }
  5683. $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>';
  5684. // store columns in array $users
  5685. $is_western_name_order = api_is_western_name_order();
  5686. $user_row = array();
  5687. $user_row[]= $user['official_code']; //0
  5688. if ($is_western_name_order) {
  5689. $user_row[]= $user['firstname'];
  5690. $user_row[]= $user['lastname'];
  5691. } else {
  5692. $user_row[]= $user['lastname'];
  5693. $user_row[]= $user['firstname'];
  5694. }
  5695. $user_row[]= $user['username'];
  5696. $user_row[]= $user['time'];
  5697. $user_row[]= $user['average_progress'];
  5698. $user_row[]= $user['exercise_progress'];
  5699. $user_row[]= $user['exercise_average_best_attempt'];
  5700. $user_row[]= $user['student_score'];
  5701. $user_row[]= $user['count_assignments'];
  5702. $user_row[]= $user['count_messages'];
  5703. if (empty($session_id)) {
  5704. $user_row[]= $user['survey'];
  5705. }
  5706. $user_row[]= $user['first_connection'];
  5707. $user_row[]= $user['last_connection'];
  5708. if (isset($_GET['additional_profile_field']) && is_numeric($_GET['additional_profile_field'])) {
  5709. $user_row[]= $user['additional'];
  5710. }
  5711. $user_row[]= $user['link'];
  5712. $users[] = $user_row;
  5713. if ($export_csv) {
  5714. if (empty($session_id)) {
  5715. $user_row = array_map('strip_tags', $user_row);
  5716. unset($user_row[14]);
  5717. unset($user_row[15]);
  5718. } else {
  5719. $user_row = array_map('strip_tags', $user_row);
  5720. unset($user_row[13]);
  5721. unset($user_row[14]);
  5722. }
  5723. $csv_content[] = $user_row;
  5724. }
  5725. }
  5726. return $users;
  5727. }
  5728. }
  5729. /**
  5730. * @package chamilo.tracking
  5731. */
  5732. class TrackingUserLog
  5733. {
  5734. /**
  5735. * Displays the number of logins every month for a specific user in a specific course.
  5736. * @param $view
  5737. * @param int $user_id
  5738. * @param int $course_id
  5739. * @param int $session_id
  5740. */
  5741. public function display_login_tracking_info($view, $user_id, $course_id, $session_id = 0)
  5742. {
  5743. $MonthsLong = $GLOBALS['MonthsLong'];
  5744. // protected data
  5745. $user_id = intval($user_id);
  5746. $session_id = intval($session_id);
  5747. $course_id = Database::escape_string($course_id);
  5748. $track_access_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  5749. $tempView = $view;
  5750. if(substr($view,0,1) == '1') {
  5751. $new_view = substr_replace($view,'0',0,1);
  5752. echo "
  5753. <tr>
  5754. <td valign='top'>
  5755. <font color='#0000FF'>-&nbsp;&nbsp;&nbsp;</font>" .
  5756. "<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>]
  5757. </td>
  5758. </tr>
  5759. ";
  5760. echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('LoginsDetails')."<br>";
  5761. $sql = "SELECT UNIX_TIMESTAMP(access_date), count(access_date)
  5762. FROM $track_access_table
  5763. WHERE access_user_id = $user_id
  5764. AND c_id = $course_id
  5765. AND access_session_id = $session_id
  5766. GROUP BY YEAR(access_date),MONTH(access_date)
  5767. ORDER BY YEAR(access_date),MONTH(access_date) ASC";
  5768. echo "<tr><td style='padding-left : 40px;padding-right : 40px;'>";
  5769. $results = getManyResults3Col($sql);
  5770. echo "<table cellpadding='2' cellspacing='1' border='0' align=center>";
  5771. echo "<tr>
  5772. <td class='secLine'>
  5773. ".get_lang('LoginsTitleMonthColumn')."
  5774. </td>
  5775. <td class='secLine'>
  5776. ".get_lang('LoginsTitleCountColumn')."
  5777. </td>
  5778. </tr>";
  5779. $total = 0;
  5780. if (is_array($results)) {
  5781. for($j = 0 ; $j < count($results) ; $j++) {
  5782. echo "<tr>";
  5783. 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>";
  5784. echo "<td valign='top' align='right' class='content'>".$results[$j][1]."</td>";
  5785. echo"</tr>";
  5786. $total = $total + $results[$j][1];
  5787. }
  5788. echo "<tr>";
  5789. echo "<td>".get_lang('Total')."</td>";
  5790. echo "<td align='right' class='content'>".$total."</td>";
  5791. echo"</tr>";
  5792. } else {
  5793. echo "<tr>";
  5794. echo "<td colspan='2'><center>".get_lang('NoResult')."</center></td>";
  5795. echo"</tr>";
  5796. }
  5797. echo "</table>";
  5798. echo "</td></tr>";
  5799. } else {
  5800. $new_view = substr_replace($view,'1',0,1);
  5801. echo "
  5802. <tr>
  5803. <td valign='top'>
  5804. +<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>
  5805. </td>
  5806. </tr>
  5807. ";
  5808. }
  5809. }
  5810. /**
  5811. * Displays the exercise results for a specific user in a specific course.
  5812. * @param string $view
  5813. * @param int $user_id User ID
  5814. * @param string $courseCode Course code
  5815. * @return array
  5816. * @todo remove globals
  5817. */
  5818. public function display_exercise_tracking_info($view, $user_id, $courseCode)
  5819. {
  5820. global $TBL_TRACK_HOTPOTATOES, $TABLECOURSE_EXERCICES, $TABLETRACK_EXERCICES, $dateTimeFormatLong;
  5821. $courseId = api_get_course_int_id($courseCode);
  5822. if(substr($view,1,1) == '1') {
  5823. $new_view = substr_replace($view,'0',1,1);
  5824. echo "<tr>
  5825. <td valign='top'>
  5826. <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>]
  5827. </td>
  5828. </tr>";
  5829. echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('ExercicesDetails')."<br />";
  5830. $sql = "SELECT ce.title, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
  5831. FROM $TABLECOURSE_EXERCICES AS ce , $TABLETRACK_EXERCICES AS te
  5832. WHERE te.c_id = $courseId
  5833. AND te.exe_user_id = ".intval($user_id)."
  5834. AND te.exe_exo_id = ce.id
  5835. ORDER BY ce.title ASC, te.exe_date ASC";
  5836. $hpsql = "SELECT te.exe_name, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
  5837. FROM $TBL_TRACK_HOTPOTATOES AS te
  5838. WHERE te.exe_user_id = '".intval($user_id)."' AND te.c_id = $courseId
  5839. ORDER BY te.c_id ASC, te.exe_date ASC";
  5840. $hpresults = StatsUtils::getManyResultsXCol($hpsql, 4);
  5841. $NoTestRes = 0;
  5842. $NoHPTestRes = 0;
  5843. echo "<tr>\n<td style='padding-left : 40px;padding-right : 40px;'>\n";
  5844. $results = StatsUtils::getManyResultsXCol($sql, 4);
  5845. echo "<table cellpadding='2' cellspacing='1' border='0' align='center'>\n";
  5846. echo "
  5847. <tr bgcolor='#E6E6E6'>
  5848. <td>
  5849. ".get_lang('ExercicesTitleExerciceColumn')."
  5850. </td>
  5851. <td>
  5852. ".get_lang('Date')."
  5853. </td>
  5854. <td>
  5855. ".get_lang('ExercicesTitleScoreColumn')."
  5856. </td>
  5857. </tr>";
  5858. if (is_array($results)) {
  5859. for($i = 0; $i < sizeof($results); $i++) {
  5860. $display_date = api_convert_and_format_date($results[$i][3], null, date_default_timezone_get());
  5861. echo "<tr>\n";
  5862. echo "<td class='content'>".$results[$i][0]."</td>\n";
  5863. echo "<td class='content'>".$display_date."</td>\n";
  5864. echo "<td valign='top' align='right' class='content'>".$results[$i][1]." / ".$results[$i][2]."</td>\n";
  5865. echo "</tr>\n";
  5866. }
  5867. } else {
  5868. // istvan begin
  5869. $NoTestRes = 1;
  5870. }
  5871. // The Result of Tests
  5872. if (is_array($hpresults)) {
  5873. for($i = 0; $i < sizeof($hpresults); $i++) {
  5874. $title = GetQuizName($hpresults[$i][0],'');
  5875. if ($title == '')
  5876. $title = basename($hpresults[$i][0]);
  5877. $display_date = api_convert_and_format_date($hpresults[$i][3], null, date_default_timezone_get());
  5878. ?>
  5879. <tr>
  5880. <td class="content"><?php echo $title; ?></td>
  5881. <td class="content" align="center"><?php echo $display_date; ?></td>
  5882. <td class="content" align="center"><?php echo $hpresults[$i][1]; ?> / <?php echo $hpresults[$i][2]; ?>
  5883. </td>
  5884. </tr>
  5885. <?php
  5886. }
  5887. } else {
  5888. $NoHPTestRes = 1;
  5889. }
  5890. if ($NoTestRes == 1 && $NoHPTestRes == 1) {
  5891. echo "<tr>\n";
  5892. echo "<td colspan='3'><center>".get_lang('NoResult')."</center></td>\n";
  5893. echo "</tr>\n";
  5894. }
  5895. echo "</table>";
  5896. echo "</td>\n</tr>\n";
  5897. } else {
  5898. $new_view = substr_replace($view,'1',1,1);
  5899. echo "
  5900. <tr>
  5901. <td valign='top'>
  5902. +<font color='#0000FF'>&nbsp;&nbsp;</font><a href='".api_get_self()."?uInfo=$user_id&view=".$new_view."' class='specialLink'>".get_lang('ExercicesResults')."</a>
  5903. </td>
  5904. </tr>";
  5905. }
  5906. }
  5907. /**
  5908. * Displays the student publications for a specific user in a specific course.
  5909. * @todo remove globals
  5910. */
  5911. public function display_student_publications_tracking_info($view, $user_id, $course_id)
  5912. {
  5913. global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK;
  5914. $_course = api_get_course_info_by_id($course_id);
  5915. if (substr($view,2,1) == '1') {
  5916. $new_view = substr_replace($view,'0',2,1);
  5917. echo "<tr>
  5918. <td valign='top'>
  5919. <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>]
  5920. </td>
  5921. </tr>";
  5922. echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('WorksDetails')."<br>";
  5923. $sql = "SELECT u.upload_date, w.title, w.author,w.url
  5924. FROM $TABLETRACK_UPLOADS u , $TABLECOURSE_WORK w
  5925. WHERE u.upload_work_id = w.id
  5926. AND u.upload_user_id = '".intval($user_id)."'
  5927. AND u.c_id = '".intval($course_id)."'
  5928. ORDER BY u.upload_date DESC";
  5929. echo "<tr><td style='padding-left : 40px;padding-right : 40px;'>";
  5930. $results = StatsUtils::getManyResultsXCol($sql,4);
  5931. echo "<table cellpadding='2' cellspacing='1' border='0' align=center>";
  5932. echo "<tr>
  5933. <td class='secLine' width='40%'>
  5934. ".get_lang('WorkTitle')."
  5935. </td>
  5936. <td class='secLine' width='30%'>
  5937. ".get_lang('WorkAuthors')."
  5938. </td>
  5939. <td class='secLine' width='30%'>
  5940. ".get_lang('Date')."
  5941. </td>
  5942. </tr>";
  5943. if (is_array($results)) {
  5944. for($j = 0 ; $j < count($results) ; $j++) {
  5945. $pathToFile = api_get_path(WEB_COURSE_PATH).$_course['path']."/".$results[$j][3];
  5946. $beautifulDate = api_convert_and_format_date($results[$j][0], null, date_default_timezone_get());
  5947. echo "<tr>";
  5948. echo "<td class='content'>"
  5949. ."<a href ='".$pathToFile."'>".$results[$j][1]."</a>"
  5950. ."</td>";
  5951. echo "<td class='content'>".$results[$j][2]."</td>";
  5952. echo "<td class='content'>".$beautifulDate."</td>";
  5953. echo"</tr>";
  5954. }
  5955. } else {
  5956. echo "<tr>";
  5957. echo "<td colspan='3'><center>".get_lang('NoResult')."</center></td>";
  5958. echo"</tr>";
  5959. }
  5960. echo "</table>";
  5961. echo "</td></tr>";
  5962. } else {
  5963. $new_view = substr_replace($view,'1',2,1);
  5964. echo "
  5965. <tr>
  5966. <td valign='top'>
  5967. +<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>
  5968. </td>
  5969. </tr>
  5970. ";
  5971. }
  5972. }
  5973. /**
  5974. * Displays the links followed for a specific user in a specific course.
  5975. * @todo remove globals
  5976. */
  5977. public function display_links_tracking_info($view, $user_id, $courseCode)
  5978. {
  5979. global $TABLETRACK_LINKS, $TABLECOURSE_LINKS;
  5980. $courseId = api_get_course_int_id($courseCode);
  5981. if (substr($view,3,1) == '1') {
  5982. $new_view = substr_replace($view,'0',3,1);
  5983. echo "
  5984. <tr>
  5985. <td valign='top'>
  5986. <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>]
  5987. </td>
  5988. </tr>
  5989. ";
  5990. echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('LinksDetails')."<br>";
  5991. $sql = "SELECT cl.title, cl.url
  5992. FROM $TABLETRACK_LINKS AS sl, $TABLECOURSE_LINKS AS cl
  5993. WHERE sl.links_link_id = cl.id
  5994. AND sl.c_id = $courseId
  5995. AND sl.links_user_id = ".intval($user_id)."
  5996. GROUP BY cl.title, cl.url";
  5997. echo "<tr><td style='padding-left : 40px;padding-right : 40px;'>";
  5998. $results = StatsUtils::getManyResults2Col($sql);
  5999. echo "<table cellpadding='2' cellspacing='1' border='0' align=center>";
  6000. echo "<tr>
  6001. <td class='secLine'>
  6002. ".get_lang('LinksTitleLinkColumn')."
  6003. </td>
  6004. </tr>";
  6005. if (is_array($results)) {
  6006. for($j = 0 ; $j < count($results) ; $j++) {
  6007. echo "<tr>";
  6008. echo "<td class='content'><a href='".$results[$j][1]."'>".$results[$j][0]."</a></td>";
  6009. echo"</tr>";
  6010. }
  6011. } else {
  6012. echo "<tr>";
  6013. echo "<td ><center>".get_lang('NoResult')."</center></td>";
  6014. echo"</tr>";
  6015. }
  6016. echo "</table>";
  6017. echo "</td></tr>";
  6018. } else {
  6019. $new_view = substr_replace($view,'1',3,1);
  6020. echo "
  6021. <tr>
  6022. <td valign='top'>
  6023. +<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>
  6024. </td>
  6025. </tr>
  6026. ";
  6027. }
  6028. }
  6029. /**
  6030. * Displays the documents downloaded for a specific user in a specific course.
  6031. * @param string kind of view inside tracking info
  6032. * @param int User id
  6033. * @param string Course code
  6034. * @param int Session id (optional, default = 0)
  6035. * @return void
  6036. */
  6037. public static function display_document_tracking_info($view, $user_id, $course_code, $session_id = 0)
  6038. {
  6039. // protect data
  6040. $user_id = intval($user_id);
  6041. $courseId = api_get_course_int_id($course_code);
  6042. $session_id = intval($session_id);
  6043. $downloads_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  6044. if(substr($view,4,1) == '1') {
  6045. $new_view = substr_replace($view,'0',4,1);
  6046. echo "
  6047. <tr>
  6048. <td valign='top'>
  6049. <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>]
  6050. </td>
  6051. </tr>
  6052. ";
  6053. echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('DocumentsDetails')."<br>";
  6054. $sql = "SELECT down_doc_path
  6055. FROM $downloads_table
  6056. WHERE c_id = $courseId
  6057. AND down_user_id = $user_id
  6058. AND down_session_id = $session_id
  6059. GROUP BY down_doc_path";
  6060. echo "<tr><td style='padding-left : 40px;padding-right : 40px;'>";
  6061. $results = StatsUtils::getManyResults1Col($sql);
  6062. echo "<table cellpadding='2' cellspacing='1' border='0' align='center'>";
  6063. echo "<tr>
  6064. <td class='secLine'>
  6065. ".get_lang('DocumentsTitleDocumentColumn')."
  6066. </td>
  6067. </tr>";
  6068. if (is_array($results)) {
  6069. for($j = 0 ; $j < count($results) ; $j++) {
  6070. echo "<tr>";
  6071. echo "<td class='content'>".$results[$j]."</td>";
  6072. echo"</tr>";
  6073. }
  6074. } else {
  6075. echo "<tr>";
  6076. echo "<td><center>".get_lang('NoResult')."</center></td>";
  6077. echo"</tr>";
  6078. }
  6079. echo "</table>";
  6080. echo "</td></tr>";
  6081. } else {
  6082. $new_view = substr_replace($view,'1',4,1);
  6083. echo "
  6084. <tr>
  6085. <td valign='top'>
  6086. +<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>
  6087. </td>
  6088. </tr>
  6089. ";
  6090. }
  6091. }
  6092. /**
  6093. * Gets the IP of a given user, using the last login before the given date
  6094. * @param int User ID
  6095. * @param string Datetime
  6096. * @param bool Whether to return the IP as a link or just as an IP
  6097. * @param string If defined and return_as_link if true, will be used as the text to be shown as the link
  6098. * @return string IP address (or false on error)
  6099. * @assert (0,0) === false
  6100. */
  6101. public static function get_ip_from_user_event($user_id, $event_date, $return_as_link = false, $body_replace = null)
  6102. {
  6103. if (empty($user_id) or empty($event_date)) {
  6104. return false;
  6105. }
  6106. $user_id = intval($user_id);
  6107. $event_date = Database::escape_string($event_date);
  6108. $table_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  6109. $sql_ip = "SELECT login_date, user_ip FROM $table_login
  6110. WHERE login_user_id = $user_id AND login_date < '$event_date'
  6111. ORDER BY login_date DESC LIMIT 1";
  6112. $ip = '';
  6113. $res_ip = Database::query($sql_ip);
  6114. if ($res_ip !== false && Database::num_rows($res_ip)>0) {
  6115. $row_ip = Database::fetch_row($res_ip);
  6116. if ($return_as_link) {
  6117. $ip = Display::url(
  6118. (empty($body_replace)?$row_ip[1]:$body_replace), 'http://www.whatsmyip.org/ip-geo-location/?ip='.$row_ip[1],
  6119. array('title'=>get_lang('TraceIP'), 'target'=>'_blank')
  6120. );
  6121. } else {
  6122. $ip = $row_ip[1];
  6123. }
  6124. }
  6125. return $ip;
  6126. }
  6127. }
  6128. /**
  6129. * @package chamilo.tracking
  6130. */
  6131. class TrackingUserLogCSV
  6132. {
  6133. /**
  6134. * Displays the number of logins every month for a specific user in a specific course.
  6135. * @param $view
  6136. * @param int $user_id
  6137. * @param int $course_id
  6138. * @param int $session_id
  6139. * @return array
  6140. */
  6141. public function display_login_tracking_info($view, $user_id, $course_id, $session_id = 0)
  6142. {
  6143. $MonthsLong = $GLOBALS['MonthsLong'];
  6144. $track_access_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  6145. // protected data
  6146. $user_id = intval($user_id);
  6147. $session_id = intval($session_id);
  6148. $course_id = intval($course_id);
  6149. $tempView = $view;
  6150. if (substr($view,0,1) == '1') {
  6151. $new_view = substr_replace($view,'0',0,1);
  6152. $title[1]= get_lang('LoginsAndAccessTools').get_lang('LoginsDetails');
  6153. $sql = "SELECT UNIX_TIMESTAMP(access_date), count(access_date)
  6154. FROM $track_access_table
  6155. WHERE access_user_id = $user_id
  6156. AND c_id = $course_id
  6157. AND access_session_id = $session_id
  6158. GROUP BY YEAR(access_date),MONTH(access_date)
  6159. ORDER BY YEAR(access_date),MONTH(access_date) ASC";
  6160. //$results = getManyResults2Col($sql);
  6161. $results = getManyResults3Col($sql);
  6162. $title_line= get_lang('LoginsTitleMonthColumn').';'.get_lang('LoginsTitleCountColumn')."\n";
  6163. $line='';
  6164. $total = 0;
  6165. if (is_array($results)) {
  6166. for($j = 0 ; $j < count($results) ; $j++) {
  6167. $line .= $results[$j][0].';'.$results[$j][1]."\n";
  6168. $total = $total + $results[$j][1];
  6169. }
  6170. $line .= get_lang('Total').";".$total."\n";
  6171. } else {
  6172. $line= get_lang('NoResult')."</center></td>";
  6173. }
  6174. } else {
  6175. $new_view = substr_replace($view,'1',0,1);
  6176. }
  6177. return array($title_line, $line);
  6178. }
  6179. /**
  6180. * Displays the exercise results for a specific user in a specific course.
  6181. * @param string $view
  6182. * @param int $user_id User ID
  6183. * @param string $courseCode Course code
  6184. * @return array
  6185. * @todo remove globals
  6186. */
  6187. public function display_exercise_tracking_info($view, $userId, $courseCode)
  6188. {
  6189. global $TABLECOURSE_EXERCICES, $TABLETRACK_EXERCICES, $TABLETRACK_HOTPOTATOES, $dateTimeFormatLong;
  6190. $courseId = api_get_course_int_id($courseCode);
  6191. $userId = intval($userId);
  6192. if (substr($view,1,1) == '1') {
  6193. $new_view = substr_replace($view,'0',1,1);
  6194. $title[1] = get_lang('ExercicesDetails');
  6195. $line = '';
  6196. $sql = "SELECT ce.title, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
  6197. FROM $TABLECOURSE_EXERCICES AS ce , $TABLETRACK_EXERCICES AS te
  6198. WHERE te.c_id = $courseId
  6199. AND te.exe_user_id = $userId
  6200. AND te.exe_exo_id = ce.id
  6201. ORDER BY ce.title ASC, te.exe_date ASC";
  6202. $hpsql = "SELECT te.exe_name, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
  6203. FROM $TABLETRACK_HOTPOTATOES AS te
  6204. WHERE te.exe_user_id = '$userId' AND te.c_id = $courseId
  6205. ORDER BY te.c_id ASC, te.exe_date ASC";
  6206. $hpresults = StatsUtils::getManyResultsXCol($hpsql, 4);
  6207. $NoTestRes = 0;
  6208. $NoHPTestRes = 0;
  6209. $results = StatsUtils::getManyResultsXCol($sql, 4);
  6210. $title_line = get_lang('ExercicesTitleExerciceColumn').";".get_lang('Date').';'.get_lang('ExercicesTitleScoreColumn')."\n";
  6211. if (is_array($results)) {
  6212. for($i = 0; $i < sizeof($results); $i++)
  6213. {
  6214. $display_date = api_convert_and_format_date($results[$i][3], null, date_default_timezone_get());
  6215. $line .= $results[$i][0].";".$display_date.";".$results[$i][1]." / ".$results[$i][2]."\n";
  6216. }
  6217. } else {
  6218. // istvan begin
  6219. $NoTestRes = 1;
  6220. }
  6221. // The Result of Tests
  6222. if (is_array($hpresults)) {
  6223. for($i = 0; $i < sizeof($hpresults); $i++) {
  6224. $title = GetQuizName($hpresults[$i][0],'');
  6225. if ($title == '')
  6226. $title = basename($hpresults[$i][0]);
  6227. $display_date = api_convert_and_format_date($hpresults[$i][3], null, date_default_timezone_get());
  6228. $line .= $title.';'.$display_date.';'.$hpresults[$i][1].'/'.$hpresults[$i][2]."\n";
  6229. }
  6230. } else {
  6231. $NoHPTestRes = 1;
  6232. }
  6233. if ($NoTestRes == 1 && $NoHPTestRes == 1) {
  6234. $line=get_lang('NoResult');
  6235. }
  6236. } else {
  6237. $new_view = substr_replace($view,'1',1,1);
  6238. }
  6239. return array($title_line, $line);
  6240. }
  6241. /**
  6242. * Displays the student publications for a specific user in a specific course.
  6243. * @todo remove globals
  6244. */
  6245. public function display_student_publications_tracking_info($view, $user_id, $course_id)
  6246. {
  6247. global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK;
  6248. $_course = api_get_course_info();
  6249. $user_id = intval($user_id);
  6250. $course_id = intval($course_id);
  6251. if (substr($view,2,1) == '1') {
  6252. $sql = "SELECT u.upload_date, w.title, w.author, w.url
  6253. FROM $TABLETRACK_UPLOADS u , $TABLECOURSE_WORK w
  6254. WHERE
  6255. u.upload_work_id = w.id AND
  6256. u.upload_user_id = '$user_id' AND
  6257. u.c_id = '$course_id'
  6258. ORDER BY u.upload_date DESC";
  6259. $results = StatsUtils::getManyResultsXCol($sql,4);
  6260. $title[1]=get_lang('WorksDetails');
  6261. $line='';
  6262. $title_line=get_lang('WorkTitle').";".get_lang('WorkAuthors').";".get_lang('Date')."\n";
  6263. if (is_array($results)) {
  6264. for($j = 0 ; $j < count($results) ; $j++) {
  6265. $pathToFile = api_get_path(WEB_COURSE_PATH).$_course['path']."/".$results[$j][3];
  6266. $beautifulDate = api_convert_and_format_date($results[$j][0], null, date_default_timezone_get());
  6267. $line .= $results[$j][1].";".$results[$j][2].";".$beautifulDate."\n";
  6268. }
  6269. } else {
  6270. $line= get_lang('NoResult');
  6271. }
  6272. }
  6273. return array($title_line, $line);
  6274. }
  6275. /**
  6276. * Displays the links followed for a specific user in a specific course.
  6277. * @todo remove globals
  6278. */
  6279. public function display_links_tracking_info($view, $userId, $courseCode)
  6280. {
  6281. global $TABLETRACK_LINKS, $TABLECOURSE_LINKS;
  6282. $courseId = api_get_course_int_id($courseCode);
  6283. $userId = intval($userId);
  6284. $line = null;
  6285. if (substr($view,3,1) == '1') {
  6286. $new_view = substr_replace($view,'0',3,1);
  6287. $title[1]=get_lang('LinksDetails');
  6288. $sql = "SELECT cl.title, cl.url
  6289. FROM $TABLETRACK_LINKS AS sl, $TABLECOURSE_LINKS AS cl
  6290. WHERE sl.links_link_id = cl.id
  6291. AND sl.c_id = $courseId
  6292. AND sl.links_user_id = $userId
  6293. GROUP BY cl.title, cl.url";
  6294. $results = StatsUtils::getManyResults2Col($sql);
  6295. $title_line= get_lang('LinksTitleLinkColumn')."\n";
  6296. if (is_array($results)) {
  6297. for ($j = 0 ; $j < count($results) ; $j++) {
  6298. $line .= $results[$j][0]."\n";
  6299. }
  6300. } else {
  6301. $line=get_lang('NoResult');
  6302. }
  6303. } else {
  6304. $new_view = substr_replace($view,'1',3,1);
  6305. }
  6306. return array($title_line, $line);
  6307. }
  6308. /**
  6309. * Displays the documents downloaded for a specific user in a specific course.
  6310. * @param string kind of view inside tracking info
  6311. * @param int User id
  6312. * @param string Course code
  6313. * @param int Session id (optional, default = 0)
  6314. * @return void
  6315. */
  6316. public function display_document_tracking_info($view, $user_id, $courseCode, $session_id = 0)
  6317. {
  6318. // protect data
  6319. $user_id = intval($user_id);
  6320. $courseId = api_get_course_int_id($courseCode);
  6321. $session_id = intval($session_id);
  6322. $downloads_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  6323. if (substr($view,4,1) == '1') {
  6324. $new_view = substr_replace($view,'0',4,1);
  6325. $title[1]= get_lang('DocumentsDetails');
  6326. $sql = "SELECT down_doc_path
  6327. FROM $downloads_table
  6328. WHERE c_id = $courseId
  6329. AND down_user_id = $user_id
  6330. AND down_session_id = $session_id
  6331. GROUP BY down_doc_path";
  6332. $results = StatsUtils::getManyResults1Col($sql);
  6333. $title_line = get_lang('DocumentsTitleDocumentColumn')."\n";
  6334. $line = null;
  6335. if (is_array($results)) {
  6336. for ($j = 0 ; $j < count($results) ; $j++) {
  6337. $line .= $results[$j]."\n";
  6338. }
  6339. } else {
  6340. $line = get_lang('NoResult');
  6341. }
  6342. } else {
  6343. $new_view = substr_replace($view,'1',4,1);
  6344. }
  6345. return array($title_line, $line);
  6346. }
  6347. /**
  6348. * @param $userId
  6349. * @param $courseInfo
  6350. * @param int $sessionId
  6351. * @return array
  6352. */
  6353. public static function getToolInformation(
  6354. $userId,
  6355. $courseInfo,
  6356. $sessionId = 0
  6357. ) {
  6358. $csvContent = array();
  6359. $courseToolInformation = null;
  6360. $headerTool = array(
  6361. array(get_lang('Title')),
  6362. array(get_lang('CreatedAt')),
  6363. array(get_lang('UpdatedAt')),
  6364. );
  6365. $headerListForCSV = array();
  6366. foreach ($headerTool as $item) {
  6367. $headerListForCSV[] = $item[0];
  6368. }
  6369. $courseForumInformationArray = getForumCreatedByUser(
  6370. $userId,
  6371. $courseInfo['real_id'],
  6372. $sessionId
  6373. );
  6374. if (!empty($courseForumInformationArray)) {
  6375. $csvContent[] = array();
  6376. $csvContent[] = get_lang('Forums');
  6377. $csvContent[] = $headerListForCSV;
  6378. foreach ($courseForumInformationArray as $row) {
  6379. $csvContent[] = $row;
  6380. }
  6381. $courseToolInformation .= Display::page_subheader2(
  6382. get_lang('Forums')
  6383. );
  6384. $courseToolInformation .= Display::return_sortable_table(
  6385. $headerTool,
  6386. $courseForumInformationArray
  6387. );
  6388. }
  6389. $courseWorkInformationArray = getWorkCreatedByUser(
  6390. $userId,
  6391. $courseInfo['real_id'],
  6392. $sessionId
  6393. );
  6394. if (!empty($courseWorkInformationArray)) {
  6395. $csvContent[] = null;
  6396. $csvContent[] = get_lang('Works');
  6397. $csvContent[] = $headerListForCSV;
  6398. foreach ($courseWorkInformationArray as $row) {
  6399. $csvContent[] = $row;
  6400. }
  6401. $csvContent[] = null;
  6402. $courseToolInformation .= Display::page_subheader2(
  6403. get_lang('Works')
  6404. );
  6405. $courseToolInformation .= Display::return_sortable_table(
  6406. $headerTool,
  6407. $courseWorkInformationArray
  6408. );
  6409. }
  6410. $courseToolInformationTotal = null;
  6411. if (!empty($courseToolInformation)) {
  6412. $sessionTitle = null;
  6413. if (!empty($sessionId)) {
  6414. $sessionTitle = ' ('.api_get_session_name($sessionId).')';
  6415. }
  6416. $courseToolInformationTotal .= Display::page_subheader(
  6417. $courseInfo['title'].$sessionTitle
  6418. );
  6419. $courseToolInformationTotal .= $courseToolInformation;
  6420. }
  6421. return array(
  6422. 'array' => $csvContent,
  6423. 'html' => $courseToolInformationTotal
  6424. );
  6425. }
  6426. }