sessionmanager.lib.php 304 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
  4. /**
  5. * Class SessionManager
  6. *
  7. * This is the session library for Chamilo.
  8. * All main sessions functions should be placed here.
  9. * This class provides methods for sessions management.
  10. * Include/require it in your code to use its features.
  11. *
  12. * @package chamilo.library
  13. *
  14. */
  15. class SessionManager
  16. {
  17. public static $_debug = false;
  18. /**
  19. * Constructor
  20. */
  21. public function __construct()
  22. {
  23. }
  24. /**
  25. * Fetches a session from the database
  26. * @param int $id Session Id
  27. *
  28. * @return array Session details
  29. */
  30. public static function fetch($id)
  31. {
  32. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  33. if ($id != strval(intval($id))) {
  34. return array();
  35. }
  36. $s = "SELECT * FROM $t WHERE id = $id";
  37. $r = Database::query($s);
  38. if (Database::num_rows($r) != 1) {
  39. return array();
  40. }
  41. return Database::fetch_array($r, 'ASSOC');
  42. }
  43. /**
  44. * Create a session
  45. * @author Carlos Vargas <carlos.vargas@beeznest.com>, from existing code
  46. * @param string $name
  47. * @param string $startDate (YYYY-MM-DD hh:mm:ss)
  48. * @param string $endDate (YYYY-MM-DD hh:mm:ss)
  49. * @param string $displayStartDate (YYYY-MM-DD hh:mm:ss)
  50. * @param string $displayEndDate (YYYY-MM-DD hh:mm:ss)
  51. * @param string $coachStartDate (YYYY-MM-DD hh:mm:ss)
  52. * @param string $coachEndDate (YYYY-MM-DD hh:mm:ss)
  53. * @param mixed $coachId If integer, this is the session coach id, if string, the coach ID will be looked for from the user table
  54. * @param integer $sessionCategoryId ID of the session category in which this session is registered
  55. * @param integer $visibility Visibility after end date (0 = read-only, 1 = invisible, 2 = accessible)
  56. * @param bool $fixSessionNameIfExists
  57. * @param string $duration
  58. * @param string $description Optional. The session description
  59. * @param int $showDescription Optional. Whether show the session description
  60. * @param array $extraFields
  61. * @param int $sessionAdminId Optional. If this sessions was created by a session admin, assign it to him
  62. * @param boolean $sendSubscriptionNotification Optional.
  63. * Whether send a mail notification to users being subscribed
  64. * @todo use an array to replace all this parameters or use the model.lib.php ...
  65. * @return mixed Session ID on success, error message otherwise
  66. * */
  67. public static function create_session(
  68. $name,
  69. $startDate,
  70. $endDate,
  71. $displayStartDate,
  72. $displayEndDate,
  73. $coachStartDate,
  74. $coachEndDate,
  75. $coachId,
  76. $sessionCategoryId,
  77. $visibility = 1,
  78. $fixSessionNameIfExists = false,
  79. $duration = null,
  80. $description = null,
  81. $showDescription = 0,
  82. $extraFields = array(),
  83. $sessionAdminId = 0,
  84. $sendSubscriptionNotification = false
  85. ) {
  86. global $_configuration;
  87. //Check portal limits
  88. $access_url_id = 1;
  89. if (api_get_multiple_access_url()) {
  90. $access_url_id = api_get_current_access_url_id();
  91. }
  92. if (is_array($_configuration[$access_url_id]) &&
  93. isset($_configuration[$access_url_id]['hosting_limit_sessions']) &&
  94. $_configuration[$access_url_id]['hosting_limit_sessions'] > 0
  95. ) {
  96. $num = self::count_sessions();
  97. if ($num >= $_configuration[$access_url_id]['hosting_limit_sessions']) {
  98. api_warn_hosting_contact('hosting_limit_sessions');
  99. return get_lang('PortalSessionsLimitReached');
  100. }
  101. }
  102. $name = Database::escape_string(trim($name));
  103. $sessionCategoryId = intval($sessionCategoryId);
  104. $visibility = intval($visibility);
  105. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  106. $startDate = Database::escape_string($startDate);
  107. $endDate = Database::escape_string($endDate);
  108. if (empty($name)) {
  109. $msg = get_lang('SessionNameIsRequired');
  110. return $msg;
  111. } elseif (empty($coachId)) {
  112. $msg = get_lang('CoachIsRequired');
  113. return $msg;
  114. } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i') && !api_is_valid_date($startDate, 'Y-m-d H:i:s')) {
  115. $msg = get_lang('InvalidStartDate');
  116. return $msg;
  117. } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i') && !api_is_valid_date($endDate, 'Y-m-d H:i:s')) {
  118. $msg = get_lang('InvalidEndDate');
  119. return $msg;
  120. } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
  121. $msg = get_lang('StartDateShouldBeBeforeEndDate');
  122. return $msg;
  123. } else {
  124. $ready_to_create = false;
  125. if ($fixSessionNameIfExists) {
  126. $name = self::generateNextSessionName($name);
  127. if ($name) {
  128. $ready_to_create = true;
  129. } else {
  130. $msg = get_lang('SessionNameAlreadyExists');
  131. return $msg;
  132. }
  133. } else {
  134. $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='" . $name . "'");
  135. if (Database::num_rows($rs)) {
  136. $msg = get_lang('SessionNameAlreadyExists');
  137. return $msg;
  138. }
  139. $ready_to_create = true;
  140. }
  141. if ($ready_to_create) {
  142. $sessionAdminId = !empty($sessionAdminId) ? $sessionAdminId : api_get_user_id();
  143. $values = array(
  144. 'name' => $name,
  145. 'id_coach' => $coachId,
  146. 'session_admin_id' => $sessionAdminId,
  147. 'visibility' => $visibility,
  148. 'description' => $description,
  149. 'show_description' => intval($showDescription),
  150. 'send_subscription_notification' => (int) $sendSubscriptionNotification
  151. );
  152. if (!empty($startDate)) {
  153. $values['access_start_date'] = api_get_utc_datetime($startDate);
  154. }
  155. if (!empty($endDate)) {
  156. $values['access_end_date'] = api_get_utc_datetime($endDate);
  157. }
  158. if (!empty($displayStartDate)) {
  159. $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
  160. }
  161. if (!empty($displayEndDate)) {
  162. $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
  163. }
  164. if (!empty($coachStartDate)) {
  165. $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
  166. }
  167. if (!empty($coachEndDate)) {
  168. $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
  169. }
  170. if (!empty($sessionCategoryId)) {
  171. $values['session_category_id'] = $sessionCategoryId;
  172. }
  173. $session_id = Database::insert($tbl_session, $values);
  174. $duration = intval($duration);
  175. if (!empty($duration)) {
  176. $sql = "UPDATE $tbl_session SET
  177. access_start_date = NULL,
  178. access_end_date = NULL,
  179. display_start_date = NULL,
  180. display_end_date = NULL,
  181. coach_access_start_date = NULL,
  182. coach_access_end_date = NULL,
  183. duration = $duration
  184. WHERE id = $session_id";
  185. Database::query($sql);
  186. } else {
  187. $sql = "UPDATE $tbl_session
  188. SET duration = 0
  189. WHERE id = $session_id";
  190. Database::query($sql);
  191. }
  192. if (!empty($session_id)) {
  193. $extraFields['item_id'] = $session_id;
  194. $sessionFieldValue = new ExtraFieldValue('session');
  195. $sessionFieldValue->saveFieldValues($extraFields);
  196. /*
  197. Sends a message to the user_id = 1
  198. $user_info = api_get_user_info(1);
  199. $complete_name = $user_info['firstname'].' '.$user_info['lastname'];
  200. $subject = api_get_setting('siteName').' - '.get_lang('ANewSessionWasCreated');
  201. $message = get_lang('ANewSessionWasCreated')." <br /> ".get_lang('NameOfTheSession').' : '.$name;
  202. api_mail_html($complete_name, $user_info['email'], $subject, $message);
  203. *
  204. */
  205. //Adding to the correct URL
  206. $access_url_id = api_get_current_access_url_id();
  207. UrlManager::add_session_to_url($session_id, $access_url_id);
  208. // add event to system log
  209. $user_id = api_get_user_id();
  210. Event::addEvent(
  211. LOG_SESSION_CREATE,
  212. LOG_SESSION_ID,
  213. $session_id,
  214. api_get_utc_datetime(),
  215. $user_id
  216. );
  217. }
  218. return $session_id;
  219. }
  220. }
  221. }
  222. /**
  223. * @param string $name
  224. *
  225. * @return bool
  226. */
  227. public static function session_name_exists($name)
  228. {
  229. $name = Database::escape_string($name);
  230. $sql = "SELECT COUNT(*) as count FROM " . Database::get_main_table(TABLE_MAIN_SESSION) . "
  231. WHERE name = '$name'";
  232. $result = Database::fetch_array(Database::query($sql));
  233. return $result['count'] > 0;
  234. }
  235. /**
  236. * @param string $where_condition
  237. *
  238. * @return mixed
  239. */
  240. public static function get_count_admin($where_condition = '')
  241. {
  242. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  243. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  244. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  245. $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  246. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  247. $where = 'WHERE 1=1 ';
  248. $user_id = api_get_user_id();
  249. $extraJoin = '';
  250. if (api_is_session_admin() &&
  251. api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
  252. ) {
  253. $where .= " AND (
  254. s.session_admin_id = $user_id OR
  255. sru.user_id = '$user_id' AND
  256. sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "'
  257. )
  258. ";
  259. $extraJoin = " INNER JOIN $tbl_session_rel_user sru
  260. ON sru.session_id = s.id ";
  261. }
  262. $today = api_get_utc_datetime();
  263. $today = api_strtotime($today, 'UTC');
  264. $today = date('Y-m-d', $today);
  265. if (!empty($where_condition)) {
  266. $where_condition = str_replace("( session_active = ':' )", '1=1', $where_condition);
  267. $where_condition = str_replace('category_name', 'sc.name', $where_condition);
  268. $where_condition = str_replace(
  269. array("AND session_active = '1' )", " AND ( session_active = '1' )"),
  270. array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
  271. , $where_condition
  272. );
  273. $where_condition = str_replace(
  274. array("AND session_active = '0' )", " AND ( session_active = '0' )"),
  275. array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
  276. $where_condition
  277. );
  278. } else {
  279. $where_condition = " AND 1 = 1";
  280. }
  281. $courseCondition = null;
  282. if (strpos($where_condition, 'c.id')) {
  283. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  284. $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  285. $courseCondition = " INNER JOIN $table course_rel_session
  286. ON (s.id = course_rel_session.session_id)
  287. INNER JOIN $tableCourse c
  288. ON (course_rel_session.c_id = c.id)
  289. ";
  290. }
  291. $sql = "SELECT COUNT(id) as total_rows FROM (
  292. SELECT DISTINCT
  293. IF (
  294. (s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
  295. (s.access_start_date IS NULL AND s.access_end_date = IS NULL ) OR
  296. (s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
  297. ('$today' <= s.access_end_date AND s.access_start_date IS NULL)
  298. , 1, 0) as session_active,
  299. s.id
  300. FROM $tbl_session s
  301. LEFT JOIN $tbl_session_category sc
  302. ON s.session_category_id = sc.id
  303. INNER JOIN $tbl_user u
  304. ON s.id_coach = u.user_id
  305. $courseCondition
  306. $extraJoin
  307. $where $where_condition ) as session_table";
  308. if (api_is_multiple_url_enabled()) {
  309. $access_url_id = api_get_current_access_url_id();
  310. if ($access_url_id != -1) {
  311. $where.= " AND ar.access_url_id = $access_url_id ";
  312. $sql = "SELECT count(id) as total_rows FROM (
  313. SELECT DISTINCT
  314. IF (
  315. (s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
  316. (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
  317. (s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
  318. ('$today' <= s.access_end_date AND s.access_start_date IS NULL)
  319. , 1, 0)
  320. as session_active,
  321. s.id
  322. FROM $tbl_session s
  323. LEFT JOIN $tbl_session_category sc
  324. ON s.session_category_id = sc.id
  325. INNER JOIN $tbl_user u ON s.id_coach = u.user_id
  326. INNER JOIN $table_access_url_rel_session ar
  327. ON ar.session_id = s.id
  328. $courseCondition
  329. $extraJoin
  330. $where $where_condition) as session_table";
  331. }
  332. }
  333. $result_rows = Database::query($sql);
  334. $row = Database::fetch_array($result_rows);
  335. $num = $row['total_rows'];
  336. return $num;
  337. }
  338. /**
  339. * Gets the admin session list callback of the session/session_list.php page
  340. * @param array $options order and limit keys
  341. * @param boolean $get_count Whether to get all the results or only the count
  342. * @return mixed Integer for number of rows, or array of results
  343. * @assert (array(),true) !== false
  344. */
  345. public static function get_sessions_admin($options = array(), $get_count = false, $accessStartDate = '', $accessEndDate = '', $extraFieldsToLoad = array())
  346. {
  347. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  348. $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  349. $where = 'WHERE 1 = 1 ';
  350. $user_id = api_get_user_id();
  351. if (!api_is_platform_admin()) {
  352. if (api_is_session_admin() &&
  353. api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
  354. ) {
  355. $where .=" AND s.session_admin_id = $user_id ";
  356. }
  357. }
  358. if (!api_is_platform_admin() && api_is_teacher() &&
  359. api_get_setting('allow_teachers_to_create_sessions') == 'true'
  360. ) {
  361. $where .=" AND s.id_coach = $user_id ";
  362. }
  363. $extra_field = new \ExtraField('session');
  364. $conditions = $extra_field->parseConditions($options);
  365. $inject_joins = $conditions['inject_joins'];
  366. $where .= $conditions['where'];
  367. $inject_where = $conditions['inject_where'];
  368. $inject_extra_fields = $conditions['inject_extra_fields'];
  369. $order = $conditions['order'];
  370. $limit = $conditions['limit'];
  371. $isMakingOrder = false;
  372. if ($get_count == true) {
  373. $select = " SELECT count(*) as total_rows";
  374. } else {
  375. $select ="
  376. SELECT DISTINCT
  377. s.name,
  378. s.display_start_date,
  379. s.display_end_date,
  380. access_start_date,
  381. access_end_date,
  382. s.visibility,
  383. s.session_category_id,
  384. $inject_extra_fields
  385. s.id
  386. "
  387. ;
  388. if (isset($options['order'])) {
  389. $isMakingOrder = strpos($options['order'], 'category_name') === 0;
  390. }
  391. }
  392. $isFilteringSessionCategory = strpos($where, 'category_name') !== false;
  393. if ($isMakingOrder || $isFilteringSessionCategory) {
  394. $inject_joins .= " LEFT JOIN $sessionCategoryTable sc ON s.session_category_id = sc.id ";
  395. if ($isFilteringSessionCategory) {
  396. $where = str_replace('category_name', 'sc.name', $where);
  397. }
  398. if ($isMakingOrder) {
  399. $order = str_replace('category_name', 'sc.name', $order);
  400. }
  401. }
  402. $query = "$select FROM $tbl_session s $inject_joins $where $inject_where";
  403. if (!empty($accessStartDate) && !empty($accessEndDate)) {
  404. $accessStartDate = api_get_utc_datetime($accessStartDate);
  405. $accessEndDate = api_get_utc_datetime($accessEndDate);
  406. $query .= " AND (
  407. (access_start_date > '$accessStartDate' AND access_end_date < '$accessEndDate') OR
  408. (access_start_date > '$accessStartDate' AND access_end_date IS NULL) OR
  409. (access_start_date IS NULL AND access_end_date < '$accessEndDate') OR
  410. (access_start_date IS NULL AND access_end_date IS NULL)
  411. )";
  412. }
  413. if (api_is_multiple_url_enabled()) {
  414. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  415. $access_url_id = api_get_current_access_url_id();
  416. if ($access_url_id != -1) {
  417. $where.= " AND ar.access_url_id = $access_url_id ";
  418. $query = "$select
  419. FROM $tbl_session s $inject_joins
  420. INNER JOIN $table_access_url_rel_session ar
  421. ON (ar.session_id = s.id) $where";
  422. }
  423. }
  424. $query .= $order;
  425. $query .= $limit;
  426. $result = Database::query($query);
  427. $categories = self::get_all_session_category();
  428. $orderedCategories = array();
  429. if (!empty($categories)) {
  430. foreach ($categories as $category) {
  431. $orderedCategories[$category['id']] = $category['name'];
  432. }
  433. }
  434. $formatted_sessions = array();
  435. if (Database::num_rows($result)) {
  436. $sessions = Database::store_result($result, 'ASSOC');
  437. if ($get_count) {
  438. return $sessions[0]['total_rows'];
  439. }
  440. foreach ($sessions as $session) {
  441. $session_id = $session['id'];
  442. $url = api_get_path(WEB_CODE_PATH)."session/resume_session.php?id_session=".$session['id'];
  443. if (api_is_drh()) {
  444. $url = api_get_path(WEB_CODE_PATH)."session/about.php?session_id=".$session['id'];
  445. }
  446. if (api_is_platform_admin()) {
  447. $url = api_get_path(WEB_CODE_PATH)."session/resume_session.php?id_session=".$session['id'];
  448. }
  449. $session['name'] = Display::url(
  450. $session['name'],
  451. $url
  452. );
  453. if (!empty($extraFieldsToLoad)) {
  454. foreach ($extraFieldsToLoad as $field) {
  455. $extraFieldValue = new ExtraFieldValue('session');
  456. $fieldData = $extraFieldValue->getAllValuesByItemAndField($session['id'], $field['id']);
  457. $fieldDataArray = array();
  458. $fieldDataToString = '';
  459. if (!empty($fieldData)) {
  460. foreach ($fieldData as $data) {
  461. $fieldDataArray[] = $data['value'];
  462. }
  463. $fieldDataToString = implode(', ', $fieldDataArray);
  464. }
  465. $session[$field['variable']] = $fieldDataToString;
  466. }
  467. }
  468. if (isset($session['session_active']) && $session['session_active'] == 1) {
  469. $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
  470. } else {
  471. $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
  472. }
  473. $session = self::convert_dates_to_local($session, true);
  474. switch ($session['visibility']) {
  475. case SESSION_VISIBLE_READ_ONLY: //1
  476. $session['visibility'] = get_lang('ReadOnly');
  477. break;
  478. case SESSION_VISIBLE: //2
  479. case SESSION_AVAILABLE: //4
  480. $session['visibility'] = get_lang('Visible');
  481. break;
  482. case SESSION_INVISIBLE: //3
  483. $session['visibility'] = api_ucfirst(get_lang('Invisible'));
  484. break;
  485. }
  486. // Cleaning double selects.
  487. foreach ($session as $key => &$value) {
  488. if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
  489. $options = explode('::', $value);
  490. }
  491. $original_key = $key;
  492. if (strpos($key, '_second') === false) {
  493. } else {
  494. $key = str_replace('_second', '', $key);
  495. }
  496. if (isset($options_by_double[$key])) {
  497. if (isset($options[0])) {
  498. if (isset($options_by_double[$key][$options[0]])) {
  499. if (strpos($original_key, '_second') === false) {
  500. $value = $options_by_double[$key][$options[0]]['option_display_text'];
  501. } else {
  502. $value = $options_by_double[$key][$options[1]]['option_display_text'];
  503. }
  504. }
  505. }
  506. }
  507. }
  508. $formatted_sessions[$session_id] = $session;
  509. $categoryName = isset($orderedCategories[$session['session_category_id']]) ? $orderedCategories[$session['session_category_id']] : '';
  510. $formatted_sessions[$session_id]['category_name'] = $categoryName;
  511. }
  512. }
  513. return $formatted_sessions;
  514. }
  515. /**
  516. * Get total of records for progress of learning paths in the given session
  517. * @param int session id
  518. * @return int
  519. */
  520. public static function get_count_session_lp_progress($sessionId = 0)
  521. {
  522. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  523. $tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
  524. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  525. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  526. $sessionId = intval($sessionId);
  527. $sql = "SELECT count(*) as total_rows
  528. FROM $tbl_lp_view v
  529. INNER JOIN $tbl_lp l ON l.id = v.lp_id
  530. INNER JOIN $tbl_user u ON u.user_id = v.user_id
  531. INNER JOIN $tbl_course c
  532. WHERE v.session_id = " . $sessionId;
  533. $result_rows = Database::query($sql);
  534. $row = Database::fetch_array($result_rows);
  535. $num = $row['total_rows'];
  536. return $num;
  537. }
  538. /**
  539. * Gets the progress of learning paths in the given session
  540. * @param int $sessionId
  541. * @param int $courseId
  542. * @param string $date_from
  543. * @param string $date_to
  544. * @param array options order and limit keys
  545. * @return array table with user name, lp name, progress
  546. */
  547. public static function get_session_lp_progress($sessionId = 0, $courseId = 0, $date_from, $date_to, $options)
  548. {
  549. //escaping vars
  550. $sessionId = $sessionId == 'T' ? 'T' : intval($sessionId);
  551. $courseId = intval($courseId);
  552. $date_from = Database :: escape_string($date_from);
  553. $date_to = Database :: escape_string($date_to);
  554. //tables
  555. $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  556. $user = Database::get_main_table(TABLE_MAIN_USER);
  557. $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
  558. $course = api_get_course_info_by_id($courseId);
  559. //getting all the students of the course
  560. //we are not using this because it only returns user ids
  561. /* if (empty($sessionId)
  562. {
  563. // Registered students in a course outside session.
  564. $users = CourseManager :: get_student_list_from_course_code($course_code);
  565. } else {
  566. // Registered students in session.
  567. $users = CourseManager :: get_student_list_from_course_code($course_code, true, $sessionId);
  568. } */
  569. $sessionCond = 'and session_id = %s';
  570. if ($sessionId == 'T') {
  571. $sessionCond = "";
  572. }
  573. $where = " WHERE c_id = '%s' AND s.status <> 2 $sessionCond";
  574. $limit = null;
  575. if (!empty($options['limit'])) {
  576. $limit = " LIMIT " . $options['limit'];
  577. }
  578. if (!empty($options['where'])) {
  579. $where .= ' '.$options['where'];
  580. }
  581. $order = null;
  582. if (!empty($options['order'])) {
  583. $order = " ORDER BY " . $options['order'];
  584. }
  585. $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
  586. FROM $session_course_user s
  587. INNER JOIN $user u ON u.user_id = s.user_id
  588. $where
  589. $order
  590. $limit";
  591. $sql_query = sprintf($sql, Database::escape_string($course['real_id']), $sessionId);
  592. $rs = Database::query($sql_query);
  593. while ($user = Database::fetch_array($rs)) {
  594. $users[$user['user_id']] = $user;
  595. }
  596. //Get lessons
  597. $lessons = LearnpathList::get_course_lessons($course['code'], $sessionId);
  598. $table = array();
  599. foreach ($users as $user) {
  600. $data = array(
  601. 'lastname' => $user[1],
  602. 'firstname' => $user[2],
  603. 'username' => $user[3],
  604. );
  605. $sessionCond = 'AND v.session_id = %d';
  606. if ($sessionId == 'T') {
  607. $sessionCond = "";
  608. }
  609. //Get lessons progress by user
  610. $sql = "SELECT v.lp_id as id, v.progress
  611. FROM $tbl_course_lp_view v
  612. WHERE v.c_id = %d
  613. AND v.user_id = %d
  614. $sessionCond";
  615. $sql_query = sprintf($sql,
  616. intval($courseId),
  617. intval($user['user_id']),
  618. $sessionId
  619. );
  620. $result = Database::query($sql_query);
  621. $user_lessons = array();
  622. while ($row = Database::fetch_array($result)) {
  623. $user_lessons[$row['id']] = $row;
  624. }
  625. //Match course lessons with user progress
  626. $progress = 0;
  627. $count = 0;
  628. foreach ($lessons as $lesson) {
  629. $data[$lesson['id']] = (!empty($user_lessons[$lesson['id']]['progress'])) ? $user_lessons[$lesson['id']]['progress'] : 0;
  630. $progress += $data[$lesson['id']];
  631. $data[$lesson['id']] = $data[$lesson['id']] . '%';
  632. $count++;
  633. }
  634. if ($count == 0) {
  635. $data['total'] = 0;
  636. } else {
  637. $data['total'] = round($progress / $count, 2) . '%';
  638. }
  639. $table[] = $data;
  640. }
  641. return $table;
  642. }
  643. /**
  644. * Gets the survey answers
  645. * @param int $sessionId
  646. * @param int $courseId
  647. * @param int $surveyId
  648. * @param array options order and limit keys
  649. * @todo fix the query
  650. * @return array table with user name, lp name, progress
  651. */
  652. public static function get_survey_overview($sessionId = 0, $courseId = 0, $surveyId = 0, $date_from, $date_to, $options)
  653. {
  654. //escaping vars
  655. $sessionId = intval($sessionId);
  656. $courseId = intval($courseId);
  657. $surveyId = intval($surveyId);
  658. $date_from = Database::escape_string($date_from);
  659. $date_to = Database::escape_string($date_to);
  660. //tables
  661. $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  662. $user = Database::get_main_table(TABLE_MAIN_USER);
  663. $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
  664. $c_survey = Database::get_course_table(TABLE_SURVEY);
  665. $c_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  666. $c_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  667. $c_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  668. $course = api_get_course_info_by_id($courseId);
  669. $where = " WHERE c_id = '%s' AND s.status <> 2 AND session_id = %s";
  670. $limit = null;
  671. if (!empty($options['limit'])) {
  672. $limit = " LIMIT " . $options['limit'];
  673. }
  674. if (!empty($options['where'])) {
  675. $where .= ' '.$options['where'];
  676. }
  677. $order = null;
  678. if (!empty($options['order'])) {
  679. $order = " ORDER BY " . $options['order'];
  680. }
  681. $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
  682. FROM $session_course_user s
  683. INNER JOIN $user u ON u.user_id = s.user_id
  684. $where $order $limit";
  685. $sql_query = sprintf($sql, intval($course['real_id']), $sessionId);
  686. $rs = Database::query($sql_query);
  687. while ($user = Database::fetch_array($rs)) {
  688. $users[$user['user_id']] = $user;
  689. }
  690. //Get survey questions
  691. $questions = SurveyManager::get_questions($surveyId, $courseId);
  692. //Survey is anonymous?
  693. $result = Database::query(sprintf("SELECT anonymous FROM $c_survey WHERE survey_id = %d", $surveyId));
  694. $row = Database::fetch_array($result);
  695. $anonymous = ($row['anonymous'] == 1) ? true : false;
  696. $table = array();
  697. foreach ($users as $user) {
  698. $data = array(
  699. 'lastname' => ($anonymous ? '***' : $user[1]),
  700. 'firstname' => ($anonymous ? '***' : $user[2]),
  701. 'username' => ($anonymous ? '***' : $user[3]),
  702. );
  703. //Get questions by user
  704. $sql = "SELECT sa.question_id, sa.option_id, sqo.option_text, sq.type
  705. FROM $c_survey_answer sa
  706. INNER JOIN $c_survey_question sq
  707. ON sq.question_id = sa.question_id
  708. LEFT JOIN $c_survey_question_option sqo
  709. ON
  710. sqo.c_id = sa.c_id AND
  711. sqo.question_id = sq.question_id AND
  712. sqo.question_option_id = sa.option_id AND
  713. sqo.survey_id = sq.survey_id
  714. WHERE
  715. sa.survey_id = %d AND
  716. sa.c_id = %d AND
  717. sa.user = %d
  718. "; //. $where_survey;
  719. $sql_query = sprintf($sql, $surveyId, $courseId, $user['user_id']);
  720. $result = Database::query($sql_query);
  721. $user_questions = array();
  722. while ($row = Database::fetch_array($result)) {
  723. $user_questions[$row['question_id']] = $row;
  724. }
  725. //Match course lessons with user progress
  726. foreach ($questions as $question_id => $question) {
  727. $option_text = 'option_text';
  728. if ($user_questions[$question_id]['type'] == 'open') {
  729. $option_text = 'option_id';
  730. }
  731. $data[$question_id] = $user_questions[$question_id][$option_text];
  732. }
  733. $table[] = $data;
  734. }
  735. return $table;
  736. }
  737. /**
  738. * Gets the progress of the given session
  739. * @param int $sessionId
  740. * @param int $courseId
  741. * @param array options order and limit keys
  742. *
  743. * @return array table with user name, lp name, progress
  744. */
  745. public static function get_session_progress($sessionId, $courseId, $date_from, $date_to, $options)
  746. {
  747. $sessionId = intval($sessionId);
  748. $getAllSessions = false;
  749. if (empty($sessionId)) {
  750. $sessionId = 0;
  751. $getAllSessions = true;
  752. }
  753. //tables
  754. $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  755. $user = Database::get_main_table(TABLE_MAIN_USER);
  756. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  757. $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  758. $tbl_course_lp = Database::get_course_table(TABLE_LP_MAIN);
  759. $wiki = Database::get_course_table(TABLE_WIKI);
  760. $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
  761. $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  762. $course = api_get_course_info_by_id($courseId);
  763. $where = " WHERE c_id = '%s' AND s.status <> 2 ";
  764. $limit = null;
  765. if (!empty($options['limit'])) {
  766. $limit = " LIMIT " . $options['limit'];
  767. }
  768. if (!empty($options['where'])) {
  769. $where .= ' '.$options['where'];
  770. }
  771. $order = null;
  772. if (!empty($options['order'])) {
  773. $order = " ORDER BY " . $options['order'];
  774. }
  775. //TODO, fix create report without session
  776. $queryVariables = array($course['real_id']);
  777. if (!empty($sessionId)) {
  778. $where .= ' AND session_id = %s';
  779. $queryVariables[] = $sessionId;
  780. $sql = "SELECT
  781. u.user_id, u.lastname, u.firstname, u.username,
  782. u.email, s.c_id, s.session_id
  783. FROM $session_course_user s
  784. INNER JOIN $user u
  785. ON u.user_id = s.user_id
  786. $where $order $limit";
  787. } else {
  788. $sql = "SELECT
  789. u.user_id, u.lastname, u.firstname, u.username,
  790. u.email, s.c_id, s.session_id
  791. FROM $session_course_user s
  792. INNER JOIN $user u ON u.user_id = s.user_id
  793. $where $order $limit";
  794. }
  795. $sql_query = vsprintf($sql, $queryVariables);
  796. $rs = Database::query($sql_query);
  797. while ($user = Database::fetch_array($rs)) {
  798. $users[$user['user_id']] = $user;
  799. }
  800. /**
  801. * Lessons
  802. */
  803. $sql = "SELECT * FROM $tbl_course_lp WHERE c_id = %s "; //AND session_id = %s
  804. $sql_query = sprintf($sql, $course['real_id']);
  805. $result = Database::query($sql_query);
  806. $arrLesson = array(array());
  807. while ($row = Database::fetch_array($result)) {
  808. if (empty($arrLesson[$row['session_id']]['lessons_total'])) {
  809. $arrLesson[$row['session_id']]['lessons_total'] = 1;
  810. } else {
  811. $arrLesson[$row['session_id']]['lessons_total'] ++;
  812. }
  813. }
  814. /**
  815. * Exercises
  816. */
  817. $exercises = ExerciseLib::get_all_exercises($course, $sessionId, false, '', $getAllSessions);
  818. $exercises_total = count($exercises);
  819. /**
  820. * Assignments
  821. */
  822. //total
  823. if ($getAllSessions) {
  824. $sql = "SELECT count(w.id) as count
  825. FROM $workTable w
  826. LEFT JOIN $workTableAssignment a
  827. ON (a.publication_id = w.id AND a.c_id = w.c_id)
  828. WHERE w.c_id = %s
  829. AND parent_id = 0
  830. AND active IN (1, 0)";
  831. } else {
  832. $sql = "SELECT count(w.id) as count
  833. FROM $workTable w
  834. LEFT JOIN $workTableAssignment a
  835. ON (a.publication_id = w.id AND a.c_id = w.c_id)
  836. WHERE w.c_id = %s
  837. AND parent_id = 0
  838. AND active IN (1, 0)
  839. AND session_id = %s";
  840. }
  841. $sql_query = sprintf($sql, $course['real_id'], $sessionId);
  842. $result = Database::query($sql_query);
  843. $row = Database::fetch_array($result);
  844. $assignments_total = $row['count'];
  845. /**
  846. * Wiki
  847. */
  848. if ($getAllSessions) {
  849. $sql = "SELECT count(distinct page_id) as count FROM $wiki
  850. WHERE c_id = %s";
  851. } else {
  852. $sql = "SELECT count(distinct page_id) as count FROM $wiki
  853. WHERE c_id = %s and session_id = %s";
  854. }
  855. $sql_query = sprintf($sql, $course['real_id'], $sessionId);
  856. $result = Database::query($sql_query);
  857. $row = Database::fetch_array($result);
  858. $wiki_total = $row['count'];
  859. /**
  860. * Surveys
  861. */
  862. $survey_user_list = array();
  863. $survey_list = SurveyManager::get_surveys($course['code'], $sessionId);
  864. $surveys_total = count($survey_list);
  865. foreach ($survey_list as $survey) {
  866. $user_list = SurveyManager::get_people_who_filled_survey(
  867. $survey['survey_id'],
  868. false,
  869. $course['real_id']
  870. );
  871. foreach ($user_list as $user_id) {
  872. isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id] ++ : $survey_user_list[$user_id] = 1;
  873. }
  874. }
  875. /**
  876. * Forums
  877. */
  878. $forums_total = CourseManager::getCountForum(
  879. $course['real_id'],
  880. $sessionId,
  881. $getAllSessions
  882. );
  883. //process table info
  884. foreach ($users as $user) {
  885. //Course description
  886. $sql = "SELECT count(*) as count
  887. FROM $table_stats_access
  888. WHERE access_tool = 'course_description'
  889. AND c_id = '%s'
  890. AND access_session_id = %s
  891. AND access_user_id = %s ";
  892. $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
  893. $result = Database::query($sql_query);
  894. $row = Database::fetch_array($result);
  895. $course_description_progress = ($row['count'] > 0) ? 100 : 0;
  896. if (!empty($arrLesson[$user['id_session']]['lessons_total'])) {
  897. $lessons_total = $arrLesson[$user['id_session']]['lessons_total'];
  898. } else {
  899. $lessons_total = !empty($arrLesson[0]['lessons_total']) ? $arrLesson[0]['lessons_total'] : 0;
  900. }
  901. //Lessons
  902. //TODO: Lessons done and left is calculated by progress per item in lesson, maybe we should calculate it only per completed lesson?
  903. $lessons_progress = Tracking::get_avg_student_progress(
  904. $user['user_id'],
  905. $course['code'],
  906. array(),
  907. $user['id_session']
  908. );
  909. $lessons_done = ($lessons_progress * $lessons_total) / 100;
  910. $lessons_left = $lessons_total - $lessons_done;
  911. //Exercises
  912. $exercises_progress = str_replace('%', '', Tracking::get_exercise_student_progress($exercises, $user['user_id'], $course['real_id'], $user['id_session']));
  913. $exercises_done = round(($exercises_progress * $exercises_total) / 100);
  914. $exercises_left = $exercises_total - $exercises_done;
  915. //Assignments
  916. $assignments_done = Tracking::count_student_assignments($user['user_id'], $course['code'], $user['id_session']);
  917. $assignments_left = $assignments_total - $assignments_done;
  918. if (!empty($assignments_total)) {
  919. $assignments_progress = round((( $assignments_done * 100 ) / $assignments_total), 2);
  920. } else {
  921. $assignments_progress = 0;
  922. }
  923. //Wiki
  924. //total revisions per user
  925. $sql = "SELECT count(*) as count
  926. FROM $wiki
  927. WHERE c_id = %s and session_id = %s and user_id = %s";
  928. $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
  929. $result = Database::query($sql_query);
  930. $row = Database::fetch_array($result);
  931. $wiki_revisions = $row['count'];
  932. //count visited wiki pages
  933. $sql = "SELECT count(distinct default_value) as count
  934. FROM $table_stats_default
  935. WHERE
  936. default_user_id = %s AND
  937. default_event_type = 'wiki_page_view' AND
  938. default_value_type = 'wiki_page_id' AND
  939. c_id = %s
  940. ";
  941. $sql_query = sprintf($sql, $user['user_id'], $course['real_id']);
  942. $result = Database::query($sql_query);
  943. $row = Database::fetch_array($result);
  944. $wiki_read = $row['count'];
  945. $wiki_unread = $wiki_total - $wiki_read;
  946. if (!empty($wiki_total)) {
  947. $wiki_progress = round((( $wiki_read * 100 ) / $wiki_total), 2);
  948. } else {
  949. $wiki_progress = 0;
  950. }
  951. //Surveys
  952. $surveys_done = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0);
  953. $surveys_left = $surveys_total - $surveys_done;
  954. if (!empty($surveys_total)) {
  955. $surveys_progress = round((( $surveys_done * 100 ) / $surveys_total), 2);
  956. } else {
  957. $surveys_progress = 0;
  958. }
  959. //Forums
  960. $forums_done = CourseManager::getCountForumPerUser(
  961. $user['user_id'],
  962. $course['real_id'],
  963. $user['id_session']
  964. );
  965. $forums_left = $forums_total - $forums_done;
  966. if (!empty($forums_total)) {
  967. $forums_progress = round((( $forums_done * 100 ) / $forums_total), 2);
  968. } else {
  969. $forums_progress = 0;
  970. }
  971. //Overall Total
  972. $overall_total = ($course_description_progress + $exercises_progress + $forums_progress + $assignments_progress + $wiki_progress + $surveys_progress) / 6;
  973. $link = '<a href="' . api_get_path(WEB_CODE_PATH) . 'mySpace/myStudents.php?student=' . $user[0] . '&details=true&course=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
  974. $linkForum = '<a href="' . api_get_path(WEB_CODE_PATH) . 'forum/index.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
  975. $linkWork = '<a href="' . api_get_path(WEB_CODE_PATH) . 'work/work.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
  976. $linkWiki = '<a href="' . api_get_path(WEB_CODE_PATH) . 'wiki/index.php?cidReq=' . $course['code'] . '&session_id=' . $user['id_session'] . '&action=statistics"> %s </a>';
  977. $linkSurvey = '<a href="' . api_get_path(WEB_CODE_PATH) . 'survey/survey_list.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
  978. $table[] = array(
  979. 'lastname' => $user[1],
  980. 'firstname' => $user[2],
  981. 'username' => $user[3],
  982. #'profile' => '',
  983. 'total' => round($overall_total, 2) . '%',
  984. 'courses' => sprintf($link, $course_description_progress . '%'),
  985. 'lessons' => sprintf($link, $lessons_progress . '%'),
  986. 'exercises' => sprintf($link, $exercises_progress . '%'),
  987. 'forums' => sprintf($link, $forums_progress . '%'),
  988. 'homeworks' => sprintf($link, $assignments_progress . '%'),
  989. 'wikis' => sprintf($link, $wiki_progress . '%'),
  990. 'surveys' => sprintf($link, $surveys_progress . '%'),
  991. //course description
  992. 'course_description_progress' => $course_description_progress . '%',
  993. //lessons
  994. 'lessons_total' => sprintf($link, $lessons_total),
  995. 'lessons_done' => sprintf($link, $lessons_done),
  996. 'lessons_left' => sprintf($link, $lessons_left),
  997. 'lessons_progress' => sprintf($link, $lessons_progress . '%'),
  998. //exercises
  999. 'exercises_total' => sprintf($link, $exercises_total),
  1000. 'exercises_done' => sprintf($link, $exercises_done),
  1001. 'exercises_left' => sprintf($link, $exercises_left),
  1002. 'exercises_progress' => sprintf($link, $exercises_progress . '%'),
  1003. //forums
  1004. 'forums_total' => sprintf($linkForum, $forums_total),
  1005. 'forums_done' => sprintf($linkForum, $forums_done),
  1006. 'forums_left' => sprintf($linkForum, $forums_left),
  1007. 'forums_progress' => sprintf($linkForum, $forums_progress . '%'),
  1008. //assignments
  1009. 'assignments_total' => sprintf($linkWork, $assignments_total),
  1010. 'assignments_done' => sprintf($linkWork, $assignments_done),
  1011. 'assignments_left' => sprintf($linkWork, $assignments_left),
  1012. 'assignments_progress' => sprintf($linkWork, $assignments_progress . '%'),
  1013. //wiki
  1014. 'wiki_total' => sprintf($linkWiki, $wiki_total),
  1015. 'wiki_revisions' => sprintf($linkWiki, $wiki_revisions),
  1016. 'wiki_read' => sprintf($linkWiki, $wiki_read),
  1017. 'wiki_unread' => sprintf($linkWiki, $wiki_unread),
  1018. 'wiki_progress' => sprintf($linkWiki, $wiki_progress . '%'),
  1019. //survey
  1020. 'surveys_total' => sprintf($linkSurvey, $surveys_total),
  1021. 'surveys_done' => sprintf($linkSurvey, $surveys_done),
  1022. 'surveys_left' => sprintf($linkSurvey, $surveys_left),
  1023. 'surveys_progress' => sprintf($linkSurvey, $surveys_progress . '%'),
  1024. );
  1025. }
  1026. return $table;
  1027. }
  1028. /**
  1029. * @return int
  1030. */
  1031. public static function get_number_of_tracking_access_overview()
  1032. {
  1033. // database table definition
  1034. $track_e_course_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1035. return Database::count_rows($track_e_course_access);
  1036. }
  1037. /**
  1038. * Get the ip, total of clicks, login date and time logged in for all user, in one session
  1039. * @todo track_e_course_access table should have ip so we dont have to look for it in track_e_login
  1040. *
  1041. * @author César Perales <cesar.perales@beeznest.com>, Beeznest Team
  1042. * @version 1.9.6
  1043. */
  1044. public static function get_user_data_access_tracking_overview(
  1045. $sessionId,
  1046. $courseId,
  1047. $studentId = 0,
  1048. $profile = '',
  1049. $date_from = '',
  1050. $date_to = '',
  1051. $options
  1052. ) {
  1053. //escaping variables
  1054. $sessionId = intval($sessionId);
  1055. $courseId = intval($courseId);
  1056. $studentId = intval($studentId);
  1057. $profile = intval($profile);
  1058. $date_from = Database::escape_string($date_from);
  1059. $date_to = Database::escape_string($date_to);
  1060. // database table definition
  1061. $user = Database :: get_main_table(TABLE_MAIN_USER);
  1062. $course = Database :: get_main_table(TABLE_MAIN_COURSE);
  1063. $track_e_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1064. $track_e_course_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1065. $sessionTable = Database :: get_main_table(TABLE_MAIN_SESSION);
  1066. global $export_csv;
  1067. if ($export_csv) {
  1068. $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
  1069. } else {
  1070. $is_western_name_order = api_is_western_name_order();
  1071. }
  1072. $where = null;
  1073. if (isset($sessionId) && !empty($sessionId)) {
  1074. $where = sprintf(" WHERE a.session_id = %d", $sessionId);
  1075. }
  1076. if (isset($courseId) && !empty($courseId)) {
  1077. $where .= sprintf(" AND c.id = %d", $courseId);
  1078. }
  1079. if (isset($studentId) && !empty($studentId)) {
  1080. $where .= sprintf(" AND u.user_id = %d", $studentId);
  1081. }
  1082. if (isset($profile) && !empty($profile)) {
  1083. $where .= sprintf(" AND u.status = %d", $profile);
  1084. }
  1085. if (!empty($date_to) && !empty($date_from)) {
  1086. $where .= sprintf(
  1087. " AND a.login_course_date >= '%s 00:00:00'
  1088. AND a.login_course_date <= '%s 23:59:59'",
  1089. $date_from,
  1090. $date_to
  1091. );
  1092. }
  1093. $limit = null;
  1094. if (!empty($options['limit'])) {
  1095. $limit = " LIMIT " . $options['limit'];
  1096. }
  1097. if (!empty($options['where'])) {
  1098. $where .= ' '.$options['where'];
  1099. }
  1100. $order = null;
  1101. if (!empty($options['order'])) {
  1102. $order = " ORDER BY " . $options['order'];
  1103. }
  1104. //TODO add course name
  1105. $sql = "SELECT
  1106. a.login_course_date ,
  1107. u.username ,
  1108. " . ($is_western_name_order ? "
  1109. u.firstname,
  1110. u.lastname,
  1111. " : "
  1112. u.lastname,
  1113. u.firstname,
  1114. ") . "
  1115. a.logout_course_date,
  1116. a.counter,
  1117. c.title,
  1118. c.code,
  1119. u.user_id,
  1120. a.session_id
  1121. FROM $track_e_course_access a
  1122. INNER JOIN $user u ON a.user_id = u.user_id
  1123. INNER JOIN $course c ON a.c_id = c.id
  1124. $where $order $limit";
  1125. $result = Database::query(sprintf($sql, $sessionId, $courseId));
  1126. $data = array();
  1127. while ($user = Database::fetch_assoc($result)) {
  1128. $data[] = $user;
  1129. }
  1130. //foreach
  1131. foreach ($data as $key => $info) {
  1132. $sql = "SELECT
  1133. name
  1134. FROM $sessionTable
  1135. WHERE
  1136. id = {$info['session_id']}";
  1137. $result = Database::query($sql);
  1138. $session = Database::fetch_assoc($result);
  1139. // building array to display
  1140. $return[] = array(
  1141. 'user_id' => $info['user_id'],
  1142. 'logindate' => $info['login_course_date'],
  1143. 'username' => $info['username'],
  1144. 'firstname' => $info['firstname'],
  1145. 'lastname' => $info['lastname'],
  1146. 'clicks' => $info['counter'], //+ $clicks[$info['user_id']],
  1147. 'ip' => '',
  1148. 'timeLoggedIn' => gmdate("H:i:s", strtotime($info['logout_course_date']) - strtotime($info['login_course_date'])),
  1149. 'session' => $session['name']
  1150. );
  1151. }
  1152. foreach ($return as $key => $info) {
  1153. //Search for ip, we do less querys if we iterate the final array
  1154. $sql = sprintf("SELECT user_ip FROM $track_e_login WHERE login_user_id = %d AND login_date < '%s' ORDER BY login_date DESC LIMIT 1", $info['user_id'], $info['logindate']); //TODO add select by user too
  1155. $result = Database::query($sql);
  1156. $ip = Database::fetch_assoc($result);
  1157. //if no ip founded, we search the closest higher ip
  1158. if (empty($ip['user_ip'])) {
  1159. $sql = sprintf("SELECT user_ip FROM $track_e_login WHERE login_user_id = %d AND login_date > '%s' ORDER BY login_date ASC LIMIT 1", $info['user_id'], $info['logindate']); //TODO add select by user too
  1160. $result = Database::query($sql);
  1161. $ip = Database::fetch_assoc($result);
  1162. }
  1163. #add ip to final array
  1164. $return[$key]['ip'] = $ip['user_ip'];
  1165. }
  1166. return $return;
  1167. }
  1168. /**
  1169. * Creates a new course code based in given code
  1170. *
  1171. * @param string $session_name
  1172. * <code>
  1173. * $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3
  1174. * if the course code doest not exist in the DB the same course code will be returned
  1175. * </code>
  1176. * @return string wanted unused code
  1177. */
  1178. public static function generateNextSessionName($session_name)
  1179. {
  1180. $session_name_ok = !self::session_name_exists($session_name);
  1181. if (!$session_name_ok) {
  1182. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  1183. $session_name = Database::escape_string($session_name);
  1184. $sql = "SELECT count(*) as count FROM $table
  1185. WHERE name LIKE '$session_name%'";
  1186. $result = Database::query($sql);
  1187. if (Database::num_rows($result) > 0) {
  1188. $row = Database::fetch_array($result);
  1189. $count = $row['count'] + 1;
  1190. $session_name = $session_name . '_' . $count;
  1191. $result = self::session_name_exists($session_name);
  1192. if (!$result) {
  1193. return $session_name;
  1194. }
  1195. }
  1196. return false;
  1197. }
  1198. return $session_name;
  1199. }
  1200. /**
  1201. * Edit a session
  1202. * @author Carlos Vargas from existing code
  1203. * @param integer $id Session primary key
  1204. * @param string $name
  1205. * @param string $startDate
  1206. * @param string $endDate
  1207. * @param string $displayStartDate
  1208. * @param string $displayEndDate
  1209. * @param string $coachStartDate
  1210. * @param string $coachEndDate
  1211. * @param integer $coachId
  1212. * @param integer $sessionCategoryId
  1213. * @param int $visibility
  1214. * @param string $description
  1215. * @param int $showDescription
  1216. * @param int $duration
  1217. * @param array $extraFields
  1218. * @param int $sessionAdminId
  1219. * @param boolean $sendSubscriptionNotification Optional.
  1220. * Whether send a mail notification to users being subscribed
  1221. * @return mixed
  1222. */
  1223. public static function edit_session(
  1224. $id,
  1225. $name,
  1226. $startDate,
  1227. $endDate,
  1228. $displayStartDate,
  1229. $displayEndDate,
  1230. $coachStartDate,
  1231. $coachEndDate,
  1232. $coachId,
  1233. $sessionCategoryId,
  1234. $visibility,
  1235. $description = null,
  1236. $showDescription = 0,
  1237. $duration = null,
  1238. $extraFields = array(),
  1239. $sessionAdminId = 0,
  1240. $sendSubscriptionNotification = false
  1241. ) {
  1242. $name = trim(stripslashes($name));
  1243. $coachId = intval($coachId);
  1244. $sessionCategoryId = intval($sessionCategoryId);
  1245. $visibility = intval($visibility);
  1246. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1247. if (empty($name)) {
  1248. Display::return_message(get_lang('SessionNameIsRequired'), 'warning');
  1249. return false;
  1250. } elseif (empty($coachId)) {
  1251. Display::return_message(get_lang('CoachIsRequired'), 'warning');
  1252. return false;
  1253. } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i') && !api_is_valid_date($startDate, 'Y-m-d H:i:s')) {
  1254. Display::return_message(get_lang('InvalidStartDate'), 'warning');
  1255. return false;
  1256. } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i') && !api_is_valid_date($endDate, 'Y-m-d H:i:s')) {
  1257. Display::return_message(get_lang('InvalidEndDate'), 'warning');
  1258. return false;
  1259. } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
  1260. Display::return_message(get_lang('StartDateShouldBeBeforeEndDate'), 'warning');
  1261. return false;
  1262. } else {
  1263. $sql = "SELECT id FROM $tbl_session WHERE name='" . Database::escape_string($name) . "'";
  1264. $rs = Database::query($sql);
  1265. $exists = false;
  1266. while ($row = Database::fetch_array($rs)) {
  1267. if ($row['id'] != $id) {
  1268. $exists = true;
  1269. }
  1270. }
  1271. if ($exists) {
  1272. Display::return_message(get_lang('SessionNameAlreadyExists'), 'warning');
  1273. return false;
  1274. } else {
  1275. $values = [
  1276. 'name' => $name,
  1277. 'duration' => $duration,
  1278. 'id_coach' => $coachId,
  1279. 'description'=> $description,
  1280. 'show_description' => intval($showDescription),
  1281. 'visibility' => $visibility,
  1282. 'send_subscription_notification' => $sendSubscriptionNotification
  1283. ];
  1284. if (!empty($sessionAdminId)) {
  1285. $values['session_admin_id'] = $sessionAdminId;
  1286. }
  1287. if (!empty($startDate)) {
  1288. $values['access_start_date'] = api_get_utc_datetime($startDate);
  1289. }
  1290. if (!empty($endDate)) {
  1291. $values['access_end_date'] = api_get_utc_datetime($endDate);
  1292. }
  1293. if (!empty($displayStartDate)) {
  1294. $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
  1295. }
  1296. if (!empty($displayEndDate)) {
  1297. $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
  1298. }
  1299. if (!empty($coachStartDate)) {
  1300. $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
  1301. }
  1302. if (!empty($coachEndDate)) {
  1303. $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
  1304. }
  1305. if (!empty($sessionCategoryId)) {
  1306. $values['session_category_id'] = $sessionCategoryId;
  1307. } else {
  1308. $values['session_category_id'] = null;
  1309. }
  1310. Database::update($tbl_session, $values, array(
  1311. 'id = ?' => $id
  1312. ));
  1313. if (!empty($extraFields)) {
  1314. $extraFields['item_id'] = $id;
  1315. $sessionFieldValue = new ExtraFieldValue('session');
  1316. $sessionFieldValue->saveFieldValues($extraFields);
  1317. }
  1318. return $id;
  1319. }
  1320. }
  1321. }
  1322. /**
  1323. * Delete session
  1324. * @author Carlos Vargas from existing code
  1325. * @param array $id_checked an array to delete sessions
  1326. * @param boolean $from_ws optional, true if the function is called
  1327. * by a webservice, false otherwise.
  1328. * @return void Nothing, or false on error
  1329. * */
  1330. public static function delete($id_checked, $from_ws = false)
  1331. {
  1332. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1333. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1334. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1335. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1336. $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1337. $tbl_item_properties = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1338. $em = Database::getManager();
  1339. $userId = api_get_user_id();
  1340. if (is_array($id_checked)) {
  1341. foreach ($id_checked as $sessionId) {
  1342. self::delete($sessionId);
  1343. }
  1344. } else {
  1345. $id_checked = intval($id_checked);
  1346. }
  1347. if (SessionManager::allowed($id_checked) && !$from_ws) {
  1348. $qb = $em
  1349. ->createQuery('
  1350. SELECT s.sessionAdminId FROM ChamiloCoreBundle:Session s
  1351. WHERE s.id = ?1
  1352. ')
  1353. ->setParameter(1, $id_checked);
  1354. $res = $qb->getSingleScalarResult();
  1355. if ($res != $userId && !api_is_platform_admin()) {
  1356. api_not_allowed(true);
  1357. }
  1358. }
  1359. // Delete documents inside a session
  1360. $courses = SessionManager::getCoursesInSession($id_checked);
  1361. foreach ($courses as $courseId) {
  1362. $courseInfo = api_get_course_info_by_id($courseId);
  1363. DocumentManager::deleteDocumentsFromSession($courseInfo, $id_checked);
  1364. }
  1365. Database::query("DELETE FROM $tbl_session_rel_course WHERE session_id IN($id_checked)");
  1366. Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id IN($id_checked)");
  1367. Database::query("DELETE FROM $tbl_session_rel_user WHERE session_id IN($id_checked)");
  1368. Database::query("DELETE FROM $tbl_item_properties WHERE session_id IN ($id_checked)");
  1369. Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
  1370. Database::query("DELETE FROM $tbl_session WHERE id IN ($id_checked)");
  1371. $extraFieldValue = new ExtraFieldValue('session');
  1372. $extraFieldValue->deleteValuesByItem($id_checked);
  1373. /** @var \Chamilo\CoreBundle\Entity\Repository\SequenceRepository $repo */
  1374. $repo = Database::getManager()->getRepository('ChamiloCoreBundle:SequenceResource');
  1375. $repo->deleteResource(
  1376. $id_checked,
  1377. \Chamilo\CoreBundle\Entity\SequenceResource::SESSION_TYPE
  1378. );
  1379. // Add event to system log
  1380. Event::addEvent(
  1381. LOG_SESSION_DELETE,
  1382. LOG_SESSION_ID,
  1383. $id_checked,
  1384. api_get_utc_datetime(),
  1385. $userId
  1386. );
  1387. }
  1388. /**
  1389. * @param int $id_promotion
  1390. *
  1391. * @return bool
  1392. */
  1393. public static function clear_session_ref_promotion($id_promotion)
  1394. {
  1395. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1396. $id_promotion = intval($id_promotion);
  1397. $sql = "UPDATE $tbl_session SET promotion_id=0
  1398. WHERE promotion_id = $id_promotion";
  1399. if (Database::query($sql)) {
  1400. return true;
  1401. } else {
  1402. return false;
  1403. }
  1404. }
  1405. /**
  1406. * Subscribes students to the given session and optionally (default) unsubscribes previous users
  1407. *
  1408. * @author Carlos Vargas from existing code
  1409. * @author Julio Montoya. Cleaning code.
  1410. * @param int $id_session
  1411. * @param array $user_list
  1412. * @param int $session_visibility
  1413. * @param bool $empty_users
  1414. * @return bool
  1415. */
  1416. public static function suscribe_users_to_session(
  1417. $id_session,
  1418. $user_list,
  1419. $session_visibility = SESSION_VISIBLE_READ_ONLY,
  1420. $empty_users = true
  1421. ) {
  1422. if ($id_session != strval(intval($id_session))) {
  1423. return false;
  1424. }
  1425. foreach ($user_list as $intUser) {
  1426. if ($intUser != strval(intval($intUser))) {
  1427. return false;
  1428. }
  1429. }
  1430. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1431. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1432. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1433. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1434. $entityManager = Database::getManager();
  1435. $session = $entityManager->find('ChamiloCoreBundle:Session', $id_session);
  1436. // from function parameter
  1437. if (empty($session_visibility)) {
  1438. $session_visibility = $session->getVisibility();
  1439. //default status loaded if empty
  1440. if (empty($session_visibility))
  1441. $session_visibility = SESSION_VISIBLE_READ_ONLY; // by default readonly 1
  1442. } else {
  1443. if (!in_array($session_visibility, array(SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_INVISIBLE))) {
  1444. $session_visibility = SESSION_VISIBLE_READ_ONLY;
  1445. }
  1446. }
  1447. $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user
  1448. WHERE session_id = $id_session AND status = 0";
  1449. $result = Database::query($sql);
  1450. $existingUsers = array();
  1451. while ($row = Database::fetch_array($result)) {
  1452. $existingUsers[] = $row['user_id'];
  1453. }
  1454. $sql = "SELECT c_id FROM $tbl_session_rel_course
  1455. WHERE session_id = $id_session";
  1456. $result = Database::query($sql);
  1457. $course_list = array();
  1458. while ($row = Database::fetch_array($result)) {
  1459. $course_list[] = $row['c_id'];
  1460. }
  1461. if (
  1462. $session->getSendSubscriptionNotification() &&
  1463. is_array($user_list)
  1464. ) {
  1465. // Sending emails only
  1466. foreach ($user_list as $user_id) {
  1467. if (in_array($user_id, $existingUsers)) {
  1468. continue;
  1469. }
  1470. $tplSubject = new Template(null, false, false, false, false, false);
  1471. $layoutSubject = $tplSubject->get_template(
  1472. 'mail/subject_subscription_to_session_confirmation.tpl'
  1473. );
  1474. $subject = $tplSubject->fetch($layoutSubject);
  1475. $user_info = api_get_user_info($user_id);
  1476. $tplContent = new Template(null, false, false, false, false, false);
  1477. // Variables for default template
  1478. $tplContent->assign(
  1479. 'complete_name',
  1480. stripslashes($user_info['complete_name'])
  1481. );
  1482. $tplContent->assign('session_name', $session->getName());
  1483. $tplContent->assign(
  1484. 'session_coach',
  1485. $session->getGeneralCoach()->getCompleteName()
  1486. );
  1487. $layoutContent = $tplContent->get_template(
  1488. 'mail/content_subscription_to_session_confirmation.tpl'
  1489. );
  1490. $content = $tplContent->fetch($layoutContent);
  1491. api_mail_html(
  1492. $user_info['complete_name'],
  1493. $user_info['mail'],
  1494. $subject,
  1495. $content,
  1496. api_get_person_name(
  1497. api_get_setting('administratorName'),
  1498. api_get_setting('administratorSurname')
  1499. ),
  1500. api_get_setting('emailAdministrator')
  1501. );
  1502. }
  1503. }
  1504. foreach ($course_list as $courseId) {
  1505. // for each course in the session
  1506. $nbr_users = 0;
  1507. $courseId = intval($courseId);
  1508. $sql = "SELECT DISTINCT user_id
  1509. FROM $tbl_session_rel_course_rel_user
  1510. WHERE
  1511. session_id = $id_session AND
  1512. c_id = $courseId AND
  1513. status = 0
  1514. ";
  1515. $result = Database::query($sql);
  1516. $existingUsers = array();
  1517. while ($row = Database::fetch_array($result)) {
  1518. $existingUsers[] = $row['user_id'];
  1519. }
  1520. // Delete existing users
  1521. if ($empty_users) {
  1522. foreach ($existingUsers as $existing_user) {
  1523. if (!in_array($existing_user, $user_list)) {
  1524. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  1525. WHERE
  1526. session_id = $id_session AND
  1527. c_id = $courseId AND
  1528. user_id = $existing_user AND
  1529. status = 0 ";
  1530. $result = Database::query($sql);
  1531. Event::addEvent(
  1532. LOG_SESSION_DELETE_USER_COURSE,
  1533. LOG_USER_ID,
  1534. $existing_user,
  1535. api_get_utc_datetime(),
  1536. api_get_user_id(),
  1537. $courseId,
  1538. $id_session
  1539. );
  1540. if (Database::affected_rows($result)) {
  1541. $nbr_users--;
  1542. }
  1543. }
  1544. }
  1545. }
  1546. // Replace with this new function
  1547. // insert new users into session_rel_course_rel_user and ignore if they already exist
  1548. foreach ($user_list as $enreg_user) {
  1549. if (!in_array($enreg_user, $existingUsers)) {
  1550. $enreg_user = Database::escape_string($enreg_user);
  1551. $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility, status)
  1552. VALUES($id_session, $courseId, $enreg_user, $session_visibility, 0)";
  1553. $result = Database::query($sql);
  1554. Event::addEvent(
  1555. LOG_SESSION_ADD_USER_COURSE,
  1556. LOG_USER_ID,
  1557. $enreg_user,
  1558. api_get_utc_datetime(),
  1559. api_get_user_id(),
  1560. $courseId,
  1561. $id_session
  1562. );
  1563. if (Database::affected_rows($result)) {
  1564. $nbr_users++;
  1565. }
  1566. }
  1567. }
  1568. // Count users in this session-course relation
  1569. $sql = "SELECT COUNT(user_id) as nbUsers
  1570. FROM $tbl_session_rel_course_rel_user
  1571. WHERE session_id = $id_session AND c_id = $courseId AND status<>2";
  1572. $rs = Database::query($sql);
  1573. list($nbr_users) = Database::fetch_array($rs);
  1574. // update the session-course relation to add the users total
  1575. $sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users
  1576. WHERE session_id = $id_session AND c_id = $courseId";
  1577. Database::query($sql);
  1578. }
  1579. // Delete users from the session
  1580. if ($empty_users === true) {
  1581. $sql = "DELETE FROM $tbl_session_rel_user
  1582. WHERE session_id = $id_session AND relation_type<>" . SESSION_RELATION_TYPE_RRHH . "";
  1583. Database::query($sql);
  1584. }
  1585. // Insert missing users into session
  1586. $nbr_users = 0;
  1587. foreach ($user_list as $enreg_user) {
  1588. $enreg_user = Database::escape_string($enreg_user);
  1589. $nbr_users++;
  1590. $sql = "INSERT IGNORE INTO $tbl_session_rel_user (relation_type, session_id, user_id, registered_at)
  1591. VALUES (0, $id_session, $enreg_user, '" . api_get_utc_datetime() . "')";
  1592. Database::query($sql);
  1593. }
  1594. // update number of users in the session
  1595. $nbr_users = count($user_list);
  1596. if ($empty_users) {
  1597. // update number of users in the session
  1598. $sql = "UPDATE $tbl_session SET nbr_users= $nbr_users
  1599. WHERE id = $id_session ";
  1600. Database::query($sql);
  1601. } else {
  1602. $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + $nbr_users
  1603. WHERE id = $id_session";
  1604. Database::query($sql);
  1605. }
  1606. }
  1607. /**
  1608. * Returns user list of the current users subscribed in the course-session
  1609. * @param int $sessionId
  1610. * @param array $courseInfo
  1611. * @param int $status
  1612. *
  1613. * @return array
  1614. */
  1615. public static function getUsersByCourseSession(
  1616. $sessionId,
  1617. $courseInfo,
  1618. $status = null
  1619. ) {
  1620. $sessionId = intval($sessionId);
  1621. $courseCode = $courseInfo['code'];
  1622. $courseId = $courseInfo['real_id'];
  1623. if (empty($sessionId) || empty($courseCode)) {
  1624. return array();
  1625. }
  1626. $statusCondition = null;
  1627. if (isset($status) && !is_null($status)) {
  1628. $status = intval($status);
  1629. $statusCondition = " AND status = $status";
  1630. }
  1631. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1632. $sql = "SELECT DISTINCT user_id
  1633. FROM $table
  1634. WHERE
  1635. session_id = $sessionId AND
  1636. c_id = $courseId
  1637. $statusCondition
  1638. ";
  1639. $result = Database::query($sql);
  1640. $existingUsers = array();
  1641. while ($row = Database::fetch_array($result)) {
  1642. $existingUsers[] = $row['user_id'];
  1643. }
  1644. return $existingUsers;
  1645. }
  1646. /**
  1647. * Remove a list of users from a course-session
  1648. * @param array $userList
  1649. * @param int $sessionId
  1650. * @param array $courseInfo
  1651. * @param int $status
  1652. * @param bool $updateTotal
  1653. * @return bool
  1654. */
  1655. public static function removeUsersFromCourseSession(
  1656. $userList,
  1657. $sessionId,
  1658. $courseInfo,
  1659. $status = null,
  1660. $updateTotal = true
  1661. ) {
  1662. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1663. $tableSessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1664. $sessionId = intval($sessionId);
  1665. if (empty($sessionId) || empty($userList) || empty($courseInfo)) {
  1666. return false;
  1667. }
  1668. is_array($courseInfo) ? $courseId = $courseInfo['real_id'] : $courseId = $courseInfo;
  1669. $statusCondition = null;
  1670. if (isset($status) && !is_null($status)) {
  1671. $status = intval($status);
  1672. $statusCondition = " AND status = $status";
  1673. }
  1674. foreach ($userList as $userId) {
  1675. $userId = intval($userId);
  1676. $sql = "DELETE FROM $table
  1677. WHERE
  1678. session_id = $sessionId AND
  1679. c_id = $courseId AND
  1680. user_id = $userId
  1681. $statusCondition
  1682. ";
  1683. Database::query($sql);
  1684. }
  1685. if ($updateTotal) {
  1686. // Count users in this session-course relation
  1687. $sql = "SELECT COUNT(user_id) as nbUsers
  1688. FROM $table
  1689. WHERE
  1690. session_id = $sessionId AND
  1691. c_id = $courseId AND
  1692. status <> 2";
  1693. $result = Database::query($sql);
  1694. list($userCount) = Database::fetch_array($result);
  1695. // update the session-course relation to add the users total
  1696. $sql = "UPDATE $tableSessionCourse
  1697. SET nbr_users = $userCount
  1698. WHERE
  1699. session_id = $sessionId AND
  1700. c_id = $courseId";
  1701. Database::query($sql);
  1702. }
  1703. }
  1704. /**
  1705. * Subscribe a user to an specific course inside a session.
  1706. *
  1707. * @param array $user_list
  1708. * @param int $session_id
  1709. * @param string $course_code
  1710. * @param int $session_visibility
  1711. * @param bool $removeUsersNotInList
  1712. * @return bool
  1713. */
  1714. public static function subscribe_users_to_session_course(
  1715. $user_list,
  1716. $session_id,
  1717. $course_code,
  1718. $session_visibility = SESSION_VISIBLE_READ_ONLY,
  1719. $removeUsersNotInList = false
  1720. ) {
  1721. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1722. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1723. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1724. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1725. if (empty($session_id) || empty($course_code)) {
  1726. return false;
  1727. }
  1728. $session_id = intval($session_id);
  1729. $course_code = Database::escape_string($course_code);
  1730. $courseInfo = api_get_course_info($course_code);
  1731. $courseId = $courseInfo['real_id'];
  1732. $session_visibility = intval($session_visibility);
  1733. if ($removeUsersNotInList) {
  1734. $currentUsers = self::getUsersByCourseSession($session_id, $courseInfo, 0);
  1735. if (!empty($user_list)) {
  1736. $userToDelete = array_diff($currentUsers, $user_list);
  1737. } else {
  1738. $userToDelete = $currentUsers;
  1739. }
  1740. if (!empty($userToDelete)) {
  1741. self::removeUsersFromCourseSession(
  1742. $userToDelete,
  1743. $session_id,
  1744. $courseInfo,
  1745. 0,
  1746. true
  1747. );
  1748. }
  1749. }
  1750. $nbr_users = 0;
  1751. foreach ($user_list as $enreg_user) {
  1752. $enreg_user = intval($enreg_user);
  1753. // Checking if user exists in session - course - user table.
  1754. $sql = "SELECT count(user_id) as count
  1755. FROM $tbl_session_rel_course_rel_user
  1756. WHERE
  1757. session_id = $session_id AND
  1758. c_id = $courseId and
  1759. user_id = $enreg_user ";
  1760. $result = Database::query($sql);
  1761. $count = 0;
  1762. if (Database::num_rows($result) > 0) {
  1763. $row = Database::fetch_array($result, 'ASSOC');
  1764. $count = $row['count'];
  1765. }
  1766. if ($count == 0) {
  1767. $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility)
  1768. VALUES ($session_id, $courseId, $enreg_user, $session_visibility)";
  1769. $result = Database::query($sql);
  1770. if (Database::affected_rows($result)) {
  1771. $nbr_users++;
  1772. }
  1773. }
  1774. // Checking if user exists in session - user table.
  1775. $sql = "SELECT count(user_id) as count
  1776. FROM $tbl_session_rel_user
  1777. WHERE session_id = $session_id AND user_id = $enreg_user ";
  1778. $result = Database::query($sql);
  1779. $count = 0;
  1780. if (Database::num_rows($result) > 0) {
  1781. $row = Database::fetch_array($result, 'ASSOC');
  1782. $count = $row['count'];
  1783. }
  1784. if (empty($count)) {
  1785. // If user is not registered to a session then add it.
  1786. $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, registered_at)
  1787. VALUES ($session_id, $enreg_user, '" . api_get_utc_datetime() . "')";
  1788. Database::query($sql);
  1789. $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + 1
  1790. WHERE id = $session_id ";
  1791. Database::query($sql);
  1792. }
  1793. }
  1794. // count users in this session-course relation
  1795. $sql = "SELECT COUNT(user_id) as nbUsers
  1796. FROM $tbl_session_rel_course_rel_user
  1797. WHERE session_id = $session_id AND c_id = $courseId AND status <> 2";
  1798. $rs = Database::query($sql);
  1799. list($nbr_users) = Database::fetch_array($rs);
  1800. // update the session-course relation to add the users total
  1801. $sql = "UPDATE $tbl_session_rel_course
  1802. SET nbr_users = $nbr_users
  1803. WHERE session_id = $session_id AND c_id = $courseId";
  1804. Database::query($sql);
  1805. }
  1806. /**
  1807. * Unsubscribe user from session
  1808. *
  1809. * @param int Session id
  1810. * @param int User id
  1811. * @return bool True in case of success, false in case of error
  1812. */
  1813. public static function unsubscribe_user_from_session($session_id, $user_id)
  1814. {
  1815. $session_id = (int) $session_id;
  1816. $user_id = (int) $user_id;
  1817. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1818. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1819. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1820. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1821. $delete_sql = "DELETE FROM $tbl_session_rel_user
  1822. WHERE
  1823. session_id = $session_id AND
  1824. user_id = $user_id AND
  1825. relation_type <> " . SESSION_RELATION_TYPE_RRHH . "";
  1826. $result = Database::query($delete_sql);
  1827. $return = Database::affected_rows($result);
  1828. // Update number of users
  1829. $sql = "UPDATE $tbl_session
  1830. SET nbr_users = nbr_users - $return
  1831. WHERE id = $session_id ";
  1832. Database::query($sql);
  1833. // Get the list of courses related to this session
  1834. $course_list = SessionManager::get_course_list_by_session_id($session_id);
  1835. if (!empty($course_list)) {
  1836. foreach ($course_list as $course) {
  1837. $courseId = $course['id'];
  1838. // Delete user from course
  1839. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  1840. WHERE session_id = $session_id AND c_id = $courseId AND user_id = $user_id";
  1841. $result = Database::query($sql);
  1842. Event::addEvent(
  1843. LOG_SESSION_DELETE_USER_COURSE,
  1844. LOG_USER_ID,
  1845. $user_id,
  1846. api_get_utc_datetime(),
  1847. api_get_user_id(),
  1848. $courseId,
  1849. $session_id
  1850. );
  1851. if (Database::affected_rows($result)) {
  1852. // Update number of users in this relation
  1853. $sql = "UPDATE $tbl_session_rel_course SET nbr_users = nbr_users - 1
  1854. WHERE session_id = $session_id AND c_id = $courseId";
  1855. Database::query($sql);
  1856. }
  1857. }
  1858. }
  1859. return true;
  1860. }
  1861. /**
  1862. * Subscribes courses to the given session and optionally (default)
  1863. * unsubscribes previous users
  1864. * @author Carlos Vargas from existing code
  1865. * @param int $sessionId
  1866. * @param array $courseList List of courses int ids
  1867. * @param bool $removeExistingCoursesWithUsers Whether to unsubscribe
  1868. * existing courses and users (true, default) or not (false)
  1869. * @param $copyEvaluation from base course to session course
  1870. * @return void Nothing, or false on error
  1871. * */
  1872. public static function add_courses_to_session(
  1873. $sessionId,
  1874. $courseList,
  1875. $removeExistingCoursesWithUsers = true,
  1876. $copyEvaluation = false
  1877. ) {
  1878. $sessionId = intval($sessionId);
  1879. if (empty($sessionId) || empty($courseList)) {
  1880. return false;
  1881. }
  1882. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1883. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1884. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1885. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1886. // Get list of courses subscribed to this session
  1887. $sql = "SELECT c_id
  1888. FROM $tbl_session_rel_course
  1889. WHERE session_id = $sessionId";
  1890. $rs = Database::query($sql);
  1891. $existingCourses = Database::store_result($rs);
  1892. $nbr_courses = count($existingCourses);
  1893. // Get list of users subscribed to this session
  1894. $sql = "SELECT user_id
  1895. FROM $tbl_session_rel_user
  1896. WHERE
  1897. session_id = $sessionId AND
  1898. relation_type<>" . SESSION_RELATION_TYPE_RRHH;
  1899. $result = Database::query($sql);
  1900. $user_list = Database::store_result($result);
  1901. // Remove existing courses from the session.
  1902. if ($removeExistingCoursesWithUsers === true && !empty($existingCourses)) {
  1903. foreach ($existingCourses as $existingCourse) {
  1904. if (!in_array($existingCourse['c_id'], $courseList)) {
  1905. $sql = "DELETE FROM $tbl_session_rel_course
  1906. WHERE
  1907. c_id = " . $existingCourse['c_id'] . " AND
  1908. session_id = $sessionId";
  1909. Database::query($sql);
  1910. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  1911. WHERE
  1912. c_id = ".$existingCourse['c_id']." AND
  1913. session_id = $sessionId";
  1914. Database::query($sql);
  1915. Event::addEvent(
  1916. LOG_SESSION_DELETE_COURSE,
  1917. LOG_COURSE_ID,
  1918. $existingCourse['c_id'],
  1919. api_get_utc_datetime(),
  1920. api_get_user_id(),
  1921. $existingCourse['c_id'],
  1922. $sessionId
  1923. );
  1924. CourseManager::remove_course_ranking(
  1925. $existingCourse['c_id'],
  1926. $sessionId
  1927. );
  1928. $nbr_courses--;
  1929. }
  1930. }
  1931. }
  1932. // Pass through the courses list we want to add to the session
  1933. foreach ($courseList as $courseId) {
  1934. $courseInfo = api_get_course_info_by_id($courseId);
  1935. // If course doesn't exists continue!
  1936. if (empty($courseInfo)) {
  1937. continue;
  1938. }
  1939. $exists = false;
  1940. // check if the course we want to add is already subscribed
  1941. foreach ($existingCourses as $existingCourse) {
  1942. if ($courseId == $existingCourse['c_id']) {
  1943. $exists = true;
  1944. }
  1945. }
  1946. if (!$exists) {
  1947. // Copy gradebook categories and links (from base course)
  1948. // to the new course session
  1949. if ($copyEvaluation) {
  1950. $cats = Category::load(null, null, $courseInfo['code']);
  1951. if (!empty($cats)) {
  1952. $categoryIdList = [];
  1953. /** @var Category $cat */
  1954. foreach ($cats as $cat) {
  1955. $categoryIdList[$cat->get_id()] = $cat->get_id();
  1956. }
  1957. $newCategoryIdList = [];
  1958. foreach ($cats as $cat) {
  1959. $links = $cat->get_links(null, false, $courseInfo['code'], 0);
  1960. $cat->set_session_id($sessionId);
  1961. $oldCategoryId= $cat->get_id();
  1962. $newId = $cat->add();
  1963. $newCategoryIdList[$oldCategoryId] = $newId;
  1964. $parentId = $cat->get_parent_id();
  1965. if (!empty($parentId)) {
  1966. $newParentId = $newCategoryIdList[$parentId];
  1967. $cat->set_parent_id($newParentId);
  1968. $cat->save();
  1969. }
  1970. /** @var AbstractLink $link */
  1971. foreach ($links as $link) {
  1972. $newCategoryId = $newCategoryIdList[$link->get_category_id()];
  1973. $link->set_category_id($newCategoryId);
  1974. $link->add();
  1975. }
  1976. }
  1977. // Create
  1978. DocumentManager::generateDefaultCertificate(
  1979. $courseInfo,
  1980. true,
  1981. $sessionId
  1982. );
  1983. }
  1984. }
  1985. // If the course isn't subscribed yet
  1986. $sql = "INSERT INTO $tbl_session_rel_course (session_id, c_id, nbr_users, position)
  1987. VALUES ($sessionId, $courseId, 0, 0)";
  1988. Database::query($sql);
  1989. Event::addEvent(
  1990. LOG_SESSION_ADD_COURSE,
  1991. LOG_COURSE_ID,
  1992. $courseId,
  1993. api_get_utc_datetime(),
  1994. api_get_user_id(),
  1995. $courseId,
  1996. $sessionId
  1997. );
  1998. // We add the current course in the existing courses array,
  1999. // to avoid adding another time the current course
  2000. $existingCourses[] = array('c_id' => $courseId);
  2001. $nbr_courses++;
  2002. // subscribe all the users from the session to this course inside the session
  2003. $nbr_users = 0;
  2004. foreach ($user_list as $enreg_user) {
  2005. $enreg_user_id = intval($enreg_user['user_id']);
  2006. $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id)
  2007. VALUES ($sessionId, $courseId, $enreg_user_id)";
  2008. $result = Database::query($sql);
  2009. Event::addEvent(
  2010. LOG_SESSION_ADD_USER_COURSE,
  2011. LOG_USER_ID,
  2012. $enreg_user_id,
  2013. api_get_utc_datetime(),
  2014. api_get_user_id(),
  2015. $courseId,
  2016. $sessionId
  2017. );
  2018. if (Database::affected_rows($result)) {
  2019. $nbr_users++;
  2020. }
  2021. }
  2022. $sql = "UPDATE $tbl_session_rel_course
  2023. SET nbr_users = $nbr_users
  2024. WHERE session_id = $sessionId AND c_id = $courseId";
  2025. Database::query($sql);
  2026. }
  2027. }
  2028. $sql = "UPDATE $tbl_session
  2029. SET nbr_courses = $nbr_courses
  2030. WHERE id = $sessionId";
  2031. Database::query($sql);
  2032. }
  2033. /**
  2034. * Unsubscribe course from a session
  2035. *
  2036. * @param int Session id
  2037. * @param int Course id
  2038. * @return bool True in case of success, false otherwise
  2039. */
  2040. public static function unsubscribe_course_from_session($session_id, $course_id)
  2041. {
  2042. $session_id = (int) $session_id;
  2043. $course_id = (int) $course_id;
  2044. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2045. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2046. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2047. // Get course code
  2048. $course_code = CourseManager::get_course_code_from_course_id($course_id);
  2049. $course_id = intval($course_id);
  2050. if (empty($course_code)) {
  2051. return false;
  2052. }
  2053. // Unsubscribe course
  2054. $sql = "DELETE FROM $tbl_session_rel_course
  2055. WHERE c_id = $course_id AND session_id = $session_id";
  2056. $result = Database::query($sql);
  2057. $nb_affected = Database::affected_rows($result);
  2058. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  2059. WHERE c_id = $course_id AND session_id = $session_id";
  2060. Database::query($sql);
  2061. Event::addEvent(
  2062. LOG_SESSION_DELETE_COURSE,
  2063. LOG_COURSE_ID,
  2064. $course_id,
  2065. api_get_utc_datetime(),
  2066. api_get_user_id(),
  2067. $course_id,
  2068. $session_id
  2069. );
  2070. if ($nb_affected > 0) {
  2071. // Update number of courses in the session
  2072. $sql = "UPDATE $tbl_session SET nbr_courses= nbr_courses - $nb_affected
  2073. WHERE id = $session_id";
  2074. Database::query($sql);
  2075. return true;
  2076. } else {
  2077. return false;
  2078. }
  2079. }
  2080. /**
  2081. * Creates a new extra field for a given session
  2082. * @param string $variable Field's internal variable name
  2083. * @param int $fieldType Field's type
  2084. * @param string $displayText Field's language var name
  2085. * @return int new extra field id
  2086. */
  2087. public static function create_session_extra_field($variable, $fieldType, $displayText)
  2088. {
  2089. $extraField = new ExtraField('session');
  2090. $params = [
  2091. 'variable' => $variable,
  2092. 'field_type' => $fieldType,
  2093. 'display_text' => $displayText,
  2094. ];
  2095. return $extraField->save($params);
  2096. }
  2097. /**
  2098. * Update an extra field value for a given session
  2099. * @param integer Course ID
  2100. * @param string Field variable name
  2101. * @param string Field value
  2102. * @return boolean true if field updated, false otherwise
  2103. */
  2104. public static function update_session_extra_field_value($sessionId, $variable, $value = '')
  2105. {
  2106. $extraFieldValue = new ExtraFieldValue('session');
  2107. $params = [
  2108. 'item_id' => $sessionId,
  2109. 'variable' => $variable,
  2110. 'value' => $value,
  2111. ];
  2112. return $extraFieldValue->save($params);
  2113. }
  2114. /**
  2115. * Checks the relationship between a session and a course.
  2116. * @param int $session_id
  2117. * @param int $courseId
  2118. * @return bool Returns TRUE if the session and the course are related, FALSE otherwise.
  2119. * */
  2120. public static function relation_session_course_exist($session_id, $courseId)
  2121. {
  2122. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2123. $return_value = false;
  2124. $sql = "SELECT c_id FROM $tbl_session_course
  2125. WHERE
  2126. session_id = " . intval($session_id) . " AND
  2127. c_id = " . intval($courseId) . "";
  2128. $result = Database::query($sql);
  2129. $num = Database::num_rows($result);
  2130. if ($num > 0) {
  2131. $return_value = true;
  2132. }
  2133. return $return_value;
  2134. }
  2135. /**
  2136. * Get the session information by name
  2137. * @param string session name
  2138. * @return mixed false if the session does not exist, array if the session exist
  2139. * */
  2140. public static function get_session_by_name($session_name)
  2141. {
  2142. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2143. $session_name = trim($session_name);
  2144. if (empty($session_name)) {
  2145. return false;
  2146. }
  2147. $sql = 'SELECT *
  2148. FROM ' . $tbl_session . '
  2149. WHERE name = "' . Database::escape_string($session_name) . '"';
  2150. $result = Database::query($sql);
  2151. $num = Database::num_rows($result);
  2152. if ($num > 0) {
  2153. return Database::fetch_array($result);
  2154. } else {
  2155. return false;
  2156. }
  2157. }
  2158. /**
  2159. * Create a session category
  2160. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
  2161. * @param string name
  2162. * @param integer year_start
  2163. * @param integer month_start
  2164. * @param integer day_start
  2165. * @param integer year_end
  2166. * @param integer month_end
  2167. * @param integer day_end
  2168. * @return $id_session;
  2169. * */
  2170. public static function create_category_session(
  2171. $sname,
  2172. $syear_start,
  2173. $smonth_start,
  2174. $sday_start,
  2175. $syear_end,
  2176. $smonth_end,
  2177. $sday_end
  2178. ) {
  2179. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2180. $name = trim($sname);
  2181. $year_start = intval($syear_start);
  2182. $month_start = intval($smonth_start);
  2183. $day_start = intval($sday_start);
  2184. $year_end = intval($syear_end);
  2185. $month_end = intval($smonth_end);
  2186. $day_end = intval($sday_end);
  2187. $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
  2188. $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
  2189. if (empty($name)) {
  2190. $msg = get_lang('SessionCategoryNameIsRequired');
  2191. return $msg;
  2192. } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
  2193. $msg = get_lang('InvalidStartDate');
  2194. return $msg;
  2195. } elseif (!$month_end && !$day_end && !$year_end) {
  2196. $date_end = "null";
  2197. } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
  2198. $msg = get_lang('InvalidEndDate');
  2199. return $msg;
  2200. } elseif ($date_start >= $date_end) {
  2201. $msg = get_lang('StartDateShouldBeBeforeEndDate');
  2202. return $msg;
  2203. }
  2204. $access_url_id = api_get_current_access_url_id();
  2205. $params = [
  2206. 'name' => $name,
  2207. 'date_start' => $date_start,
  2208. 'date_end' => $date_end,
  2209. 'access_url_id' => $access_url_id
  2210. ];
  2211. $id_session = Database::insert($tbl_session_category, $params);
  2212. // Add event to system log
  2213. $user_id = api_get_user_id();
  2214. Event::addEvent(
  2215. LOG_SESSION_CATEGORY_CREATE,
  2216. LOG_SESSION_CATEGORY_ID,
  2217. $id_session,
  2218. api_get_utc_datetime(),
  2219. $user_id
  2220. );
  2221. return $id_session;
  2222. }
  2223. /**
  2224. * Edit a sessions categories
  2225. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,from existing code
  2226. * @param integer id
  2227. * @param string name
  2228. * @param integer year_start
  2229. * @param integer month_start
  2230. * @param integer day_start
  2231. * @param integer year_end
  2232. * @param integer month_end
  2233. * @param integer day_end
  2234. * @return $id;
  2235. * The parameter id is a primary key
  2236. * */
  2237. public static function edit_category_session(
  2238. $id,
  2239. $sname,
  2240. $syear_start,
  2241. $smonth_start,
  2242. $sday_start,
  2243. $syear_end,
  2244. $smonth_end,
  2245. $sday_end
  2246. ) {
  2247. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2248. $name = trim($sname);
  2249. $year_start = intval($syear_start);
  2250. $month_start = intval($smonth_start);
  2251. $day_start = intval($sday_start);
  2252. $year_end = intval($syear_end);
  2253. $month_end = intval($smonth_end);
  2254. $day_end = intval($sday_end);
  2255. $id = intval($id);
  2256. $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
  2257. $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
  2258. if (empty($name)) {
  2259. $msg = get_lang('SessionCategoryNameIsRequired');
  2260. return $msg;
  2261. } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
  2262. $msg = get_lang('InvalidStartDate');
  2263. return $msg;
  2264. } elseif (!$month_end && !$day_end && !$year_end) {
  2265. $date_end = null;
  2266. } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
  2267. $msg = get_lang('InvalidEndDate');
  2268. return $msg;
  2269. } elseif ($date_start >= $date_end) {
  2270. $msg = get_lang('StartDateShouldBeBeforeEndDate');
  2271. return $msg;
  2272. }
  2273. if ($date_end <> null) {
  2274. $sql = "UPDATE $tbl_session_category
  2275. SET
  2276. name = '" . Database::escape_string($name) . "',
  2277. date_start = '$date_start' ,
  2278. date_end = '$date_end'
  2279. WHERE id= $id";
  2280. } else {
  2281. $sql = "UPDATE $tbl_session_category SET
  2282. name = '" . Database::escape_string($name) . "',
  2283. date_start = '$date_start',
  2284. date_end = NULL
  2285. WHERE id= $id";
  2286. }
  2287. $result = Database::query($sql);
  2288. return ($result ? true : false);
  2289. }
  2290. /**
  2291. * Delete sessions categories
  2292. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
  2293. * @param array id_checked
  2294. * @param bool include delete session
  2295. * @param bool optional, true if the function is called by a webservice, false otherwise.
  2296. * @return void Nothing, or false on error
  2297. * The parameters is a array to delete sessions
  2298. * */
  2299. public static function delete_session_category($id_checked, $delete_session = false, $from_ws = false)
  2300. {
  2301. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2302. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2303. if (is_array($id_checked)) {
  2304. $id_checked = Database::escape_string(implode(',', $id_checked));
  2305. } else {
  2306. $id_checked = intval($id_checked);
  2307. }
  2308. //Setting session_category_id to 0
  2309. $sql = "UPDATE $tbl_session SET session_category_id = 0
  2310. WHERE session_category_id IN (" . $id_checked . ")";
  2311. Database::query($sql);
  2312. $sql = "SELECT id FROM $tbl_session WHERE session_category_id IN (" . $id_checked . ")";
  2313. $result = Database::query($sql);
  2314. while ($rows = Database::fetch_array($result)) {
  2315. $session_id = $rows['id'];
  2316. if ($delete_session) {
  2317. if ($from_ws) {
  2318. SessionManager::delete($session_id, true);
  2319. } else {
  2320. SessionManager::delete($session_id);
  2321. }
  2322. }
  2323. }
  2324. $sql = "DELETE FROM $tbl_session_category WHERE id IN (" . $id_checked . ")";
  2325. Database::query($sql);
  2326. // Add event to system log
  2327. $user_id = api_get_user_id();
  2328. Event::addEvent(
  2329. LOG_SESSION_CATEGORY_DELETE,
  2330. LOG_SESSION_CATEGORY_ID,
  2331. $id_checked,
  2332. api_get_utc_datetime(),
  2333. $user_id
  2334. );
  2335. return true;
  2336. }
  2337. /**
  2338. * Get a list of sessions of which the given conditions match with an = 'cond'
  2339. * @param array $conditions a list of condition example :
  2340. * array('status' => STUDENT) or
  2341. * array('s.name' => array('operator' => 'LIKE', value = '%$needle%'))
  2342. * @param array $order_by a list of fields on which sort
  2343. * @return array An array with all sessions of the platform.
  2344. * @todo optional course code parameter, optional sorting parameters...
  2345. */
  2346. public static function get_sessions_list($conditions = array(), $order_by = array(), $from = null, $to = null)
  2347. {
  2348. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  2349. $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2350. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  2351. $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2352. $session_course_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2353. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  2354. $access_url_id = api_get_current_access_url_id();
  2355. $return_array = array();
  2356. $sql_query = " SELECT
  2357. s.id,
  2358. s.name,
  2359. s.nbr_courses,
  2360. s.access_start_date,
  2361. s.access_end_date,
  2362. u.firstname,
  2363. u.lastname,
  2364. sc.name as category_name,
  2365. s.promotion_id
  2366. FROM $session_table s
  2367. INNER JOIN $user_table u ON s.id_coach = u.user_id
  2368. INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
  2369. LEFT JOIN $session_category_table sc ON s.session_category_id = sc.id
  2370. LEFT JOIN $session_course_table sco ON (sco.session_id = s.id)
  2371. INNER JOIN $course_table c ON sco.c_id = c.id
  2372. WHERE ar.access_url_id = $access_url_id ";
  2373. $availableFields = array(
  2374. 's.id',
  2375. 's.name',
  2376. 'c.id'
  2377. );
  2378. $availableOperator = array(
  2379. 'like',
  2380. '>=',
  2381. '<=',
  2382. '=',
  2383. );
  2384. if (count($conditions) > 0) {
  2385. foreach ($conditions as $field => $options) {
  2386. $operator = strtolower($options['operator']);
  2387. $value = Database::escape_string($options['value']);
  2388. $sql_query .= ' AND ';
  2389. if (in_array($field, $availableFields) && in_array($operator, $availableOperator)) {
  2390. $sql_query .= $field . " $operator '" . $value . "'";
  2391. }
  2392. }
  2393. }
  2394. $orderAvailableList = array('name');
  2395. if (count($order_by) > 0) {
  2396. $order = null;
  2397. $direction = null;
  2398. if (isset($order_by[0]) && in_array($order_by[0], $orderAvailableList)) {
  2399. $order = $order_by[0];
  2400. }
  2401. if (isset($order_by[1]) && in_array(strtolower($order_by[1]), array('desc', 'asc'))) {
  2402. $direction = $order_by[1];
  2403. }
  2404. if (!empty($order)) {
  2405. $sql_query .= " ORDER BY $order $direction ";
  2406. }
  2407. }
  2408. if (!is_null($from) && !is_null($to)) {
  2409. $to = intval($to);
  2410. $from = intval($from);
  2411. $sql_query .= "LIMIT $from, $to";
  2412. }
  2413. $sql_result = Database::query($sql_query);
  2414. if (Database::num_rows($sql_result) > 0) {
  2415. while ($result = Database::fetch_array($sql_result)) {
  2416. $return_array[$result['id']] = $result;
  2417. }
  2418. }
  2419. return $return_array;
  2420. }
  2421. /**
  2422. * Get the session category information by id
  2423. * @param string session category ID
  2424. * @return mixed false if the session category does not exist, array if the session category exists
  2425. */
  2426. public static function get_session_category($id)
  2427. {
  2428. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2429. $id = intval($id);
  2430. $sql = "SELECT id, name, date_start, date_end
  2431. FROM $tbl_session_category
  2432. WHERE id= $id";
  2433. $result = Database::query($sql);
  2434. $num = Database::num_rows($result);
  2435. if ($num > 0) {
  2436. return Database::fetch_array($result);
  2437. } else {
  2438. return false;
  2439. }
  2440. }
  2441. /**
  2442. * Get all session categories (filter by access_url_id)
  2443. * @return mixed false if the session category does not exist, array if the session category exists
  2444. */
  2445. public static function get_all_session_category()
  2446. {
  2447. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2448. $id = api_get_current_access_url_id();
  2449. $sql = 'SELECT * FROM ' . $tbl_session_category . '
  2450. WHERE access_url_id = ' . $id . '
  2451. ORDER BY name ASC';
  2452. $result = Database::query($sql);
  2453. if (Database::num_rows($result) > 0) {
  2454. $data = Database::store_result($result, 'ASSOC');
  2455. return $data;
  2456. } else {
  2457. return false;
  2458. }
  2459. }
  2460. /**
  2461. * Assign a coach to course in session with status = 2
  2462. * @param int $user_id
  2463. * @param int $session_id
  2464. * @param int $courseId
  2465. * @param bool $nocoach optional, if is true the user don't be a coach now,
  2466. * otherwise it'll assign a coach
  2467. * @return bool true if there are affected rows, otherwise false
  2468. */
  2469. public static function set_coach_to_course_session(
  2470. $user_id,
  2471. $session_id = 0,
  2472. $courseId = 0,
  2473. $nocoach = false
  2474. ) {
  2475. // Definition of variables
  2476. $user_id = intval($user_id);
  2477. if (!empty($session_id)) {
  2478. $session_id = intval($session_id);
  2479. } else {
  2480. $session_id = api_get_session_id();
  2481. }
  2482. if (!empty($courseId)) {
  2483. $courseId = intval($courseId);
  2484. } else {
  2485. $courseId = api_get_course_id();
  2486. }
  2487. // Table definition
  2488. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2489. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2490. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2491. // check if user is a teacher
  2492. $sql = "SELECT * FROM $tbl_user
  2493. WHERE status = 1 AND user_id = $user_id";
  2494. $rs_check_user = Database::query($sql);
  2495. if (Database::num_rows($rs_check_user) > 0) {
  2496. if ($nocoach) {
  2497. // check if user_id exists in session_rel_user (if the user is
  2498. // subscribed to the session in any manner)
  2499. $sql = "SELECT user_id FROM $tbl_session_rel_user
  2500. WHERE
  2501. session_id = $session_id AND
  2502. user_id = $user_id";
  2503. $res = Database::query($sql);
  2504. if (Database::num_rows($res) > 0) {
  2505. // The user is already subscribed to the session. Change the
  2506. // record so the user is NOT a coach for this course anymore
  2507. // and then exit
  2508. $sql = "UPDATE $tbl_session_rel_course_rel_user
  2509. SET status = 0
  2510. WHERE
  2511. session_id = $session_id AND
  2512. c_id = $courseId AND
  2513. user_id = $user_id ";
  2514. $result = Database::query($sql);
  2515. if (Database::affected_rows($result) > 0)
  2516. return true;
  2517. else
  2518. return false;
  2519. } else {
  2520. // The user is not subscribed to the session, so make sure
  2521. // he isn't subscribed to a course in this session either
  2522. // and then exit
  2523. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  2524. WHERE
  2525. session_id = $session_id AND
  2526. c_id = $courseId AND
  2527. user_id = $user_id ";
  2528. $result = Database::query($sql);
  2529. if (Database::affected_rows($result) > 0)
  2530. return true;
  2531. else
  2532. return false;
  2533. }
  2534. } else {
  2535. // Assign user as a coach to course
  2536. // First check if the user is registered to the course
  2537. $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user
  2538. WHERE
  2539. session_id = $session_id AND
  2540. c_id = $courseId AND
  2541. user_id = $user_id";
  2542. $rs_check = Database::query($sql);
  2543. // Then update or insert.
  2544. if (Database::num_rows($rs_check) > 0) {
  2545. $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 2
  2546. WHERE
  2547. session_id = $session_id AND
  2548. c_id = $courseId AND
  2549. user_id = $user_id ";
  2550. $result = Database::query($sql);
  2551. if (Database::affected_rows($result) > 0) {
  2552. return true;
  2553. } else {
  2554. return false;
  2555. }
  2556. } else {
  2557. $sql = "INSERT INTO $tbl_session_rel_course_rel_user(session_id, c_id, user_id, status)
  2558. VALUES($session_id, $courseId, $user_id, 2)";
  2559. $result = Database::query($sql);
  2560. if (Database::affected_rows($result) > 0) {
  2561. return true;
  2562. } else {
  2563. return false;
  2564. }
  2565. }
  2566. }
  2567. } else {
  2568. return false;
  2569. }
  2570. }
  2571. /**
  2572. * Subscribes sessions to human resource manager (Dashboard feature)
  2573. * @param array $userInfo Human Resource Manager info
  2574. * @param array $sessions_list Sessions id
  2575. * @param bool $sendEmail
  2576. * @param bool $removeOldConnections
  2577. * @return int
  2578. * */
  2579. public static function suscribe_sessions_to_hr_manager(
  2580. $userInfo,
  2581. $sessions_list,
  2582. $sendEmail = false,
  2583. $removeOldConnections = true
  2584. ) {
  2585. // Database Table Definitions
  2586. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2587. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2588. if (empty($userInfo)) {
  2589. return 0;
  2590. }
  2591. $userId = $userInfo['user_id'];
  2592. // Only subscribe DRH users.
  2593. $rolesAllowed = array(
  2594. DRH,
  2595. SESSIONADMIN,
  2596. PLATFORM_ADMIN,
  2597. COURSE_TUTOR
  2598. );
  2599. $isAdmin = api_is_platform_admin_by_id($userInfo['user_id']);
  2600. if (!$isAdmin && !in_array($userInfo['status'], $rolesAllowed)) {
  2601. return 0;
  2602. }
  2603. $affected_rows = 0;
  2604. // Deleting assigned sessions to hrm_id.
  2605. if ($removeOldConnections) {
  2606. if (api_is_multiple_url_enabled()) {
  2607. $sql = "SELECT session_id
  2608. FROM $tbl_session_rel_user s
  2609. INNER JOIN $tbl_session_rel_access_url a ON (a.session_id = s.session_id)
  2610. WHERE
  2611. s.user_id = $userId AND
  2612. relation_type=" . SESSION_RELATION_TYPE_RRHH . " AND
  2613. access_url_id = " . api_get_current_access_url_id() . "";
  2614. } else {
  2615. $sql = "SELECT session_id FROM $tbl_session_rel_user s
  2616. WHERE user_id = $userId AND relation_type=" . SESSION_RELATION_TYPE_RRHH . "";
  2617. }
  2618. $result = Database::query($sql);
  2619. if (Database::num_rows($result) > 0) {
  2620. while ($row = Database::fetch_array($result)) {
  2621. $sql = "DELETE FROM $tbl_session_rel_user
  2622. WHERE
  2623. session_id = {$row['session_id']} AND
  2624. user_id = $userId AND
  2625. relation_type=" . SESSION_RELATION_TYPE_RRHH . " ";
  2626. Database::query($sql);
  2627. }
  2628. }
  2629. }
  2630. // Inserting new sessions list.
  2631. if (!empty($sessions_list) && is_array($sessions_list)) {
  2632. foreach ($sessions_list as $session_id) {
  2633. $session_id = intval($session_id);
  2634. $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, relation_type, registered_at)
  2635. VALUES (
  2636. $session_id,
  2637. $userId,
  2638. '" . SESSION_RELATION_TYPE_RRHH . "',
  2639. '" . api_get_utc_datetime() . "'
  2640. )";
  2641. Database::query($sql);
  2642. $affected_rows++;
  2643. }
  2644. }
  2645. return $affected_rows;
  2646. }
  2647. /**
  2648. * @param int $sessionId
  2649. * @return array
  2650. */
  2651. public static function getDrhUsersInSession($sessionId)
  2652. {
  2653. return self::get_users_by_session($sessionId, SESSION_RELATION_TYPE_RRHH);
  2654. }
  2655. /**
  2656. * @param int $userId
  2657. * @param int $sessionId
  2658. * @return array
  2659. */
  2660. public static function getSessionFollowedByDrh($userId, $sessionId)
  2661. {
  2662. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2663. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2664. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2665. $userId = intval($userId);
  2666. $sessionId = intval($sessionId);
  2667. $select = " SELECT * ";
  2668. if (api_is_multiple_url_enabled()) {
  2669. $sql = " $select FROM $tbl_session s
  2670. INNER JOIN $tbl_session_rel_user sru ON (sru.session_id = s.id)
  2671. LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
  2672. WHERE
  2673. sru.user_id = '$userId' AND
  2674. sru.session_id = '$sessionId' AND
  2675. sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "' AND
  2676. access_url_id = " . api_get_current_access_url_id() . "
  2677. ";
  2678. } else {
  2679. $sql = "$select FROM $tbl_session s
  2680. INNER JOIN $tbl_session_rel_user sru
  2681. ON
  2682. sru.session_id = s.id AND
  2683. sru.user_id = '$userId' AND
  2684. sru.session_id = '$sessionId' AND
  2685. sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "'
  2686. ";
  2687. }
  2688. $result = Database::query($sql);
  2689. if (Database::num_rows($result)) {
  2690. $row = Database::fetch_array($result, 'ASSOC');
  2691. $row['course_list'] = self::get_course_list_by_session_id($sessionId);
  2692. return $row;
  2693. }
  2694. return array();
  2695. }
  2696. /**
  2697. * Get sessions followed by human resources manager
  2698. * @param int $userId
  2699. * @param int $start
  2700. * @param int $limit
  2701. * @param bool $getCount
  2702. * @param bool $getOnlySessionId
  2703. * @param bool $getSql
  2704. * @param string $orderCondition
  2705. * @param string $description
  2706. *
  2707. * @return array sessions
  2708. */
  2709. public static function get_sessions_followed_by_drh(
  2710. $userId,
  2711. $start = null,
  2712. $limit = null,
  2713. $getCount = false,
  2714. $getOnlySessionId = false,
  2715. $getSql = false,
  2716. $orderCondition = null,
  2717. $keyword = '',
  2718. $description = ''
  2719. ) {
  2720. return self::getSessionsFollowedByUser(
  2721. $userId,
  2722. DRH,
  2723. $start,
  2724. $limit,
  2725. $getCount,
  2726. $getOnlySessionId,
  2727. $getSql,
  2728. $orderCondition,
  2729. $keyword,
  2730. $description
  2731. );
  2732. }
  2733. /**
  2734. * Get sessions followed by human resources manager
  2735. * @param int $userId
  2736. * @param int $start
  2737. * @param int $limit
  2738. * @param bool $getCount
  2739. * @param bool $getOnlySessionId
  2740. * @param bool $getSql
  2741. * @param string $orderCondition
  2742. * @param string $keyword
  2743. * @param string $description
  2744. * @return array sessions
  2745. */
  2746. public static function getSessionsFollowedByUser(
  2747. $userId,
  2748. $status = null,
  2749. $start = null,
  2750. $limit = null,
  2751. $getCount = false,
  2752. $getOnlySessionId = false,
  2753. $getSql = false,
  2754. $orderCondition = null,
  2755. $keyword = '',
  2756. $description = ''
  2757. ) {
  2758. // Database Table Definitions
  2759. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2760. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2761. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2762. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2763. $userId = intval($userId);
  2764. $select = " SELECT DISTINCT * ";
  2765. if ($getCount) {
  2766. $select = " SELECT count(DISTINCT(s.id)) as count ";
  2767. }
  2768. if ($getOnlySessionId) {
  2769. $select = " SELECT DISTINCT(s.id) ";
  2770. }
  2771. $limitCondition = null;
  2772. if (!empty($start) && !empty($limit)) {
  2773. $limitCondition = " LIMIT " . intval($start) . ", " . intval($limit);
  2774. }
  2775. if (empty($orderCondition)) {
  2776. $orderCondition = " ORDER BY s.name ";
  2777. }
  2778. $whereConditions = null;
  2779. $sessionCourseConditions = null;
  2780. $sessionConditions = null;
  2781. $sessionQuery = null;
  2782. $courseSessionQuery = null;
  2783. switch ($status) {
  2784. case DRH:
  2785. $sessionQuery = "SELECT sru.session_id
  2786. FROM
  2787. $tbl_session_rel_user sru
  2788. WHERE
  2789. sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
  2790. sru.user_id = $userId";
  2791. break;
  2792. case COURSEMANAGER:
  2793. $courseSessionQuery = "
  2794. SELECT scu.session_id as id
  2795. FROM $tbl_session_rel_course_rel_user scu
  2796. WHERE (scu.status = 2 AND scu.user_id = $userId)";
  2797. $whereConditions = " OR (s.id_coach = $userId) ";
  2798. break;
  2799. default:
  2800. $sessionQuery = "SELECT sru.session_id
  2801. FROM
  2802. $tbl_session_rel_user sru
  2803. WHERE
  2804. sru.user_id = $userId";
  2805. break;
  2806. }
  2807. $keywordCondition = '';
  2808. if (!empty($keyword)) {
  2809. $keyword = Database::escape_string($keyword);
  2810. $keywordCondition = " AND (s.name LIKE '%$keyword%' ) ";
  2811. if (!empty($description)) {
  2812. $description = Database::escape_string($description);
  2813. $keywordCondition = " AND (s.name LIKE '%$keyword%' OR s.description LIKE '%$description%' ) ";
  2814. }
  2815. }
  2816. $whereConditions .= $keywordCondition;
  2817. $subQuery = $sessionQuery.$courseSessionQuery;
  2818. $sql = " $select FROM $tbl_session s
  2819. INNER JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
  2820. WHERE
  2821. access_url_id = ".api_get_current_access_url_id()." AND
  2822. s.id IN (
  2823. $subQuery
  2824. )
  2825. $whereConditions
  2826. $orderCondition
  2827. $limitCondition";
  2828. if ($getSql) {
  2829. return $sql;
  2830. }
  2831. $result = Database::query($sql);
  2832. if ($getCount) {
  2833. $row = Database::fetch_array($result);
  2834. return $row['count'];
  2835. }
  2836. $sessions = array();
  2837. if (Database::num_rows($result) > 0) {
  2838. $sysUploadPath = api_get_path(SYS_UPLOAD_PATH). 'sessions/';
  2839. $webUploadPath = api_get_path(WEB_UPLOAD_PATH). 'sessions/';
  2840. $imgPath = Display::return_icon('session_default_small.png', null, null, null, null, true);
  2841. $tableExtraFields = Database::get_main_table(TABLE_EXTRA_FIELD);
  2842. $sql = "SELECT id FROM " . $tableExtraFields . "
  2843. WHERE extra_field_type = 3 AND variable='image'";
  2844. $resultField = Database::query($sql);
  2845. $imageFieldId = Database::fetch_assoc($resultField);
  2846. while ($row = Database::fetch_array($result)) {
  2847. $row['image'] = null;
  2848. $sessionImage = $sysUploadPath . $imageFieldId['id'] . '_' . $row['id'] . '.png';
  2849. if (is_file($sessionImage)) {
  2850. $sessionImage = $webUploadPath . $imageFieldId['id'] . '_' . $row['id'] . '.png';
  2851. $row['image'] = $sessionImage;
  2852. } else {
  2853. $row['image'] = $imgPath;
  2854. }
  2855. $sessions[$row['id']] = $row;
  2856. }
  2857. }
  2858. return $sessions;
  2859. }
  2860. /**
  2861. * Gets the list (or the count) of courses by session filtered by access_url
  2862. * @param int $session_id The session id
  2863. * @param string $course_name The course code
  2864. * @param string $orderBy Field to order the data
  2865. * @param boolean $getCount Optional. Count the session courses
  2866. * @return array|int List of courses. Whether $getCount is true, return the count
  2867. */
  2868. public static function get_course_list_by_session_id(
  2869. $session_id,
  2870. $course_name = '',
  2871. $orderBy = null,
  2872. $getCount = false
  2873. ) {
  2874. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2875. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2876. $session_id = intval($session_id);
  2877. $sqlSelect = "SELECT *";
  2878. if ($getCount) {
  2879. $sqlSelect = "SELECT COUNT(1)";
  2880. }
  2881. // select the courses
  2882. $sql = "SELECT *, c.id, c.id as real_id
  2883. FROM $tbl_course c
  2884. INNER JOIN $tbl_session_rel_course src
  2885. ON c.id = src.c_id
  2886. WHERE src.session_id = '$session_id' ";
  2887. if (!empty($course_name)) {
  2888. $course_name = Database::escape_string($course_name);
  2889. $sql .= " AND c.title LIKE '%$course_name%' ";
  2890. }
  2891. if (!empty($orderBy)) {
  2892. $orderBy = Database::escape_string($orderBy);
  2893. $orderBy = " ORDER BY $orderBy";
  2894. } else {
  2895. if (SessionManager::orderCourseIsEnabled()) {
  2896. $orderBy .= " ORDER BY position ";
  2897. } else {
  2898. $orderBy .= " ORDER BY title ";
  2899. }
  2900. }
  2901. $sql .= Database::escape_string($orderBy);
  2902. $result = Database::query($sql);
  2903. $num_rows = Database::num_rows($result);
  2904. $courses = array();
  2905. if ($num_rows > 0) {
  2906. if ($getCount) {
  2907. $count = Database::fetch_array($result);
  2908. return intval($count[0]);
  2909. }
  2910. while ($row = Database::fetch_array($result,'ASSOC')) {
  2911. $courses[$row['real_id']] = $row;
  2912. }
  2913. }
  2914. return $courses;
  2915. }
  2916. /**
  2917. * Gets the list of courses by session filtered by access_url
  2918. *
  2919. * @param $userId
  2920. * @param $sessionId
  2921. * @param null $from
  2922. * @param null $limit
  2923. * @param null $column
  2924. * @param null $direction
  2925. * @param bool $getCount
  2926. * @return array
  2927. */
  2928. public static function getAllCoursesFollowedByUser(
  2929. $userId,
  2930. $sessionId,
  2931. $from = null,
  2932. $limit = null,
  2933. $column = null,
  2934. $direction = null,
  2935. $getCount = false,
  2936. $keyword = null
  2937. ) {
  2938. if (empty($sessionId)) {
  2939. $sessionsSQL = SessionManager::get_sessions_followed_by_drh(
  2940. $userId,
  2941. null,
  2942. null,
  2943. null,
  2944. true,
  2945. true
  2946. );
  2947. } else {
  2948. $sessionsSQL = intval($sessionId);
  2949. }
  2950. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2951. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2952. if ($getCount) {
  2953. $select = "SELECT COUNT(DISTINCT(c.code)) as count ";
  2954. } else {
  2955. $select = "SELECT DISTINCT c.* ";
  2956. }
  2957. $keywordCondition = null;
  2958. if (!empty($keyword)) {
  2959. $keyword = Database::escape_string($keyword);
  2960. $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
  2961. }
  2962. // Select the courses
  2963. $sql = "$select
  2964. FROM $tbl_course c
  2965. INNER JOIN $tbl_session_rel_course src
  2966. ON c.id = src.c_id
  2967. WHERE
  2968. src.session_id IN ($sessionsSQL)
  2969. $keywordCondition
  2970. ";
  2971. if ($getCount) {
  2972. $result = Database::query($sql);
  2973. $row = Database::fetch_array($result,'ASSOC');
  2974. return $row['count'];
  2975. }
  2976. if (isset($from) && isset($limit)) {
  2977. $from = intval($from);
  2978. $limit = intval($limit);
  2979. $sql .= " LIMIT $from, $limit";
  2980. }
  2981. $result = Database::query($sql);
  2982. $num_rows = Database::num_rows($result);
  2983. $courses = array();
  2984. if ($num_rows > 0) {
  2985. while ($row = Database::fetch_array($result,'ASSOC')) {
  2986. $courses[$row['id']] = $row;
  2987. }
  2988. }
  2989. return $courses;
  2990. }
  2991. /**
  2992. * Gets the list of courses by session filtered by access_url
  2993. * @param int $session_id
  2994. * @param string $course_name
  2995. * @return array list of courses
  2996. */
  2997. public static function get_course_list_by_session_id_like($session_id, $course_name = '')
  2998. {
  2999. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3000. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3001. $session_id = intval($session_id);
  3002. $course_name = Database::escape_string($course_name);
  3003. // select the courses
  3004. $sql = "SELECT c.id, c.title FROM $tbl_course c
  3005. INNER JOIN $tbl_session_rel_course src
  3006. ON c.id = src.c_id
  3007. WHERE ";
  3008. if (!empty($session_id)) {
  3009. $sql .= "src.session_id LIKE '$session_id' AND ";
  3010. }
  3011. if (!empty($course_name)) {
  3012. $sql .= "UPPER(c.title) LIKE UPPER('%$course_name%') ";
  3013. }
  3014. $sql .= "ORDER BY title;";
  3015. $result = Database::query($sql);
  3016. $num_rows = Database::num_rows($result);
  3017. $courses = array();
  3018. if ($num_rows > 0) {
  3019. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3020. $courses[$row['id']] = $row;
  3021. }
  3022. }
  3023. return $courses;
  3024. }
  3025. /**
  3026. * Gets the count of courses by session filtered by access_url
  3027. * @param int session id
  3028. * @return array list of courses
  3029. */
  3030. public static function getCourseCountBySessionId($session_id, $keyword = null)
  3031. {
  3032. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3033. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3034. $session_id = intval($session_id);
  3035. // select the courses
  3036. $sql = "SELECT COUNT(c.code) count
  3037. FROM $tbl_course c
  3038. INNER JOIN $tbl_session_rel_course src
  3039. ON c.id = src.c_id
  3040. WHERE src.session_id = '$session_id' ";
  3041. $keywordCondition = null;
  3042. if (!empty($keyword)) {
  3043. $keyword = Database::escape_string($keyword);
  3044. $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
  3045. }
  3046. $sql .= $keywordCondition;
  3047. $result = Database::query($sql);
  3048. $num_rows = Database::num_rows($result);
  3049. if ($num_rows > 0) {
  3050. $row = Database::fetch_array($result,'ASSOC');
  3051. return $row['count'];
  3052. }
  3053. return null;
  3054. }
  3055. /**
  3056. * Get the session id based on the original id and field name in the extra fields.
  3057. * Returns 0 if session was not found
  3058. *
  3059. * @param string $value Original session id
  3060. * @param string $variable Original field name
  3061. * @return int Session id
  3062. */
  3063. public static function getSessionIdFromOriginalId($value, $variable)
  3064. {
  3065. $extraFieldValue = new ExtraFieldValue('session');
  3066. $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  3067. $variable,
  3068. $value
  3069. );
  3070. if (!empty($result)) {
  3071. return $result['item_id'];
  3072. }
  3073. return 0;
  3074. }
  3075. /**
  3076. * Get users by session
  3077. * @param int $id session id
  3078. * @param int $status filter by status coach = 2
  3079. * @return array a list with an user list
  3080. */
  3081. public static function get_users_by_session($id, $status = null)
  3082. {
  3083. if (empty($id)) {
  3084. return array();
  3085. }
  3086. $id = intval($id);
  3087. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3088. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3089. $table_access_url_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3090. $sql = "SELECT
  3091. u.user_id,
  3092. lastname,
  3093. firstname,
  3094. username,
  3095. relation_type,
  3096. access_url_id
  3097. FROM $tbl_user u
  3098. INNER JOIN $tbl_session_rel_user
  3099. ON u.user_id = $tbl_session_rel_user.user_id AND
  3100. $tbl_session_rel_user.session_id = $id
  3101. LEFT OUTER JOIN $table_access_url_user uu
  3102. ON (uu.user_id = u.user_id)
  3103. ";
  3104. $urlId = api_get_current_access_url_id();
  3105. if (isset($status) && $status != '') {
  3106. $status = intval($status);
  3107. $sql .= " WHERE relation_type = $status AND (access_url_id = $urlId OR access_url_id is null )";
  3108. } else {
  3109. $sql .= " WHERE (access_url_id = $urlId OR access_url_id is null )";
  3110. }
  3111. $sql .= " ORDER BY relation_type, ";
  3112. $sql .= api_sort_by_first_name() ? ' firstname, lastname' : ' lastname, firstname';
  3113. $result = Database::query($sql);
  3114. $return = array();
  3115. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3116. $return[] = $row;
  3117. }
  3118. return $return;
  3119. }
  3120. /**
  3121. * The general coach (field: session.id_coach)
  3122. * @param int $user_id user id
  3123. * @param boolean $asPlatformAdmin The user is platform admin, return everything
  3124. * @return array
  3125. */
  3126. public static function get_sessions_by_general_coach($user_id, $asPlatformAdmin = false)
  3127. {
  3128. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3129. $user_id = intval($user_id);
  3130. // Session where we are general coach
  3131. $sql = "SELECT DISTINCT *
  3132. FROM $session_table";
  3133. if (!$asPlatformAdmin) {
  3134. $sql .= " WHERE id_coach = $user_id";
  3135. }
  3136. if (api_is_multiple_url_enabled()) {
  3137. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3138. $access_url_id = api_get_current_access_url_id();
  3139. $sqlCoach = '';
  3140. if (!$asPlatformAdmin) {
  3141. $sqlCoach = " id_coach = $user_id AND ";
  3142. }
  3143. if ($access_url_id != -1) {
  3144. $sql = 'SELECT DISTINCT session.*
  3145. FROM ' . $session_table . ' session INNER JOIN ' . $tbl_session_rel_access_url . ' session_rel_url
  3146. ON (session.id = session_rel_url.session_id)
  3147. WHERE '.$sqlCoach.' access_url_id = ' . $access_url_id;
  3148. }
  3149. }
  3150. $sql .= ' ORDER by name';
  3151. $result = Database::query($sql);
  3152. return Database::store_result($result, 'ASSOC');
  3153. }
  3154. /**
  3155. * @param int $user_id
  3156. * @return array
  3157. * @deprecated use get_sessions_by_general_coach()
  3158. */
  3159. public static function get_sessions_by_coach($user_id)
  3160. {
  3161. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3162. return Database::select('*', $session_table, array('where' => array('id_coach = ?' => $user_id)));
  3163. }
  3164. /**
  3165. * @param int $user_id
  3166. * @param int $courseId
  3167. * @param int $session_id
  3168. * @return array|bool
  3169. */
  3170. public static function get_user_status_in_course_session($user_id, $courseId, $session_id)
  3171. {
  3172. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3173. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3174. $sql = "SELECT session_rcru.status
  3175. FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  3176. WHERE
  3177. session_rcru.user_id = user.user_id AND
  3178. session_rcru.session_id = '" . intval($session_id) . "' AND
  3179. session_rcru.c_id ='" . intval($courseId) . "' AND
  3180. user.user_id = " . intval($user_id);
  3181. $result = Database::query($sql);
  3182. $status = false;
  3183. if (Database::num_rows($result)) {
  3184. $status = Database::fetch_row($result);
  3185. $status = $status['0'];
  3186. }
  3187. return $status;
  3188. }
  3189. /**
  3190. * Gets user status within a session
  3191. * @param int $user_id
  3192. * @param int $courseId
  3193. * @param $session_id
  3194. * @return int
  3195. * @assert (null,null,null) === false
  3196. */
  3197. public static function get_user_status_in_session($user_id, $courseId, $session_id)
  3198. {
  3199. if (empty($user_id) or empty($courseId) or empty($session_id)) {
  3200. return false;
  3201. }
  3202. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3203. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3204. $sql = "SELECT session_rcru.status
  3205. FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  3206. WHERE session_rcru.user_id = user.user_id AND
  3207. session_rcru.session_id = '" . intval($session_id) . "' AND
  3208. session_rcru.c_id ='" . intval($courseId) . "' AND
  3209. user.user_id = " . intval($user_id);
  3210. $result = Database::query($sql);
  3211. $status = false;
  3212. if (Database::num_rows($result)) {
  3213. $status = Database::fetch_row($result);
  3214. $status = $status['0'];
  3215. }
  3216. return $status;
  3217. }
  3218. /**
  3219. * @param int $id
  3220. * @return array
  3221. */
  3222. public static function get_all_sessions_by_promotion($id)
  3223. {
  3224. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  3225. return Database::select('*', $t, array('where' => array('promotion_id = ?' => $id)));
  3226. }
  3227. /**
  3228. * @param int $promotion_id
  3229. * @param array $list
  3230. */
  3231. public static function suscribe_sessions_to_promotion($promotion_id, $list)
  3232. {
  3233. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  3234. $params = array();
  3235. $params['promotion_id'] = 0;
  3236. Database::update($t, $params, array('promotion_id = ?' => $promotion_id));
  3237. $params['promotion_id'] = $promotion_id;
  3238. if (!empty($list)) {
  3239. foreach ($list as $session_id) {
  3240. $session_id = intval($session_id);
  3241. Database::update($t, $params, array('id = ?' => $session_id));
  3242. }
  3243. }
  3244. }
  3245. /**
  3246. * Updates a session status
  3247. * @param int session id
  3248. * @param int status
  3249. */
  3250. public static function set_session_status($session_id, $status)
  3251. {
  3252. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  3253. $params['visibility'] = $status;
  3254. Database::update($t, $params, array('id = ?' => $session_id));
  3255. }
  3256. /**
  3257. * Copies a session with the same data to a new session.
  3258. * The new copy is not assigned to the same promotion. @see suscribe_sessions_to_promotions() for that
  3259. * @param int Session ID
  3260. * @param bool Whether to copy the relationship with courses
  3261. * @param bool Whether to copy the relationship with users
  3262. * @param bool New courses will be created
  3263. * @param bool Whether to set exercises and learning paths in the new session to invisible by default
  3264. * @return int The new session ID on success, 0 otherwise
  3265. * @todo make sure the extra session fields are copied too
  3266. */
  3267. public static function copy(
  3268. $id,
  3269. $copy_courses = true,
  3270. $copy_users = true,
  3271. $create_new_courses = false,
  3272. $set_exercises_lp_invisible = false
  3273. ) {
  3274. $id = intval($id);
  3275. $s = self::fetch($id);
  3276. // Check all dates before copying
  3277. // Get timestamp for now in UTC - see http://php.net/manual/es/function.time.php#117251
  3278. $now = time() - date('Z');
  3279. // Timestamp in one month
  3280. $inOneMonth = $now + (30*24*3600);
  3281. $inOneMonth = api_get_local_time($inOneMonth);
  3282. if (api_strtotime($s['access_start_date']) < $now) {
  3283. $s['access_start_date'] = api_get_local_time($now);
  3284. }
  3285. if (api_strtotime($s['display_start_date']) < $now) {
  3286. $s['display_start_date'] = api_get_local_time($now);
  3287. }
  3288. if (api_strtotime($s['coach_access_start_date']) < $now) {
  3289. $s['coach_access_start_date'] = api_get_local_time($now);
  3290. }
  3291. if (api_strtotime($s['access_end_date']) < $now) {
  3292. $s['access_end_date'] = $inOneMonth;
  3293. }
  3294. if (api_strtotime($s['display_end_date']) < $now) {
  3295. $s['display_end_date'] = $inOneMonth;
  3296. }
  3297. if (api_strtotime($s['coach_access_end_date']) < $now) {
  3298. $s['coach_access_end_date'] = $inOneMonth;
  3299. }
  3300. // Now try to create the session
  3301. $sid = self::create_session(
  3302. $s['name'] . ' ' . get_lang('CopyLabelSuffix'),
  3303. $s['access_start_date'],
  3304. $s['access_end_date'],
  3305. $s['display_start_date'],
  3306. $s['display_end_date'],
  3307. $s['coach_access_start_date'],
  3308. $s['coach_access_end_date'],
  3309. (int)$s['id_coach'],
  3310. $s['session_category_id'],
  3311. (int)$s['visibility'],
  3312. true
  3313. );
  3314. if (!is_numeric($sid) || empty($sid)) {
  3315. return false;
  3316. }
  3317. if ($copy_courses) {
  3318. // Register courses from the original session to the new session
  3319. $courses = self::get_course_list_by_session_id($id);
  3320. $short_courses = $new_short_courses = array();
  3321. if (is_array($courses) && count($courses) > 0) {
  3322. foreach ($courses as $course) {
  3323. $short_courses[] = $course;
  3324. }
  3325. }
  3326. $courses = null;
  3327. //We will copy the current courses of the session to new courses
  3328. if (!empty($short_courses)) {
  3329. if ($create_new_courses) {
  3330. //Just in case
  3331. if (function_exists('ini_set')) {
  3332. api_set_memory_limit('256M');
  3333. ini_set('max_execution_time', 0);
  3334. }
  3335. $params = array();
  3336. $params['skip_lp_dates'] = true;
  3337. foreach ($short_courses as $course_data) {
  3338. $course_info = CourseManager::copy_course_simple(
  3339. $course_data['title'].' '.get_lang(
  3340. 'CopyLabelSuffix'
  3341. ),
  3342. $course_data['course_code'],
  3343. $id,
  3344. $sid,
  3345. $params
  3346. );
  3347. if ($course_info) {
  3348. //By default new elements are invisible
  3349. if ($set_exercises_lp_invisible) {
  3350. $list = new LearnpathList('', $course_info['code'], $sid);
  3351. $flat_list = $list->get_flat_list();
  3352. if (!empty($flat_list)) {
  3353. foreach ($flat_list as $lp_id => $data) {
  3354. api_item_property_update(
  3355. $course_info,
  3356. TOOL_LEARNPATH,
  3357. $lp_id,
  3358. 'invisible',
  3359. api_get_user_id(),
  3360. 0,
  3361. 0,
  3362. 0,
  3363. 0,
  3364. $sid
  3365. );
  3366. }
  3367. }
  3368. $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
  3369. $course_id = $course_info['real_id'];
  3370. //@todo check this query
  3371. $sql = "UPDATE $quiz_table SET active = 0
  3372. WHERE c_id = $course_id AND session_id = $sid";
  3373. Database::query($sql);
  3374. }
  3375. $new_short_courses[] = $course_info['real_id'];
  3376. }
  3377. }
  3378. } else {
  3379. foreach ($short_courses as $course_data) {
  3380. $new_short_courses[] = $course_data['id'];
  3381. }
  3382. }
  3383. $short_courses = $new_short_courses;
  3384. self::add_courses_to_session($sid, $short_courses, true);
  3385. $short_courses = null;
  3386. }
  3387. }
  3388. if ($copy_users) {
  3389. // Register users from the original session to the new session
  3390. $users = self::get_users_by_session($id);
  3391. $short_users = array();
  3392. if (is_array($users) && count($users) > 0) {
  3393. foreach ($users as $user) {
  3394. $short_users[] = $user['user_id'];
  3395. }
  3396. }
  3397. $users = null;
  3398. //Subscribing in read only mode
  3399. self::suscribe_users_to_session($sid, $short_users, SESSION_VISIBLE_READ_ONLY, true);
  3400. $short_users = null;
  3401. }
  3402. return $sid;
  3403. }
  3404. /**
  3405. * @param int $user_id
  3406. * @param int $session_id
  3407. * @return bool
  3408. */
  3409. static function user_is_general_coach($user_id, $session_id)
  3410. {
  3411. $session_id = intval($session_id);
  3412. $user_id = intval($user_id);
  3413. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3414. $sql = "SELECT DISTINCT id
  3415. FROM $session_table
  3416. WHERE session.id_coach = '" . $user_id . "' AND id = '$session_id'";
  3417. $result = Database::query($sql);
  3418. if ($result && Database::num_rows($result)) {
  3419. return true;
  3420. }
  3421. return false;
  3422. }
  3423. /**
  3424. * Get the number of sessions
  3425. * @param int ID of the URL we want to filter on (optional)
  3426. * @return int Number of sessions
  3427. */
  3428. public static function count_sessions($access_url_id = null)
  3429. {
  3430. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3431. $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3432. $sql = "SELECT count(id) FROM $session_table s";
  3433. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  3434. $sql .= ", $access_url_rel_session_table u " .
  3435. " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
  3436. }
  3437. $res = Database::query($sql);
  3438. $row = Database::fetch_row($res);
  3439. return $row[0];
  3440. }
  3441. /**
  3442. * Protect a session to be edited.
  3443. * @param int $id
  3444. * @param bool $checkSession
  3445. */
  3446. public static function protectSession($id, $checkSession = true)
  3447. {
  3448. // api_protect_admin_script(true);
  3449. if (self::allowToManageSessions()) {
  3450. if (api_is_platform_admin()) {
  3451. return true;
  3452. }
  3453. if ($checkSession) {
  3454. if (self::allowed($id)) {
  3455. return true;
  3456. } else {
  3457. api_not_allowed(true);
  3458. }
  3459. }
  3460. } else {
  3461. api_not_allowed(true);
  3462. }
  3463. }
  3464. /**
  3465. * @param int $id
  3466. * @return bool
  3467. */
  3468. private static function allowed($id)
  3469. {
  3470. $sessionInfo = self::fetch($id);
  3471. if (empty($sessionInfo)) {
  3472. return false;
  3473. }
  3474. if (api_is_platform_admin()) {
  3475. return true;
  3476. }
  3477. $userId = api_get_user_id();
  3478. if (api_is_session_admin() &&
  3479. api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true'
  3480. ) {
  3481. if ($sessionInfo['session_admin_id'] != $userId) {
  3482. return false;
  3483. }
  3484. }
  3485. if (api_is_teacher() &&
  3486. api_get_setting('allow_teachers_to_create_sessions') == 'true'
  3487. ) {
  3488. if ($sessionInfo['id_coach'] != $userId) {
  3489. return false;
  3490. }
  3491. }
  3492. return true;
  3493. }
  3494. /**
  3495. * @return bool
  3496. */
  3497. public static function allowToManageSessions()
  3498. {
  3499. if (self::allowManageAllSessions()) {
  3500. return true;
  3501. }
  3502. $setting = api_get_setting('allow_teachers_to_create_sessions');
  3503. if (api_is_teacher() && $setting == 'true') {
  3504. return true;
  3505. }
  3506. return false;
  3507. }
  3508. /**
  3509. * @return bool
  3510. */
  3511. public static function allowOnlyMySessions()
  3512. {
  3513. if (self::allowToManageSessions() &&
  3514. !api_is_platform_admin() &&
  3515. api_is_teacher()
  3516. ) {
  3517. return true;
  3518. }
  3519. return false;
  3520. }
  3521. /**
  3522. * @return bool
  3523. */
  3524. public static function allowManageAllSessions()
  3525. {
  3526. if (api_is_platform_admin()) {
  3527. return true;
  3528. }
  3529. return false;
  3530. }
  3531. /**
  3532. * @param $id
  3533. * @return bool
  3534. */
  3535. public static function protect_teacher_session_edit($id)
  3536. {
  3537. if (!api_is_coach($id) && !api_is_platform_admin()) {
  3538. api_not_allowed(true);
  3539. } else {
  3540. return true;
  3541. }
  3542. }
  3543. /**
  3544. * @param int $courseId
  3545. * @return array
  3546. */
  3547. public static function get_session_by_course($courseId)
  3548. {
  3549. $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3550. $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3551. $courseId = intval($courseId);
  3552. $sql = "SELECT name, s.id
  3553. FROM $table_session_course sc
  3554. INNER JOIN $table_session s ON (sc.session_id = s.id)
  3555. WHERE sc.c_id = '$courseId' ";
  3556. $result = Database::query($sql);
  3557. return Database::store_result($result);
  3558. }
  3559. /**
  3560. * @param int $user_id
  3561. * @param bool $ignore_visibility_for_admins
  3562. * @param bool $ignoreTimeLimit
  3563. *
  3564. * @return array
  3565. */
  3566. public static function get_sessions_by_user($user_id, $ignore_visibility_for_admins = false, $ignoreTimeLimit = false)
  3567. {
  3568. $sessionCategories = UserManager::get_sessions_by_category(
  3569. $user_id,
  3570. false,
  3571. $ignore_visibility_for_admins,
  3572. $ignoreTimeLimit
  3573. );
  3574. $sessionArray = array();
  3575. if (!empty($sessionCategories)) {
  3576. foreach ($sessionCategories as $category) {
  3577. if (isset($category['sessions'])) {
  3578. foreach ($category['sessions'] as $session) {
  3579. $sessionArray[] = $session;
  3580. }
  3581. }
  3582. }
  3583. }
  3584. return $sessionArray;
  3585. }
  3586. /**
  3587. * @param string $file
  3588. * @param bool $updateSession options:
  3589. * true: if the session exists it will be updated.
  3590. * false: if session exists a new session will be created adding a counter session1, session2, etc
  3591. * @param int $defaultUserId
  3592. * @param mixed $logger
  3593. * @param array $extraFields convert a file row to an extra field. Example in CSV file there's a SessionID then it will
  3594. * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
  3595. * @param string $extraFieldId
  3596. * @param int $daysCoachAccessBeforeBeginning
  3597. * @param int $daysCoachAccessAfterBeginning
  3598. * @param int $sessionVisibility
  3599. * @param array $fieldsToAvoidUpdate
  3600. * @param bool $deleteUsersNotInList
  3601. * @param bool $updateCourseCoaches
  3602. * @param bool $sessionWithCoursesModifier
  3603. * @param int $showDescription
  3604. * @param array $teacherBackupList
  3605. * @param array $groupBackup
  3606. * @return array
  3607. */
  3608. public static function importCSV(
  3609. $file,
  3610. $updateSession,
  3611. $defaultUserId = null,
  3612. $logger = null,
  3613. $extraFields = array(),
  3614. $extraFieldId = null,
  3615. $daysCoachAccessBeforeBeginning = null,
  3616. $daysCoachAccessAfterBeginning = null,
  3617. $sessionVisibility = 1,
  3618. $fieldsToAvoidUpdate = array(),
  3619. $deleteUsersNotInList = false,
  3620. $updateCourseCoaches = false,
  3621. $sessionWithCoursesModifier = false,
  3622. $addOriginalCourseTeachersAsCourseSessionCoaches = true,
  3623. $removeAllTeachersFromCourse = true,
  3624. $showDescription = null,
  3625. &$teacherBackupList = array(),
  3626. &$groupBackup = array()
  3627. ) {
  3628. $content = file($file);
  3629. $error_message = null;
  3630. $session_counter = 0;
  3631. if (empty($defaultUserId)) {
  3632. $defaultUserId = api_get_user_id();
  3633. }
  3634. $eol = PHP_EOL;
  3635. if (PHP_SAPI != 'cli') {
  3636. $eol = '<br />';
  3637. }
  3638. $debug = false;
  3639. if (isset($logger)) {
  3640. $debug = true;
  3641. }
  3642. $extraParameters = null;
  3643. if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
  3644. $extraParameters .= ' , nb_days_access_before_beginning = '.intval($daysCoachAccessBeforeBeginning);
  3645. $extraParameters .= ' , nb_days_access_after_end = '.intval($daysCoachAccessAfterBeginning);
  3646. }
  3647. if (!is_null($showDescription)) {
  3648. $extraParameters .= ' , show_description = '.intval($showDescription);
  3649. }
  3650. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3651. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3652. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3653. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3654. $sessions = array();
  3655. if (!api_strstr($content[0], ';')) {
  3656. $error_message = get_lang('NotCSV');
  3657. } else {
  3658. $tag_names = array();
  3659. foreach ($content as $key => $enreg) {
  3660. $enreg = explode(';', trim($enreg));
  3661. if ($key) {
  3662. foreach ($tag_names as $tag_key => $tag_name) {
  3663. $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
  3664. }
  3665. } else {
  3666. foreach ($enreg as $tag_name) {
  3667. $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
  3668. }
  3669. if (!in_array('SessionName', $tag_names) ||
  3670. !in_array('DateStart', $tag_names) ||
  3671. !in_array('DateEnd', $tag_names)
  3672. ) {
  3673. $error_message = get_lang('NoNeededData');
  3674. break;
  3675. }
  3676. }
  3677. }
  3678. $sessionList = array();
  3679. // Looping the sessions.
  3680. foreach ($sessions as $enreg) {
  3681. $user_counter = 0;
  3682. $course_counter = 0;
  3683. if (isset($extraFields) && !empty($extraFields)) {
  3684. foreach ($extraFields as $original => $to) {
  3685. $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
  3686. }
  3687. }
  3688. $session_name = Database::escape_string($enreg['SessionName']);
  3689. // Default visibility
  3690. $visibilityAfterExpirationPerSession = $sessionVisibility;
  3691. if (isset($enreg['VisibilityAfterExpiration'])) {
  3692. $visibility = $enreg['VisibilityAfterExpiration'];
  3693. switch ($visibility) {
  3694. case 'read_only':
  3695. $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
  3696. break;
  3697. case 'accessible':
  3698. $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
  3699. break;
  3700. case 'not_accessible':
  3701. $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
  3702. break;
  3703. }
  3704. }
  3705. if (empty($session_name)) {
  3706. continue;
  3707. }
  3708. $date_start = $enreg['DateStart'];
  3709. $date_end = $enreg['DateEnd'];
  3710. $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
  3711. $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
  3712. $extraSessionParameters = null;
  3713. if (!empty($sessionDescription)) {
  3714. $extraSessionParameters = " , description = '".Database::escape_string($sessionDescription)."'";
  3715. }
  3716. // Searching a general coach.
  3717. if (!empty($enreg['Coach'])) {
  3718. $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
  3719. if ($coach_id === false) {
  3720. // If the coach-user does not exist - I'm the coach.
  3721. $coach_id = $defaultUserId;
  3722. }
  3723. } else {
  3724. $coach_id = $defaultUserId;
  3725. }
  3726. if (!$updateSession) {
  3727. // Always create a session.
  3728. $unique_name = false;
  3729. $i = 0;
  3730. // Change session name, verify that session doesn't exist.
  3731. $suffix = null;
  3732. while (!$unique_name) {
  3733. if ($i > 1) {
  3734. $suffix = ' - ' . $i;
  3735. }
  3736. $sql = 'SELECT 1 FROM ' . $tbl_session . '
  3737. WHERE name="' . $session_name . $suffix . '"';
  3738. $rs = Database::query($sql);
  3739. if (Database::result($rs, 0, 0)) {
  3740. $i++;
  3741. } else {
  3742. $unique_name = true;
  3743. $session_name .= $suffix;
  3744. }
  3745. }
  3746. $sessionCondition = '';
  3747. if (!empty($session_category_id)) {
  3748. $sessionCondition = "session_category_id = '$session_category_id',";
  3749. }
  3750. // Creating the session.
  3751. $sql = "INSERT IGNORE INTO $tbl_session SET
  3752. name = '" . $session_name . "',
  3753. id_coach = '$coach_id',
  3754. access_start_date = '$date_start',
  3755. access_end_date = '$date_end',
  3756. visibility = '$visibilityAfterExpirationPerSession',
  3757. $sessionCondition
  3758. session_admin_id = " . intval($defaultUserId) . $extraParameters . $extraSessionParameters;
  3759. Database::query($sql);
  3760. $session_id = Database::insert_id();
  3761. if ($debug) {
  3762. if ($session_id) {
  3763. foreach ($enreg as $key => $value) {
  3764. if (substr($key, 0, 6) == 'extra_') { //an extra field
  3765. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  3766. }
  3767. }
  3768. $logger->addInfo("Sessions - Session created: #$session_id - $session_name");
  3769. } else {
  3770. $logger->addError("Sessions - Session NOT created: $session_name");
  3771. }
  3772. }
  3773. $session_counter++;
  3774. } else {
  3775. $sessionId = null;
  3776. if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_'.$extraFieldId])) {
  3777. $sessionId = self::getSessionIdFromOriginalId($enreg['extra_'.$extraFieldId], $extraFieldId);
  3778. if (empty($sessionId)) {
  3779. $my_session_result = false;
  3780. } else {
  3781. $my_session_result = true;
  3782. }
  3783. } else {
  3784. $my_session_result = self::get_session_by_name($enreg['SessionName']);
  3785. }
  3786. if ($my_session_result === false) {
  3787. // Creating a session.
  3788. $sql = "INSERT IGNORE INTO $tbl_session SET
  3789. name = '$session_name',
  3790. id_coach = '$coach_id',
  3791. access_start_date = '$date_start',
  3792. access_end_date = '$date_end',
  3793. visibility = '$visibilityAfterExpirationPerSession',
  3794. session_category_id = '$session_category_id' " . $extraParameters . $extraSessionParameters;
  3795. Database::query($sql);
  3796. // We get the last insert id.
  3797. $my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
  3798. $session_id = $my_session_result['id'];
  3799. if ($session_id) {
  3800. foreach ($enreg as $key => $value) {
  3801. if (substr($key, 0, 6) == 'extra_') { //an extra field
  3802. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  3803. }
  3804. }
  3805. if ($debug) {
  3806. $logger->addInfo("Sessions - #$session_id created: $session_name");
  3807. }
  3808. // Delete session-user relation only for students
  3809. $sql = "DELETE FROM $tbl_session_user
  3810. WHERE session_id = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
  3811. Database::query($sql);
  3812. $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
  3813. Database::query($sql);
  3814. // Delete session-course-user relationships students and coaches.
  3815. if ($updateCourseCoaches) {
  3816. $sql = "DELETE FROM $tbl_session_course_user
  3817. WHERE session_id = '$session_id' AND status in ('0', '2')";
  3818. Database::query($sql);
  3819. } else {
  3820. // Delete session-course-user relation ships *only* for students.
  3821. $sql = "DELETE FROM $tbl_session_course_user
  3822. WHERE session_id = '$session_id' AND status <> 2";
  3823. Database::query($sql);
  3824. }
  3825. }
  3826. } else {
  3827. if ($debug) {
  3828. $logger->addError("Sessions - Session to be updated: $session_name");
  3829. }
  3830. // Updating the session.
  3831. $params = array(
  3832. 'id_coach' => $coach_id,
  3833. 'access_start_date' => $date_start,
  3834. 'access_end_date' => $date_end,
  3835. 'visibility' => $visibilityAfterExpirationPerSession,
  3836. 'session_category_id' => $session_category_id,
  3837. );
  3838. if (!empty($sessionDescription)) {
  3839. $params['description'] = $sessionDescription;
  3840. }
  3841. if (!empty($fieldsToAvoidUpdate)) {
  3842. foreach ($fieldsToAvoidUpdate as $field) {
  3843. unset($params[$field]);
  3844. }
  3845. }
  3846. if (isset($sessionId) && !empty($sessionId)) {
  3847. if (!empty($enreg['SessionName'])) {
  3848. $params['name'] = $enreg['SessionName'];
  3849. }
  3850. $session_id = $sessionId;
  3851. } else {
  3852. $row = Database::query("SELECT id FROM $tbl_session WHERE name = '$session_name'");
  3853. list($session_id) = Database::fetch_array($row);
  3854. }
  3855. if ($session_id) {
  3856. if ($debug) {
  3857. $logger->addError("Sessions - Session to be updated #$session_id");
  3858. }
  3859. $sessionInfo = api_get_session_info($session_id);
  3860. $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
  3861. if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
  3862. if (empty($sessionInfo['nb_days_access_before_beginning']) ||
  3863. (!empty($sessionInfo['nb_days_access_before_beginning']) &&
  3864. $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning)
  3865. ) {
  3866. $params['nb_days_access_before_beginning'] = intval($daysCoachAccessBeforeBeginning);
  3867. }
  3868. if (empty($sessionInfo['nb_days_access_after_end']) ||
  3869. (!empty($sessionInfo['nb_days_access_after_end']) &&
  3870. $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning)
  3871. ) {
  3872. $params['nb_days_access_after_end'] = intval($daysCoachAccessAfterBeginning);
  3873. }
  3874. }
  3875. Database::update($tbl_session, $params, array('id = ?' => $session_id));
  3876. foreach ($enreg as $key => $value) {
  3877. if (substr($key, 0, 6) == 'extra_') { //an extra field
  3878. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  3879. }
  3880. }
  3881. // Delete session-user relation only for students
  3882. $sql = "DELETE FROM $tbl_session_user
  3883. WHERE session_id = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
  3884. Database::query($sql);
  3885. $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
  3886. Database::query($sql);
  3887. // Delete session-course-user relationships students and coaches.
  3888. if ($updateCourseCoaches) {
  3889. $sql = "DELETE FROM $tbl_session_course_user
  3890. WHERE session_id = '$session_id' AND status in ('0', '2')";
  3891. Database::query($sql);
  3892. } else {
  3893. // Delete session-course-user relation ships *only* for students.
  3894. $sql = "DELETE FROM $tbl_session_course_user
  3895. WHERE session_id = '$session_id' AND status <> 2";
  3896. Database::query($sql);
  3897. }
  3898. } else {
  3899. if ($debug) {
  3900. $logger->addError(
  3901. "Sessions - Session not found"
  3902. );
  3903. }
  3904. }
  3905. }
  3906. $session_counter++;
  3907. }
  3908. $sessionList[] = $session_id;
  3909. $users = explode('|', $enreg['Users']);
  3910. // Adding the relationship "Session - User" for students
  3911. $userList = array();
  3912. if (is_array($users)) {
  3913. foreach ($users as $user) {
  3914. $user_id = UserManager::get_user_id_from_username($user);
  3915. if ($user_id !== false) {
  3916. $userList[] = $user_id;
  3917. // Insert new users.
  3918. $sql = "INSERT IGNORE INTO $tbl_session_user SET
  3919. user_id = '$user_id',
  3920. session_id = '$session_id',
  3921. registered_at = '" . api_get_utc_datetime() . "'";
  3922. Database::query($sql);
  3923. if ($debug) {
  3924. $logger->addInfo("Sessions - Adding User #$user_id ($user) to session #$session_id");
  3925. }
  3926. $user_counter++;
  3927. }
  3928. }
  3929. }
  3930. if ($deleteUsersNotInList) {
  3931. // Getting user in DB in order to compare to the new list.
  3932. $usersListInDatabase = self::get_users_by_session($session_id, 0);
  3933. if (!empty($usersListInDatabase)) {
  3934. if (empty($userList)) {
  3935. foreach ($usersListInDatabase as $userInfo) {
  3936. self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
  3937. }
  3938. } else {
  3939. foreach ($usersListInDatabase as $userInfo) {
  3940. if (!in_array($userInfo['user_id'], $userList)) {
  3941. self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
  3942. }
  3943. }
  3944. }
  3945. }
  3946. }
  3947. $courses = explode('|', $enreg['Courses']);
  3948. // See BT#6449
  3949. $onlyAddFirstCoachOrTeacher = false;
  3950. if ($sessionWithCoursesModifier) {
  3951. if (count($courses) >= 2) {
  3952. // Only first teacher in course session;
  3953. $onlyAddFirstCoachOrTeacher = true;
  3954. // Remove all teachers from course.
  3955. $removeAllTeachersFromCourse = false;
  3956. }
  3957. }
  3958. foreach ($courses as $course) {
  3959. $courseArray = bracketsToArray($course);
  3960. $course_code = $courseArray[0];
  3961. if (CourseManager::course_exists($course_code)) {
  3962. $courseInfo = api_get_course_info($course_code);
  3963. $courseId = $courseInfo['real_id'];
  3964. // Adding the course to a session.
  3965. $sql = "INSERT IGNORE INTO $tbl_session_course
  3966. SET c_id = '$courseId', session_id='$session_id'";
  3967. Database::query($sql);
  3968. SessionManager::installCourse($session_id, $courseInfo['real_id']);
  3969. if ($debug) {
  3970. $logger->addInfo("Sessions - Adding course '$course_code' to session #$session_id");
  3971. }
  3972. $course_counter++;
  3973. $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
  3974. $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
  3975. $course_users = explode(',', $course_users);
  3976. $course_coaches = explode(',', $course_coaches);
  3977. // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
  3978. $addTeachersToSession = true;
  3979. if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
  3980. $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
  3981. }
  3982. // If any user provided for a course, use the users array.
  3983. if (empty($course_users)) {
  3984. if (!empty($userList)) {
  3985. SessionManager::subscribe_users_to_session_course(
  3986. $userList,
  3987. $session_id,
  3988. $course_code
  3989. );
  3990. if ($debug) {
  3991. $msg = "Sessions - Adding student list ".implode(', #', $userList)." to course: '$course_code' and session #$session_id";
  3992. $logger->addInfo($msg);
  3993. }
  3994. }
  3995. }
  3996. // Adding coaches to session course user.
  3997. if (!empty($course_coaches)) {
  3998. $savedCoaches = array();
  3999. // only edit if add_teachers_to_sessions_courses is set.
  4000. if ($addTeachersToSession) {
  4001. if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
  4002. // Adding course teachers as course session teachers.
  4003. $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code(
  4004. $course_code
  4005. );
  4006. if (!empty($alreadyAddedTeachers)) {
  4007. $teachersToAdd = array();
  4008. foreach ($alreadyAddedTeachers as $user) {
  4009. $teachersToAdd[] = $user['username'];
  4010. }
  4011. $course_coaches = array_merge(
  4012. $course_coaches,
  4013. $teachersToAdd
  4014. );
  4015. }
  4016. }
  4017. foreach ($course_coaches as $course_coach) {
  4018. $coach_id = UserManager::get_user_id_from_username($course_coach);
  4019. if ($coach_id !== false) {
  4020. // Just insert new coaches
  4021. SessionManager::updateCoaches($session_id, $courseId, array($coach_id), false);
  4022. if ($debug) {
  4023. $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  4024. }
  4025. $savedCoaches[] = $coach_id;
  4026. } else {
  4027. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  4028. }
  4029. }
  4030. }
  4031. // Custom courses/session coaches
  4032. $teacherToAdd = null;
  4033. // Only one coach is added.
  4034. if ($onlyAddFirstCoachOrTeacher == true) {
  4035. foreach ($course_coaches as $course_coach) {
  4036. $coach_id = UserManager::get_user_id_from_username($course_coach);
  4037. if ($coach_id !== false) {
  4038. $teacherToAdd = $coach_id;
  4039. break;
  4040. }
  4041. }
  4042. // Un subscribe everyone that's not in the list.
  4043. $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
  4044. if (!empty($teacherList)) {
  4045. foreach ($teacherList as $teacher) {
  4046. if ($teacherToAdd != $teacher['user_id']) {
  4047. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  4048. WHERE
  4049. user_id = ".$teacher['user_id']." AND
  4050. course_code = '".$course_code."'
  4051. ";
  4052. $result = Database::query($sql);
  4053. $userCourseData = Database::fetch_array($result, 'ASSOC');
  4054. $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
  4055. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  4056. WHERE
  4057. user_id = ".$teacher['user_id']." AND
  4058. c_id = '".$courseInfo['real_id']."'
  4059. ";
  4060. $result = Database::query($sql);
  4061. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4062. $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4063. }
  4064. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  4065. WHERE
  4066. user_id = ".$teacher['user_id']." AND
  4067. c_id = '".$courseInfo['real_id']."'
  4068. ";
  4069. $result = Database::query($sql);
  4070. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4071. $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4072. }
  4073. CourseManager::unsubscribe_user(
  4074. $teacher['user_id'],
  4075. $course_code
  4076. );
  4077. }
  4078. }
  4079. }
  4080. if (!empty($teacherToAdd)) {
  4081. SessionManager::updateCoaches($session_id, $courseId, array($teacherToAdd), true);
  4082. $userCourseCategory = '';
  4083. if (isset($teacherBackupList[$teacherToAdd]) &&
  4084. isset($teacherBackupList[$teacherToAdd][$course_code])
  4085. ) {
  4086. $courseUserData = $teacherBackupList[$teacherToAdd][$course_code];
  4087. $userCourseCategory = $courseUserData['user_course_cat'];
  4088. }
  4089. CourseManager::subscribe_user(
  4090. $teacherToAdd,
  4091. $course_code,
  4092. COURSEMANAGER,
  4093. 0,
  4094. $userCourseCategory
  4095. );
  4096. if (isset($groupBackup['user'][$teacherToAdd]) &&
  4097. isset($groupBackup['user'][$teacherToAdd][$course_code]) &&
  4098. !empty($groupBackup['user'][$teacherToAdd][$course_code])
  4099. ) {
  4100. foreach ($groupBackup['user'][$teacherToAdd][$course_code] as $data) {
  4101. GroupManager::subscribe_users(
  4102. $teacherToAdd,
  4103. $data['group_id'],
  4104. $data['c_id']
  4105. );
  4106. }
  4107. }
  4108. if (isset($groupBackup['tutor'][$teacherToAdd]) &&
  4109. isset($groupBackup['tutor'][$teacherToAdd][$course_code]) &&
  4110. !empty($groupBackup['tutor'][$teacherToAdd][$course_code])
  4111. ) {
  4112. foreach ($groupBackup['tutor'][$teacherToAdd][$course_code] as $data) {
  4113. GroupManager::subscribe_tutors(
  4114. $teacherToAdd,
  4115. $data['group_id'],
  4116. $data['c_id']
  4117. );
  4118. }
  4119. }
  4120. }
  4121. }
  4122. // See BT#6449#note-195
  4123. // All coaches are added.
  4124. if ($removeAllTeachersFromCourse) {
  4125. $teacherToAdd = null;
  4126. foreach ($course_coaches as $course_coach) {
  4127. $coach_id = UserManager::get_user_id_from_username(
  4128. $course_coach
  4129. );
  4130. if ($coach_id !== false) {
  4131. $teacherToAdd[] = $coach_id;
  4132. }
  4133. }
  4134. if (!empty($teacherToAdd)) {
  4135. // Deleting all course teachers and adding the only coach as teacher.
  4136. $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
  4137. if (!empty($teacherList)) {
  4138. foreach ($teacherList as $teacher) {
  4139. if (!in_array($teacher['user_id'], $teacherToAdd)) {
  4140. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  4141. WHERE
  4142. user_id = ".$teacher['user_id']." AND
  4143. course_code = '".$course_code."'
  4144. ";
  4145. $result = Database::query($sql);
  4146. $userCourseData = Database::fetch_array($result, 'ASSOC');
  4147. $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
  4148. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  4149. WHERE
  4150. user_id = ".$teacher['user_id']." AND
  4151. c_id = '".$courseInfo['real_id']."'
  4152. ";
  4153. $result = Database::query($sql);
  4154. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4155. $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4156. }
  4157. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  4158. WHERE
  4159. user_id = ".$teacher['user_id']." AND
  4160. c_id = '".$courseInfo['real_id']."'
  4161. ";
  4162. $result = Database::query($sql);
  4163. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4164. $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4165. }
  4166. CourseManager::unsubscribe_user(
  4167. $teacher['user_id'],
  4168. $course_code
  4169. );
  4170. }
  4171. }
  4172. }
  4173. foreach ($teacherToAdd as $teacherId) {
  4174. $userCourseCategory = '';
  4175. if (isset($teacherBackupList[$teacherId]) &&
  4176. isset($teacherBackupList[$teacherId][$course_code])
  4177. ) {
  4178. $courseUserData = $teacherBackupList[$teacherId][$course_code];
  4179. $userCourseCategory = $courseUserData['user_course_cat'];
  4180. }
  4181. CourseManager::subscribe_user(
  4182. $teacherId,
  4183. $course_code,
  4184. COURSEMANAGER,
  4185. 0,
  4186. $userCourseCategory
  4187. );
  4188. if (isset($groupBackup['user'][$teacherId]) &&
  4189. isset($groupBackup['user'][$teacherId][$course_code]) &&
  4190. !empty($groupBackup['user'][$teacherId][$course_code])
  4191. ) {
  4192. foreach ($groupBackup['user'][$teacherId][$course_code] as $data) {
  4193. GroupManager::subscribe_users(
  4194. $teacherId,
  4195. $data['group_id'],
  4196. $data['c_id']
  4197. );
  4198. }
  4199. }
  4200. if (isset($groupBackup['tutor'][$teacherId]) &&
  4201. isset($groupBackup['tutor'][$teacherId][$course_code]) &&
  4202. !empty($groupBackup['tutor'][$teacherId][$course_code])
  4203. ) {
  4204. foreach ($groupBackup['tutor'][$teacherId][$course_code] as $data) {
  4205. GroupManager::subscribe_tutors(
  4206. $teacherId,
  4207. $data['group_id'],
  4208. $data['c_id']
  4209. );
  4210. }
  4211. }
  4212. }
  4213. }
  4214. }
  4215. // Continue default behaviour.
  4216. if ($onlyAddFirstCoachOrTeacher == false) {
  4217. // Checking one more time see BT#6449#note-149
  4218. $coaches = SessionManager::getCoachesByCourseSession($session_id, $courseId);
  4219. // Update coaches if only there's 1 course see BT#6449#note-189
  4220. if (empty($coaches) || count($courses) == 1) {
  4221. foreach ($course_coaches as $course_coach) {
  4222. $course_coach = trim($course_coach);
  4223. $coach_id = UserManager::get_user_id_from_username($course_coach);
  4224. if ($coach_id !== false) {
  4225. // Just insert new coaches
  4226. SessionManager::updateCoaches(
  4227. $session_id,
  4228. $courseId,
  4229. array($coach_id),
  4230. false
  4231. );
  4232. if ($debug) {
  4233. $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  4234. }
  4235. $savedCoaches[] = $coach_id;
  4236. } else {
  4237. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  4238. }
  4239. }
  4240. }
  4241. }
  4242. }
  4243. // Adding Students, updating relationship "Session - Course - User".
  4244. $course_users = array_filter($course_users);
  4245. if (!empty($course_users)) {
  4246. foreach ($course_users as $user) {
  4247. $user_id = UserManager::get_user_id_from_username($user);
  4248. if ($user_id !== false) {
  4249. SessionManager::subscribe_users_to_session_course(
  4250. array($user_id),
  4251. $session_id,
  4252. $course_code
  4253. );
  4254. if ($debug) {
  4255. $logger->addInfo("Sessions - Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
  4256. }
  4257. } else {
  4258. $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
  4259. }
  4260. }
  4261. }
  4262. $inserted_in_course[$course_code] = $courseInfo['title'];
  4263. }
  4264. }
  4265. $access_url_id = api_get_current_access_url_id();
  4266. UrlManager::add_session_to_url($session_id, $access_url_id);
  4267. $sql = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter' WHERE id = '$session_id'";
  4268. Database::query($sql);
  4269. }
  4270. }
  4271. return array(
  4272. 'error_message' => $error_message,
  4273. 'session_counter' => $session_counter,
  4274. 'session_list' => $sessionList,
  4275. );
  4276. }
  4277. /**
  4278. * @param int $sessionId
  4279. * @param int $courseId
  4280. * @return array
  4281. */
  4282. public static function getCoachesByCourseSession($sessionId, $courseId)
  4283. {
  4284. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4285. $sessionId = intval($sessionId);
  4286. $courseId = intval($courseId);
  4287. $sql = "SELECT user_id FROM $table
  4288. WHERE
  4289. session_id = '$sessionId' AND
  4290. c_id = '$courseId' AND
  4291. status = 2";
  4292. $result = Database::query($sql);
  4293. $coaches = array();
  4294. if (Database::num_rows($result) > 0) {
  4295. while ($row = Database::fetch_row($result)) {
  4296. $coaches[] = $row[0];
  4297. }
  4298. }
  4299. return $coaches;
  4300. }
  4301. /**
  4302. * @param int $sessionId
  4303. * @param int $courseId
  4304. * @return string
  4305. */
  4306. public static function getCoachesByCourseSessionToString(
  4307. $sessionId,
  4308. $courseId
  4309. ) {
  4310. $coaches = self::getCoachesByCourseSession($sessionId, $courseId);
  4311. $list = array();
  4312. if (!empty($coaches)) {
  4313. foreach ($coaches as $coachId) {
  4314. $userInfo = api_get_user_info($coachId);
  4315. $list[] = api_get_person_name(
  4316. $userInfo['firstname'],
  4317. $userInfo['lastname']
  4318. );
  4319. }
  4320. }
  4321. return array_to_string($list, CourseManager::USER_SEPARATOR);
  4322. }
  4323. /**
  4324. * Get all coaches added in the session - course relationship
  4325. * @param int $sessionId
  4326. * @return array
  4327. */
  4328. public static function getCoachesBySession($sessionId)
  4329. {
  4330. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4331. $sessionId = intval($sessionId);
  4332. $sql = "SELECT DISTINCT user_id
  4333. FROM $table
  4334. WHERE session_id = '$sessionId' AND status = 2";
  4335. $result = Database::query($sql);
  4336. $coaches = array();
  4337. if (Database::num_rows($result) > 0) {
  4338. while ($row = Database::fetch_array($result)) {
  4339. $coaches[] = $row['user_id'];
  4340. }
  4341. }
  4342. return $coaches;
  4343. }
  4344. /**
  4345. * @param int $userId
  4346. * @return array
  4347. */
  4348. public static function getAllCoursesFromAllSessionFromDrh($userId)
  4349. {
  4350. $sessions = SessionManager::get_sessions_followed_by_drh($userId);
  4351. $coursesFromSession = array();
  4352. if (!empty($sessions)) {
  4353. foreach ($sessions as $session) {
  4354. $courseList = SessionManager::get_course_list_by_session_id($session['id']);
  4355. foreach ($courseList as $course) {
  4356. $coursesFromSession[] = $course['code'];
  4357. }
  4358. }
  4359. }
  4360. return $coursesFromSession;
  4361. }
  4362. /**
  4363. * @param string $status
  4364. * @param int $userId
  4365. * @param bool $getCount
  4366. * @param int $from
  4367. * @param int $numberItems
  4368. * @param int $column
  4369. * @param string $direction
  4370. * @param string $keyword
  4371. * @param string $active
  4372. * @param string $lastConnectionDate
  4373. * @param array $sessionIdList
  4374. * @param array $studentIdList
  4375. * @param int $filterByStatus
  4376. * @return array|int
  4377. */
  4378. public static function getAllUsersFromCoursesFromAllSessionFromStatus(
  4379. $status,
  4380. $userId,
  4381. $getCount = false,
  4382. $from = null,
  4383. $numberItems = null,
  4384. $column = 1,
  4385. $direction = 'asc',
  4386. $keyword = null,
  4387. $active = null,
  4388. $lastConnectionDate = null,
  4389. $sessionIdList = array(),
  4390. $studentIdList = array(),
  4391. $filterByStatus = null
  4392. ) {
  4393. $filterByStatus = intval($filterByStatus);
  4394. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  4395. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  4396. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  4397. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4398. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4399. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4400. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  4401. $direction = in_array(strtolower($direction), array('asc', 'desc')) ? $direction : 'asc';
  4402. $column = Database::escape_string($column);
  4403. $userId = intval($userId);
  4404. $limitCondition = null;
  4405. if (isset($from) && isset($numberItems)) {
  4406. $from = intval($from);
  4407. $numberItems = intval($numberItems);
  4408. $limitCondition = "LIMIT $from, $numberItems";
  4409. }
  4410. $urlId = api_get_current_access_url_id();
  4411. $sessionConditions = null;
  4412. $courseConditions = null;
  4413. $userConditions = null;
  4414. if (isset($active)) {
  4415. $active = intval($active);
  4416. $userConditions .= " AND active = $active";
  4417. }
  4418. switch ($status) {
  4419. case 'drh':
  4420. // Classic DRH
  4421. if (empty($studentIdList)) {
  4422. $studentListSql = UserManager::get_users_followed_by_drh(
  4423. $userId,
  4424. $filterByStatus,
  4425. true,
  4426. false
  4427. );
  4428. $studentIdList = array_keys($studentListSql);
  4429. $studentListSql = "'".implode("','", $studentIdList)."'";
  4430. } else {
  4431. $studentIdList = array_map('intval', $studentIdList);
  4432. $studentListSql = "'".implode("','", $studentIdList)."'";
  4433. }
  4434. if (!empty($studentListSql)) {
  4435. $userConditions = " AND u.user_id IN (".$studentListSql.") ";
  4436. }
  4437. break;
  4438. case 'drh_all':
  4439. // Show all by DRH
  4440. if (empty($sessionIdList)) {
  4441. $sessionsListSql = SessionManager::get_sessions_followed_by_drh(
  4442. $userId,
  4443. null,
  4444. null,
  4445. false,
  4446. true,
  4447. true
  4448. );
  4449. } else {
  4450. $sessionIdList = array_map('intval', $sessionIdList);
  4451. $sessionsListSql = "'".implode("','", $sessionIdList)."'";
  4452. }
  4453. if (!empty($sessionsListSql)) {
  4454. $sessionConditions = " AND s.id IN (".$sessionsListSql.") ";
  4455. }
  4456. break;
  4457. case 'session_admin';
  4458. $sessionConditions = " AND s.id_coach = $userId ";
  4459. break;
  4460. case 'admin':
  4461. break;
  4462. case 'teacher':
  4463. $sessionConditions = " AND s.id_coach = $userId ";
  4464. break;
  4465. }
  4466. $select = "SELECT DISTINCT u.* ";
  4467. $masterSelect = "SELECT DISTINCT * FROM ";
  4468. if ($getCount) {
  4469. $select = "SELECT DISTINCT u.user_id ";
  4470. $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
  4471. }
  4472. if (!empty($filterByStatus)) {
  4473. $userConditions .= " AND u.status = ".$filterByStatus;
  4474. }
  4475. if (!empty($lastConnectionDate)) {
  4476. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  4477. $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
  4478. }
  4479. if (!empty($keyword)) {
  4480. $keyword = Database::escape_string($keyword);
  4481. $userConditions .= " AND (
  4482. u.username LIKE '%$keyword%' OR
  4483. u.firstname LIKE '%$keyword%' OR
  4484. u.lastname LIKE '%$keyword%' OR
  4485. u.official_code LIKE '%$keyword%' OR
  4486. u.email LIKE '%$keyword%'
  4487. )";
  4488. }
  4489. $where = " WHERE
  4490. access_url_id = $urlId
  4491. $userConditions
  4492. ";
  4493. $sql = "$masterSelect (
  4494. ($select
  4495. FROM $tbl_session s
  4496. INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.session_id)
  4497. INNER JOIN $tbl_user u ON (u.user_id = su.user_id)
  4498. INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
  4499. $where
  4500. $sessionConditions
  4501. )
  4502. UNION (
  4503. $select
  4504. FROM $tbl_course c
  4505. INNER JOIN $tbl_course_user cu ON (cu.c_id = c.id)
  4506. INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
  4507. INNER JOIN $tbl_course_rel_access_url url ON (url.c_id = c.id)
  4508. $where
  4509. $courseConditions
  4510. )
  4511. ) as t1
  4512. ";
  4513. if ($getCount) {
  4514. $result = Database::query($sql);
  4515. $count = 0;
  4516. if (Database::num_rows($result)) {
  4517. $rows = Database::fetch_array($result);
  4518. $count = $rows['count'];
  4519. }
  4520. return $count;
  4521. }
  4522. if (!empty($column) && !empty($direction)) {
  4523. $column = str_replace('u.', '', $column);
  4524. $sql .= " ORDER BY $column $direction ";
  4525. }
  4526. $sql .= $limitCondition;
  4527. $result = Database::query($sql);
  4528. $result = Database::store_result($result);
  4529. return $result ;
  4530. }
  4531. /**
  4532. * @param int $sessionId
  4533. * @param int $courseId
  4534. * @param array $coachList
  4535. * @param bool $deleteCoachesNotInList
  4536. */
  4537. public static function updateCoaches(
  4538. $sessionId,
  4539. $courseId,
  4540. $coachList,
  4541. $deleteCoachesNotInList = false
  4542. ) {
  4543. $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseId);
  4544. if (!empty($coachList)) {
  4545. foreach ($coachList as $userId) {
  4546. self::set_coach_to_course_session($userId, $sessionId, $courseId);
  4547. }
  4548. }
  4549. if ($deleteCoachesNotInList) {
  4550. if (!empty($coachList)) {
  4551. $coachesToDelete = array_diff($currentCoaches, $coachList);
  4552. } else {
  4553. $coachesToDelete = $currentCoaches;
  4554. }
  4555. if (!empty($coachesToDelete)) {
  4556. foreach ($coachesToDelete as $userId) {
  4557. self::set_coach_to_course_session(
  4558. $userId,
  4559. $sessionId,
  4560. $courseId,
  4561. true
  4562. );
  4563. }
  4564. }
  4565. }
  4566. }
  4567. /**
  4568. * @param array $sessions
  4569. * @param array $sessionsDestination
  4570. * @return string
  4571. */
  4572. public static function copyStudentsFromSession($sessions, $sessionsDestination)
  4573. {
  4574. $messages = array();
  4575. if (!empty($sessions)) {
  4576. foreach ($sessions as $sessionId) {
  4577. $sessionInfo = self::fetch($sessionId);
  4578. $userList = self::get_users_by_session($sessionId, 0);
  4579. if (!empty($userList)) {
  4580. $newUserList = array();
  4581. $userToString = null;
  4582. foreach ($userList as $userInfo) {
  4583. $newUserList[] = $userInfo['user_id'];
  4584. $userToString .= $userInfo['firstname'] . ' ' . $userInfo['lastname'] . '<br />';
  4585. }
  4586. if (!empty($sessionsDestination)) {
  4587. foreach ($sessionsDestination as $sessionDestinationId) {
  4588. $sessionDestinationInfo = self::fetch($sessionDestinationId);
  4589. $messages[] = Display::return_message(
  4590. sprintf(get_lang('AddingStudentsFromSessionXToSessionY'), $sessionInfo['name'], $sessionDestinationInfo['name']), 'info', false
  4591. );
  4592. if ($sessionId == $sessionDestinationId) {
  4593. $messages[] = Display::return_message(sprintf(get_lang('SessionXSkipped'), $sessionDestinationId), 'warning', false);
  4594. continue;
  4595. }
  4596. $messages[] = Display::return_message(get_lang('StudentList') . '<br />' . $userToString, 'info', false);
  4597. SessionManager::suscribe_users_to_session(
  4598. $sessionDestinationId,
  4599. $newUserList,
  4600. SESSION_VISIBLE_READ_ONLY,
  4601. false
  4602. );
  4603. }
  4604. } else {
  4605. $messages[] = Display::return_message(get_lang('NoDestinationSessionProvided'), 'warning');
  4606. }
  4607. } else {
  4608. $messages[] = Display::return_message(
  4609. get_lang('NoStudentsFoundForSession').' #'.$sessionInfo['name'],
  4610. 'warning'
  4611. );
  4612. }
  4613. }
  4614. } else {
  4615. $messages[] = Display::return_message(get_lang('NoData'), 'warning');
  4616. }
  4617. return $messages;
  4618. }
  4619. /**
  4620. * Assign coaches of a session(s) as teachers to a given course (or courses)
  4621. * @param array A list of session IDs
  4622. * @param array A list of course IDs
  4623. * @return string
  4624. */
  4625. public static function copyCoachesFromSessionToCourse($sessions, $courses)
  4626. {
  4627. $coachesPerSession = array();
  4628. foreach ($sessions as $sessionId) {
  4629. $coaches = self::getCoachesBySession($sessionId);
  4630. $coachesPerSession[$sessionId] = $coaches;
  4631. }
  4632. $result = array();
  4633. if (!empty($courses)) {
  4634. foreach ($courses as $courseId) {
  4635. $courseInfo = api_get_course_info_by_id($courseId);
  4636. foreach ($coachesPerSession as $sessionId => $coachList) {
  4637. CourseManager::updateTeachers(
  4638. $courseInfo['real_id'], $coachList, false, false, false
  4639. );
  4640. $result[$courseInfo['code']][$sessionId] = $coachList;
  4641. }
  4642. }
  4643. }
  4644. $sessionUrl = api_get_path(WEB_CODE_PATH) . 'admin/resume_session.php?id_session=';
  4645. $htmlResult = null;
  4646. if (!empty($result)) {
  4647. foreach ($result as $courseCode => $data) {
  4648. $url = api_get_course_url($courseCode);
  4649. $htmlResult .= sprintf(
  4650. get_lang('CoachesSubscribedAsATeacherInCourseX'),
  4651. Display::url($courseCode, $url, array('target' => '_blank'))
  4652. );
  4653. foreach ($data as $sessionId => $coachList) {
  4654. $sessionInfo = self::fetch($sessionId);
  4655. $htmlResult .= '<br />';
  4656. $htmlResult .= Display::url(
  4657. get_lang('Session') . ': ' . $sessionInfo['name'] . ' <br />', $sessionUrl . $sessionId, array('target' => '_blank')
  4658. );
  4659. $teacherList = array();
  4660. foreach ($coachList as $coachId) {
  4661. $userInfo = api_get_user_info($coachId);
  4662. $teacherList[] = $userInfo['complete_name'];
  4663. }
  4664. if (!empty($teacherList)) {
  4665. $htmlResult .= implode(', ', $teacherList);
  4666. } else {
  4667. $htmlResult .= get_lang('NothingToAdd');
  4668. }
  4669. }
  4670. $htmlResult .= '<br />';
  4671. }
  4672. $htmlResult = Display::return_message($htmlResult, 'normal', false);
  4673. }
  4674. return $htmlResult;
  4675. }
  4676. /**
  4677. * @param string $keyword
  4678. * @param string $active
  4679. * @param string $lastConnectionDate
  4680. * @param array $sessionIdList
  4681. * @param array $studentIdList
  4682. * @param int $userStatus STUDENT|COURSEMANAGER constants
  4683. *
  4684. * @return array|int
  4685. */
  4686. public static function getCountUserTracking(
  4687. $keyword = null,
  4688. $active = null,
  4689. $lastConnectionDate = null,
  4690. $sessionIdList = array(),
  4691. $studentIdList = array(),
  4692. $filterUserStatus = null
  4693. ) {
  4694. $userId = api_get_user_id();
  4695. $drhLoaded = false;
  4696. if (api_is_drh()) {
  4697. if (api_drh_can_access_all_session_content()) {
  4698. $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
  4699. 'drh_all',
  4700. $userId,
  4701. true,
  4702. null,
  4703. null,
  4704. null,
  4705. null,
  4706. $keyword,
  4707. $active,
  4708. $lastConnectionDate,
  4709. $sessionIdList,
  4710. $studentIdList,
  4711. $filterUserStatus
  4712. );
  4713. $drhLoaded = true;
  4714. }
  4715. }
  4716. if ($drhLoaded == false) {
  4717. $count = UserManager::getUsersFollowedByUser(
  4718. $userId,
  4719. $filterUserStatus,
  4720. false,
  4721. false,
  4722. true,
  4723. null,
  4724. null,
  4725. null,
  4726. null,
  4727. $active,
  4728. $lastConnectionDate,
  4729. api_is_student_boss() ? STUDENT_BOSS : COURSEMANAGER,
  4730. $keyword
  4731. );
  4732. }
  4733. return $count;
  4734. }
  4735. /**
  4736. * Get teachers followed by a user
  4737. * @param int $userId
  4738. * @param int $active
  4739. * @param string $lastConnectionDate
  4740. * @param bool $getCount
  4741. * @param array $sessionIdList
  4742. * @return array|int
  4743. */
  4744. public static function getTeacherTracking(
  4745. $userId,
  4746. $active = 1,
  4747. $lastConnectionDate = null,
  4748. $getCount = false,
  4749. $sessionIdList = array()
  4750. ) {
  4751. $teacherListId = array();
  4752. if (api_is_drh() || api_is_platform_admin()) {
  4753. // Followed teachers by drh
  4754. if (api_drh_can_access_all_session_content()) {
  4755. if (empty($sessionIdList)) {
  4756. $sessions = SessionManager::get_sessions_followed_by_drh($userId);
  4757. $sessionIdList = array();
  4758. foreach ($sessions as $session) {
  4759. $sessionIdList[] = $session['id'];
  4760. }
  4761. }
  4762. $sessionIdList = array_map('intval', $sessionIdList);
  4763. $sessionToString = implode("', '", $sessionIdList);
  4764. $course = Database::get_main_table(TABLE_MAIN_COURSE);
  4765. $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  4766. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4767. // Select the teachers.
  4768. $sql = "SELECT DISTINCT(cu.user_id) FROM $course c
  4769. INNER JOIN $sessionCourse src ON c.id = src.c_id
  4770. INNER JOIN $courseUser cu ON (cu.c_id = c.id)
  4771. WHERE src.session_id IN ('$sessionToString') AND cu.status = 1";
  4772. $result = Database::query($sql);
  4773. while($row = Database::fetch_array($result, 'ASSOC')) {
  4774. $teacherListId[$row['user_id']] = $row['user_id'];
  4775. }
  4776. } else {
  4777. $teacherResult = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
  4778. foreach ($teacherResult as $userInfo) {
  4779. $teacherListId[] = $userInfo['user_id'];
  4780. }
  4781. }
  4782. }
  4783. if (!empty($teacherListId)) {
  4784. $tableUser = Database::get_main_table(TABLE_MAIN_USER);
  4785. $select = "SELECT DISTINCT u.* ";
  4786. if ($getCount) {
  4787. $select = "SELECT count(DISTINCT(u.user_id)) as count";
  4788. }
  4789. $sql = "$select FROM $tableUser u";
  4790. if (!empty($lastConnectionDate)) {
  4791. $tableLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  4792. //$sql .= " INNER JOIN $tableLogin l ON (l.login_user_id = u.user_id) ";
  4793. }
  4794. $active = intval($active);
  4795. $teacherListId = implode("','", $teacherListId);
  4796. $where = " WHERE u.active = $active AND u.user_id IN ('$teacherListId') ";
  4797. if (!empty($lastConnectionDate)) {
  4798. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  4799. //$where .= " AND l.login_date <= '$lastConnectionDate' ";
  4800. }
  4801. $sql .= $where;
  4802. $result = Database::query($sql);
  4803. if (Database::num_rows($result)) {
  4804. if ($getCount) {
  4805. $row = Database::fetch_array($result);
  4806. return $row['count'];
  4807. } else {
  4808. return Database::store_result($result, 'ASSOC');
  4809. }
  4810. }
  4811. }
  4812. return 0;
  4813. }
  4814. /**
  4815. * Get the list of course tools that have to be dealt with in case of
  4816. * registering any course to a session
  4817. * @return array The list of tools to be dealt with (literal names)
  4818. */
  4819. public static function getCourseToolToBeManaged()
  4820. {
  4821. return array(
  4822. 'courseDescription',
  4823. 'courseIntroduction',
  4824. );
  4825. }
  4826. /**
  4827. * Calls the methods bound to each tool when a course is registered into a session
  4828. * @param int $sessionId
  4829. * @param int $courseId
  4830. * @return void
  4831. */
  4832. public static function installCourse($sessionId, $courseId)
  4833. {
  4834. return true;
  4835. $toolList = self::getCourseToolToBeManaged();
  4836. foreach ($toolList as $tool) {
  4837. $method = 'add' . $tool;
  4838. if (method_exists(get_class(), $method)) {
  4839. self::$method($sessionId, $courseId);
  4840. }
  4841. }
  4842. }
  4843. /**
  4844. * Calls the methods bound to each tool when a course is unregistered from
  4845. * a session
  4846. * @param int $sessionId
  4847. * @param int $courseId
  4848. */
  4849. public static function unInstallCourse($sessionId, $courseId)
  4850. {
  4851. return true;
  4852. $toolList = self::getCourseToolToBeManaged();
  4853. foreach ($toolList as $tool) {
  4854. $method = 'remove' . $tool;
  4855. if (method_exists(get_class(), $method)) {
  4856. self::$method($sessionId, $courseId);
  4857. }
  4858. }
  4859. }
  4860. /**
  4861. * @param int $sessionId
  4862. * @param int $courseId
  4863. */
  4864. public static function addCourseIntroduction($sessionId, $courseId)
  4865. {
  4866. // @todo create a tool intro lib
  4867. $sessionId = intval($sessionId);
  4868. $courseId = intval($courseId);
  4869. $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
  4870. $sql = "SELECT * FROM $TBL_INTRODUCTION WHERE c_id = $courseId";
  4871. $result = Database::query($sql);
  4872. $result = Database::store_result($result, 'ASSOC');
  4873. if (!empty($result)) {
  4874. foreach ($result as $result) {
  4875. // @todo check if relation exits.
  4876. $result['session_id'] = $sessionId;
  4877. Database::insert($TBL_INTRODUCTION, $result);
  4878. }
  4879. }
  4880. }
  4881. /**
  4882. * @param int $sessionId
  4883. * @param int $courseId
  4884. */
  4885. public static function removeCourseIntroduction($sessionId, $courseId)
  4886. {
  4887. $sessionId = intval($sessionId);
  4888. $courseId = intval($courseId);
  4889. $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
  4890. $sql = "DELETE FROM $TBL_INTRODUCTION
  4891. WHERE c_id = $courseId AND session_id = $sessionId";
  4892. Database::query($sql);
  4893. }
  4894. /**
  4895. * @param int $sessionId
  4896. * @param int $courseId
  4897. */
  4898. public static function addCourseDescription($sessionId, $courseId)
  4899. {
  4900. /* $description = new CourseDescription();
  4901. $descriptions = $description->get_descriptions($courseId);
  4902. foreach ($descriptions as $description) {
  4903. } */
  4904. }
  4905. /**
  4906. * @param int $sessionId
  4907. * @param int $courseId
  4908. */
  4909. public static function removeCourseDescription($sessionId, $courseId)
  4910. {
  4911. }
  4912. /**
  4913. * @param array $userSessionList format see self::importSessionDrhCSV()
  4914. * @param bool $sendEmail
  4915. * @param bool $removeOldRelationShips
  4916. * @return string
  4917. */
  4918. public static function subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips)
  4919. {
  4920. if (!empty($userSessionList)) {
  4921. foreach ($userSessionList as $userId => $data) {
  4922. $sessionList = array();
  4923. foreach ($data['session_list'] as $sessionInfo) {
  4924. $sessionList[] = $sessionInfo['session_id'];
  4925. }
  4926. $userInfo = $data['user_info'];
  4927. self::suscribe_sessions_to_hr_manager(
  4928. $userInfo,
  4929. $sessionList,
  4930. $sendEmail,
  4931. $removeOldRelationShips
  4932. );
  4933. }
  4934. }
  4935. }
  4936. /**
  4937. * @param array $userSessionList format see self::importSessionDrhCSV()
  4938. *
  4939. * @return string
  4940. */
  4941. public static function checkSubscribeDrhToSessionList($userSessionList)
  4942. {
  4943. $message = null;
  4944. if (!empty($userSessionList)) {
  4945. if (!empty($userSessionList)) {
  4946. foreach ($userSessionList as $userId => $data) {
  4947. $userInfo = $data['user_info'];
  4948. $sessionListSubscribed = self::get_sessions_followed_by_drh($userId);
  4949. if (!empty($sessionListSubscribed)) {
  4950. $sessionListSubscribed = array_keys($sessionListSubscribed);
  4951. }
  4952. $sessionList = array();
  4953. if (!empty($data['session_list'])) {
  4954. foreach ($data['session_list'] as $sessionInfo) {
  4955. if (in_array($sessionInfo['session_id'], $sessionListSubscribed)) {
  4956. $sessionList[] = $sessionInfo['session_info']['name'];
  4957. }
  4958. }
  4959. }
  4960. $message .= '<strong>' . get_lang('User') . '</strong> ' . $userInfo['complete_name'] . ' <br />';
  4961. if (!in_array($userInfo['status'], array(DRH)) && !api_is_platform_admin_by_id($userInfo['user_id'])) {
  4962. $message .= get_lang('UserMustHaveTheDrhRole') . '<br />';
  4963. continue;
  4964. }
  4965. if (!empty($sessionList)) {
  4966. $message .= '<strong>' . get_lang('Sessions') . ':</strong> <br />';
  4967. $message .= implode(', ', $sessionList) . '<br /><br />';
  4968. } else {
  4969. $message .= get_lang('NoSessionProvided') . ' <br /><br />';
  4970. }
  4971. }
  4972. }
  4973. }
  4974. return $message;
  4975. }
  4976. /**
  4977. * @param string $file
  4978. * @param bool $sendEmail
  4979. * @param bool $removeOldRelationShips
  4980. *
  4981. * @return string
  4982. */
  4983. public static function importSessionDrhCSV($file, $sendEmail, $removeOldRelationShips)
  4984. {
  4985. $list = Import::csv_reader($file);
  4986. if (!empty($list)) {
  4987. $userSessionList = array();
  4988. foreach ($list as $data) {
  4989. $userInfo = api_get_user_info_from_username($data['Username']);
  4990. $sessionInfo = self::get_session_by_name($data['SessionName']);
  4991. if (!empty($userInfo) && !empty($sessionInfo)) {
  4992. $userSessionList[$userInfo['user_id']]['session_list'][] = array(
  4993. 'session_id' => $sessionInfo['id'],
  4994. 'session_info' => $sessionInfo,
  4995. );
  4996. $userSessionList[$userInfo['user_id']]['user_info'] = $userInfo;
  4997. }
  4998. }
  4999. self::subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips);
  5000. return self::checkSubscribeDrhToSessionList($userSessionList);
  5001. }
  5002. }
  5003. /**
  5004. * Courses re-ordering in resume_session.php flag see BT#8316
  5005. */
  5006. public static function orderCourseIsEnabled()
  5007. {
  5008. $sessionCourseOrder = api_get_setting('session_course_ordering');
  5009. if ($sessionCourseOrder === 'true') {
  5010. return true;
  5011. }
  5012. return false;
  5013. }
  5014. /**
  5015. * @param string $direction (up/down)
  5016. * @param int $sessionId
  5017. * @param int $courseId
  5018. * @return bool
  5019. */
  5020. public static function move($direction, $sessionId, $courseId)
  5021. {
  5022. if (!self::orderCourseIsEnabled()) {
  5023. return false;
  5024. }
  5025. $sessionId = intval($sessionId);
  5026. $courseId = intval($courseId);
  5027. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  5028. $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
  5029. $position = array();
  5030. $count = 0;
  5031. foreach ($courseList as $course) {
  5032. if ($course['position'] == '') {
  5033. $course['position'] = $count;
  5034. }
  5035. $position[$course['code']] = $course['position'];
  5036. // Saving current order.
  5037. $sql = "UPDATE $table SET position = $count
  5038. WHERE session_id = $sessionId AND c_id = '".$course['real_id']."'";
  5039. Database::query($sql);
  5040. $count++;
  5041. }
  5042. // Loading new positions.
  5043. $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
  5044. $found = false;
  5045. switch ($direction) {
  5046. case 'up':
  5047. $courseList = array_reverse($courseList);
  5048. break;
  5049. case 'down':
  5050. break;
  5051. }
  5052. foreach ($courseList as $course) {
  5053. if ($found) {
  5054. $nextId = $course['real_id'];
  5055. $nextOrder = $course['position'];
  5056. break;
  5057. }
  5058. if ($courseId == $course['real_id']) {
  5059. $thisCourseCode = $course['real_id'];
  5060. $thisOrder = $course['position'];
  5061. $found = true;
  5062. }
  5063. }
  5064. $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."'
  5065. WHERE session_id = $sessionId AND c_id = $thisCourseCode";
  5066. Database::query($sql1);
  5067. $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."'
  5068. WHERE session_id = $sessionId AND c_id = $nextId";
  5069. Database::query($sql2);
  5070. return true;
  5071. }
  5072. /**
  5073. * @param int $sessionId
  5074. * @param int $courseId
  5075. * @return bool
  5076. */
  5077. public static function moveUp($sessionId, $courseId)
  5078. {
  5079. return self::move('up', $sessionId, $courseId);
  5080. }
  5081. /**
  5082. * @param int $sessionId
  5083. * @param string $courseCode
  5084. * @return bool
  5085. */
  5086. public static function moveDown($sessionId, $courseCode)
  5087. {
  5088. return self::move('down', $sessionId, $courseCode);
  5089. }
  5090. /**
  5091. * Use the session duration to allow/block user access see BT#8317
  5092. * Needs these DB changes
  5093. * ALTER TABLE session ADD COLUMN duration int;
  5094. * ALTER TABLE session_rel_user ADD COLUMN duration int;
  5095. */
  5096. public static function durationPerUserIsEnabled()
  5097. {
  5098. return api_get_configuration_value('session_duration_feature');
  5099. }
  5100. /**
  5101. * Returns the number of days the student has left in a session when using
  5102. * sessions durations
  5103. * @param int $userId
  5104. * @param int $sessionId
  5105. * @param int $duration in days
  5106. * @return int
  5107. */
  5108. public static function getDayLeftInSession($sessionId, $userId, $duration)
  5109. {
  5110. // Get an array with the details of the first access of the student to
  5111. // this session
  5112. $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
  5113. $sessionId,
  5114. $userId
  5115. );
  5116. $currentTime = time();
  5117. // If no previous access, return false
  5118. if (count($courseAccess) == 0) {
  5119. return false;
  5120. }
  5121. $firstAccess = api_strtotime($courseAccess['login_course_date'], 'UTC');
  5122. $endDateInSeconds = $firstAccess + $duration*24*60*60;
  5123. $leftDays = round(($endDateInSeconds- $currentTime) / 60 / 60 / 24);
  5124. return $leftDays;
  5125. }
  5126. /**
  5127. * @param int $duration
  5128. * @param int $userId
  5129. * @param int $sessionId
  5130. */
  5131. public static function editUserSessionDuration($duration, $userId, $sessionId)
  5132. {
  5133. $duration = intval($duration);
  5134. $userId = intval($userId);
  5135. $sessionId = intval($sessionId);
  5136. if (empty($userId) || empty($sessionId)) {
  5137. return false;
  5138. }
  5139. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  5140. $parameters = array('duration' => $duration);
  5141. $where = array('session_id = ? AND user_id = ? ' => array($sessionId, $userId));
  5142. Database::update($table, $parameters, $where);
  5143. }
  5144. /**
  5145. * Gets one row from the session_rel_user table
  5146. * @param int $userId
  5147. * @param int $sessionId
  5148. *
  5149. * @return array
  5150. */
  5151. public static function getUserSession($userId, $sessionId)
  5152. {
  5153. $userId = intval($userId);
  5154. $sessionId = intval($sessionId);
  5155. if (empty($userId) || empty($sessionId)) {
  5156. return false;
  5157. }
  5158. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  5159. $sql = "SELECT * FROM $table
  5160. WHERE session_id = $sessionId AND user_id = $userId";
  5161. $result = Database::query($sql);
  5162. $values = array();
  5163. if (Database::num_rows($result)) {
  5164. $values = Database::fetch_array($result, 'ASSOC');
  5165. }
  5166. return $values;
  5167. }
  5168. /**
  5169. * Check if user is subscribed inside a session as student
  5170. * @param int $sessionId The session id
  5171. * @param int $userId The user id
  5172. * @return boolean Whether is subscribed
  5173. */
  5174. public static function isUserSubscribedAsStudent($sessionId, $userId)
  5175. {
  5176. $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  5177. $sessionId = intval($sessionId);
  5178. $userId = intval($userId);
  5179. // COUNT(1) actually returns the number of rows from the table (as if
  5180. // counting the results from the first column)
  5181. $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
  5182. WHERE
  5183. session_id = $sessionId AND
  5184. user_id = $userId AND
  5185. relation_type = 0";
  5186. $result = Database::fetch_assoc(Database::query($sql));
  5187. if (!empty($result) && $result['qty'] > 0) {
  5188. return true;
  5189. }
  5190. return false;
  5191. }
  5192. /**
  5193. * Get the session coached by a user (general coach and course-session coach)
  5194. * @param int $coachId The coach id
  5195. * @param boolean $checkSessionRelUserVisibility Check the session visibility
  5196. * @param boolean $asPlatformAdmin The user is a platform admin and we want all sessions
  5197. * @return array The session list
  5198. */
  5199. public static function getSessionsCoachedByUser($coachId, $checkSessionRelUserVisibility = false, $asPlatformAdmin = false)
  5200. {
  5201. // Get all sessions where $coachId is the general coach
  5202. $sessions = self::get_sessions_by_general_coach($coachId, $asPlatformAdmin);
  5203. // Get all sessions where $coachId is the course - session coach
  5204. $courseSessionList = self::getCoursesListByCourseCoach($coachId);
  5205. $sessionsByCoach = array();
  5206. if (!empty($courseSessionList)) {
  5207. foreach ($courseSessionList as $userCourseSubscription) {
  5208. $session = $userCourseSubscription->getSession();
  5209. $sessionsByCoach[$session->getId()] = api_get_session_info(
  5210. $session->getId()
  5211. );
  5212. }
  5213. }
  5214. if (!empty($sessionsByCoach)) {
  5215. $sessions = array_merge($sessions, $sessionsByCoach);
  5216. }
  5217. // Remove repeated sessions
  5218. if (!empty($sessions)) {
  5219. $cleanSessions = array();
  5220. foreach ($sessions as $session) {
  5221. $cleanSessions[$session['id']] = $session;
  5222. }
  5223. $sessions = $cleanSessions;
  5224. }
  5225. if ($checkSessionRelUserVisibility) {
  5226. if (!empty($sessions)) {
  5227. $newSessions = array();
  5228. foreach ($sessions as $session) {
  5229. $visibility = api_get_session_visibility($session['id']);
  5230. if ($visibility == SESSION_INVISIBLE) {
  5231. continue;
  5232. }
  5233. $newSessions[] = $session;
  5234. }
  5235. $sessions = $newSessions;
  5236. }
  5237. }
  5238. return $sessions;
  5239. }
  5240. /**
  5241. * Check if the course belongs to the session
  5242. * @param int $sessionId The session id
  5243. * @param string $courseCode The course code
  5244. *
  5245. * @return bool
  5246. */
  5247. public static function sessionHasCourse($sessionId, $courseCode)
  5248. {
  5249. $sessionId = intval($sessionId);
  5250. $courseCode = Database::escape_string($courseCode);
  5251. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  5252. $sessionRelCourseTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  5253. $sql = "SELECT COUNT(1) AS qty
  5254. FROM $courseTable c
  5255. INNER JOIN $sessionRelCourseTable src
  5256. ON c.id = src.c_id
  5257. WHERE src.session_id = $sessionId
  5258. AND c.code = '$courseCode' ";
  5259. $result = Database::query($sql);
  5260. if ($result !== false) {
  5261. $data = Database::fetch_assoc($result);
  5262. if ($data['qty'] > 0) {
  5263. return true;
  5264. }
  5265. }
  5266. return false;
  5267. }
  5268. /**
  5269. * Get the list of course coaches
  5270. * @return array The list
  5271. */
  5272. public static function getAllCourseCoaches()
  5273. {
  5274. $coaches = array();
  5275. $scuTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5276. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  5277. $idResult = Database::select('DISTINCT user_id', $scuTable, array(
  5278. 'where' => array(
  5279. 'status = ?' => 2,
  5280. ),
  5281. ));
  5282. if ($idResult != false) {
  5283. foreach ($idResult as $idData) {
  5284. $userResult = Database::select('user_id, lastname, firstname, username', $userTable, array(
  5285. 'where' => array(
  5286. 'user_id = ?' => $idData['user_id'],
  5287. ),
  5288. ), 'first');
  5289. if ($userResult != false) {
  5290. $coaches[] = array(
  5291. 'id' => $userResult['user_id'],
  5292. 'lastname' => $userResult['lastname'],
  5293. 'firstname' => $userResult['firstname'],
  5294. 'username' => $userResult['username'],
  5295. 'completeName' => api_get_person_name(
  5296. $userResult['firstname'],
  5297. $userResult['lastname']
  5298. ),
  5299. );
  5300. }
  5301. }
  5302. }
  5303. return $coaches;
  5304. }
  5305. /**
  5306. * Calculate the total user time in the platform
  5307. * @param int $userId The user id
  5308. * @param string $from Optional. From date
  5309. * @param string $until Optional. Until date
  5310. * @return string The time (hh:mm:ss)
  5311. */
  5312. public static function getTotalUserTimeInPlatform($userId, $from = '', $until = '')
  5313. {
  5314. $userId = intval($userId);
  5315. $trackLoginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  5316. $whereConditions = array(
  5317. 'login_user_id = ? ' => $userId,
  5318. );
  5319. if (!empty($from) && !empty($until)) {
  5320. $whereConditions["AND (login_date >= '?' "] = $from;
  5321. $whereConditions["AND logout_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
  5322. }
  5323. $trackResult = Database::select(
  5324. 'SEC_TO_TIME(SUM(UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date))) as total_time',
  5325. $trackLoginTable,
  5326. array(
  5327. 'where' => $whereConditions,
  5328. ), 'first'
  5329. );
  5330. if ($trackResult != false) {
  5331. return $trackResult['total_time'] ? $trackResult['total_time'] : '00:00:00';
  5332. }
  5333. return '00:00:00';
  5334. }
  5335. /**
  5336. * Get the courses list by a course coach
  5337. * @param int $coachId The coach id
  5338. * @return array (id, user_id, session_id, c_id, visibility, status, legal_agreement)
  5339. */
  5340. public static function getCoursesListByCourseCoach($coachId)
  5341. {
  5342. $entityManager = Database::getManager();
  5343. $scuRepo = $entityManager->getRepository(
  5344. 'ChamiloCoreBundle:SessionRelCourseRelUser'
  5345. );
  5346. return $scuRepo->findBy([
  5347. 'user' => $coachId,
  5348. 'status' => SessionRelCourseRelUser::STATUS_COURSE_COACH
  5349. ]);
  5350. }
  5351. /**
  5352. * Get the count of user courses in session
  5353. * @param int $sessionId The session id
  5354. * @return array
  5355. */
  5356. public static function getTotalUserCoursesInSession($sessionId)
  5357. {
  5358. $tableUser = Database::get_main_table(TABLE_MAIN_USER);
  5359. $tableSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5360. $sql = "SELECT COUNT(1) as count, u.id, scu.status status_in_session, u.status user_status
  5361. FROM $tableSessionRelCourseRelUser scu
  5362. INNER JOIN $tableUser u ON scu.user_id = u.id
  5363. WHERE scu.session_id = " . intval($sessionId) ."
  5364. GROUP BY u.id";
  5365. $result = Database::query($sql);
  5366. $list = array();
  5367. while ($data = Database::fetch_assoc($result)) {
  5368. $list[] = $data;
  5369. }
  5370. return $list;
  5371. }
  5372. /**
  5373. * Returns list of a few data from session (name, short description, start
  5374. * date, end date) and the given extra fields if defined based on a
  5375. * session category Id.
  5376. * @param int $categoryId The internal ID of the session category
  5377. * @param string $target Value to search for in the session field values
  5378. * @param array $extraFields A list of fields to be scanned and returned
  5379. * @return mixed
  5380. */
  5381. public static function getShortSessionListAndExtraByCategory($categoryId, $target, $extraFields = null, $publicationDate = null)
  5382. {
  5383. // Init variables
  5384. $categoryId = (int) $categoryId;
  5385. $sessionList = array();
  5386. // Check if categoryId is valid
  5387. if ($categoryId > 0) {
  5388. $target = Database::escape_string($target);
  5389. $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
  5390. $sfTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  5391. $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  5392. // Join session field and session field values tables
  5393. $joinTable = $sfTable . ' sf INNER JOIN ' . $sfvTable . ' sfv ON sf.id = sfv.field_id';
  5394. $fieldsArray = array();
  5395. foreach ($extraFields as $field) {
  5396. $fieldsArray[] = Database::escape_string($field);
  5397. }
  5398. $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::SESSION_FIELD_TYPE;
  5399. if (isset ($publicationDate)) {
  5400. $publicationDateString = $publicationDate->format('Y-m-d H:i:s');
  5401. $wherePublication = " AND id NOT IN (
  5402. SELECT sfv.item_id FROM $joinTable
  5403. WHERE
  5404. sf.extra_field_type = $extraFieldType AND
  5405. ((sf.variable = 'publication_start_date' AND sfv.value > '$publicationDateString' and sfv.value != '') OR
  5406. (sf.variable = 'publication_end_date' AND sfv.value < '$publicationDateString' and sfv.value != ''))
  5407. )";
  5408. }
  5409. // Get the session list from session category and target
  5410. $sessionList = Database::select(
  5411. 'id, name, access_start_date, access_end_date',
  5412. $sTable,
  5413. array(
  5414. 'where' => array(
  5415. "session_category_id = ? AND id IN (
  5416. SELECT sfv.item_id FROM $joinTable
  5417. WHERE
  5418. sf.extra_field_type = $extraFieldType AND
  5419. sfv.item_id = session.id AND
  5420. sf.variable = 'target' AND
  5421. sfv.value = ?
  5422. ) $wherePublication" => array($categoryId, $target),
  5423. ),
  5424. )
  5425. );
  5426. $whereFieldVariables = array();
  5427. $whereFieldIds = array();
  5428. if (
  5429. is_array($fieldsArray) &&
  5430. count($fieldsArray) > 0
  5431. ) {
  5432. $whereParams = '?';
  5433. for ($i = 1; $i < count($fieldsArray); $i++) {
  5434. $whereParams .= ', ?';
  5435. }
  5436. $whereFieldVariables = ' variable IN ( ' . $whereParams .' )';
  5437. $whereFieldIds = 'field_id IN ( ' . $whereParams . ' )';
  5438. }
  5439. // Get session fields
  5440. $extraField = new ExtraField('session');
  5441. $questionMarks = substr(str_repeat('?, ', count($fieldsArray)), 0, -2);
  5442. $fieldsList = $extraField->get_all(array(
  5443. ' variable IN ( ' . $questionMarks . ' )' => $fieldsArray,
  5444. ));
  5445. // Index session fields
  5446. foreach ($fieldsList as $field) {
  5447. $fields[$field['id']] = $field['variable'];
  5448. }
  5449. // Get session field values
  5450. $extra = new ExtraFieldValue('session');
  5451. $questionMarksFields = substr(str_repeat('?, ', count($fields)), 0, -2);
  5452. $sessionFieldValueList = $extra->get_all(array ('where' => array('field_id IN ( ' . $questionMarksFields . ' )' => array_keys($fields))));
  5453. // Add session fields values to session list
  5454. foreach ($sessionList as $id => &$session) {
  5455. foreach ($sessionFieldValueList as $sessionFieldValue) {
  5456. // Match session field values to session
  5457. if ($sessionFieldValue['item_id'] == $id) {
  5458. // Check if session field value is set in session field list
  5459. if (isset($fields[$sessionFieldValue['field_id']])) {
  5460. // Avoid overwriting the session's ID field
  5461. if ($fields[$sessionFieldValue['field_id']] != 'id') {
  5462. $var = $fields[$sessionFieldValue['field_id']];
  5463. $val = $sessionFieldValue['value'];
  5464. // Assign session field value to session
  5465. $session[$var] = $val;
  5466. }
  5467. }
  5468. }
  5469. }
  5470. }
  5471. }
  5472. return $sessionList;
  5473. }
  5474. /**
  5475. * Return the Session Category id searched by name
  5476. * @param string $categoryName Name attribute of session category used for search query
  5477. * @param bool $force boolean used to get even if something is wrong (e.g not unique name)
  5478. * @return int|array If success, return category id (int), else it will return an array
  5479. * with the next structure:
  5480. * array('error' => true, 'errorMessage' => ERROR_MESSAGE)
  5481. */
  5482. public static function getSessionCategoryIdByName($categoryName, $force = false)
  5483. {
  5484. // Start error result
  5485. $errorResult = array('error' => true, 'errorMessage' => get_lang('ThereWasAnError'));
  5486. $categoryName = Database::escape_string($categoryName);
  5487. // Check if is not empty category name
  5488. if (!empty($categoryName)) {
  5489. $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  5490. // Get all session category with same name
  5491. $result = Database::select(
  5492. 'id',
  5493. $sessionCategoryTable,
  5494. array(
  5495. 'where' => array(
  5496. 'name = ?' => $categoryName,
  5497. ),
  5498. )
  5499. );
  5500. // Check the result
  5501. if ($result < 1) {
  5502. // If not found any result, update error message
  5503. $errorResult['errorMessage'] = 'Not found any session category name ' . $categoryName;
  5504. } elseif (count($result) > 1 && !$force) {
  5505. // If found more than one result and force is disabled, update error message
  5506. $errorResult['errorMessage'] = 'Found many session categories';
  5507. } elseif (count($result) == 1 || $force) {
  5508. // If found just one session category or force option is enabled
  5509. return key($result);
  5510. }
  5511. } else {
  5512. // category name is empty, update error message
  5513. $errorResult['errorMessage'] = 'Not valid category name';
  5514. }
  5515. return $errorResult;
  5516. }
  5517. /**
  5518. * Return all data from sessions (plus extra field, course and coach data) by category id
  5519. * @param int $sessionCategoryId session category id used to search sessions
  5520. * @return array If success, return session list and more session related data, else it will return an array
  5521. * with the next structure:
  5522. * array('error' => true, 'errorMessage' => ERROR_MESSAGE)
  5523. */
  5524. public static function getSessionListAndExtraByCategoryId($sessionCategoryId)
  5525. {
  5526. // Start error result
  5527. $errorResult = array(
  5528. 'error' => true,
  5529. 'errorMessage' => get_lang('ThereWasAnError'),
  5530. );
  5531. $sessionCategoryId = intval($sessionCategoryId);
  5532. // Check if session category id is valid
  5533. if ($sessionCategoryId > 0) {
  5534. // Get table names
  5535. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  5536. $sessionFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  5537. $sessionFieldValueTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  5538. $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5539. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  5540. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  5541. // Get all data from all sessions whit the session category specified
  5542. $sessionList = Database::select(
  5543. '*',
  5544. $sessionTable,
  5545. array(
  5546. 'where' => array(
  5547. 'session_category_id = ?' => $sessionCategoryId,
  5548. ),
  5549. )
  5550. );
  5551. $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::SESSION_FIELD_TYPE;
  5552. // Check if session list query had result
  5553. if (!empty($sessionList)) {
  5554. // implode all session id
  5555. $sessionIdsString = '(' . implode(', ', array_keys($sessionList)) . ')';
  5556. // Get all field variables
  5557. $sessionFieldList = Database::select(
  5558. 'id, variable',
  5559. $sessionFieldTable,
  5560. array('extra_field_type = ? ' => array($extraFieldType))
  5561. );
  5562. // Get all field values
  5563. $sql = "SELECT item_id, field_id, value FROM
  5564. $sessionFieldValueTable v INNER JOIN $sessionFieldTable f
  5565. ON (f.id = v.field_id)
  5566. WHERE
  5567. item_id IN $sessionIdsString AND
  5568. extra_field_type = $extraFieldType
  5569. ";
  5570. $result = Database::query($sql);
  5571. $sessionFieldValueList = Database::store_result($result, 'ASSOC');
  5572. // Check if session field values had result
  5573. if (!empty($sessionFieldValueList)) {
  5574. $sessionFieldValueListBySession = array();
  5575. foreach ($sessionFieldValueList as $key => $sessionFieldValue) {
  5576. // Create an array to index ids to session id
  5577. $sessionFieldValueListBySession[$sessionFieldValue['item_id']][] = $key;
  5578. }
  5579. }
  5580. // Query used to find course-coaches from sessions
  5581. $sql = "SELECT
  5582. scu.session_id,
  5583. c.id AS course_id,
  5584. c.code AS course_code,
  5585. c.title AS course_title,
  5586. u.username AS coach_username,
  5587. u.firstname AS coach_firstname,
  5588. u.lastname AS coach_lastname
  5589. FROM $courseTable c
  5590. INNER JOIN $sessionCourseUserTable scu ON c.id = scu.c_id
  5591. INNER JOIN $userTable u ON scu.user_id = u.user_id
  5592. WHERE scu.status = 2 AND scu.session_id IN $sessionIdsString
  5593. ORDER BY scu.session_id ASC ";
  5594. $res = Database::query($sql);
  5595. $sessionCourseList = Database::store_result($res, 'ASSOC');
  5596. // Check if course list had result
  5597. if (!empty($sessionCourseList)) {
  5598. foreach ($sessionCourseList as $key => $sessionCourse) {
  5599. // Create an array to index ids to session_id
  5600. $sessionCourseListBySession[$sessionCourse['session_id']][] = $key;
  5601. }
  5602. }
  5603. // Join lists
  5604. if (is_array($sessionList)) {
  5605. foreach ($sessionList as $id => &$row) {
  5606. if (
  5607. !empty($sessionFieldValueListBySession) &&
  5608. is_array($sessionFieldValueListBySession[$id])
  5609. ) {
  5610. // If have an index array for session extra fields, use it to join arrays
  5611. foreach ($sessionFieldValueListBySession[$id] as $key) {
  5612. $row['extra'][$key] = array(
  5613. 'field_name' => $sessionFieldList[$sessionFieldValueList[$key]['field_id']]['variable'],
  5614. 'value' => $sessionFieldValueList[$key]['value'],
  5615. );
  5616. }
  5617. }
  5618. if (
  5619. !empty($sessionCourseListBySession) &&
  5620. is_array($sessionCourseListBySession[$id])
  5621. ) {
  5622. // If have an index array for session course coach, use it to join arrays
  5623. foreach ($sessionCourseListBySession[$id] as $key) {
  5624. $row['course'][$key] = array(
  5625. 'course_id' => $sessionCourseList[$key]['course_id'],
  5626. 'course_code' => $sessionCourseList[$key]['course_code'],
  5627. 'course_title' => $sessionCourseList[$key]['course_title'],
  5628. 'coach_username' => $sessionCourseList[$key]['coach_username'],
  5629. 'coach_firstname' => $sessionCourseList[$key]['coach_firstname'],
  5630. 'coach_lastname' => $sessionCourseList[$key]['coach_lastname'],
  5631. );
  5632. }
  5633. }
  5634. }
  5635. }
  5636. return $sessionList;
  5637. } else {
  5638. // Not found result, update error message
  5639. $errorResult['errorMessage'] = 'Not found any session for session category id ' . $sessionCategoryId;
  5640. }
  5641. }
  5642. return $errorResult;
  5643. }
  5644. /**
  5645. * Return session description from session id
  5646. * @param int $sessionId
  5647. * @return string
  5648. */
  5649. public static function getDescriptionFromSessionId($sessionId)
  5650. {
  5651. // Init variables
  5652. $sessionId = intval($sessionId);
  5653. $description = '';
  5654. // Check if session id is valid
  5655. if ($sessionId > 0) {
  5656. // Select query from session id
  5657. $rows = Database::select(
  5658. 'description',
  5659. Database::get_main_table(TABLE_MAIN_SESSION),
  5660. array(
  5661. 'where' => array(
  5662. 'id = ?' => $sessionId,
  5663. ),
  5664. )
  5665. );
  5666. // Check if select query result is not empty
  5667. if (!empty($rows)) {
  5668. // Get session description
  5669. $description = $rows[0]['description'];
  5670. }
  5671. }
  5672. return $description;
  5673. }
  5674. /**
  5675. * Get a session list filtered by name, description or any of the given extra fields
  5676. * @param string $term The term to search
  5677. * @param array $extraFieldsToInclude Extra fields to include in the session data
  5678. * @return array The list
  5679. */
  5680. public static function searchSession($term, $extraFieldsToInclude = array())
  5681. {
  5682. $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
  5683. $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  5684. $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  5685. $term = Database::escape_string($term);
  5686. $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::SESSION_FIELD_TYPE;
  5687. if (is_array($extraFieldsToInclude) && count($extraFieldsToInclude) > 0) {
  5688. $resultData = Database::select('*', $sTable, array(
  5689. 'where' => array(
  5690. "name LIKE %?% " => $term,
  5691. " OR description LIKE %?% " => $term,
  5692. " OR id IN (
  5693. SELECT item_id
  5694. FROM $sfvTable v INNER JOIN $extraFieldTable e
  5695. ON (v.field_id = e.id)
  5696. WHERE value LIKE %?% AND extra_field_type = $extraFieldType
  5697. ) " => $term,
  5698. ),
  5699. ));
  5700. } else {
  5701. $resultData = Database::select('*', $sTable, array(
  5702. 'where' => array(
  5703. "name LIKE %?% " => $term,
  5704. "OR description LIKE %?% " => $term,
  5705. ),
  5706. ));
  5707. return $resultData;
  5708. }
  5709. foreach ($resultData as $id => &$session) {
  5710. $session['extra'] = self::getFilteredExtraFields($id, $extraFieldsToInclude);
  5711. }
  5712. return $resultData;
  5713. }
  5714. /**
  5715. * @param $sessionId
  5716. * @param array $extraFieldsToInclude
  5717. * @return array
  5718. */
  5719. public static function getFilteredExtraFields($sessionId, $extraFieldsToInclude = array())
  5720. {
  5721. $extraData = array();
  5722. $variables = array();
  5723. $variablePlaceHolders = array();
  5724. foreach ($extraFieldsToInclude as $sessionExtraField) {
  5725. $variablePlaceHolders[] = "?";
  5726. $variables[] = Database::escape_string($sessionExtraField);
  5727. }
  5728. $sessionExtraField = new ExtraField('session');
  5729. $fieldList = $sessionExtraField->get_all(array(
  5730. "variable IN ( " . implode(", ", $variablePlaceHolders) . " ) " => $variables,
  5731. ));
  5732. $fields = array();
  5733. // Index session fields
  5734. foreach ($fieldList as $field) {
  5735. $fields[$field['id']] = $field['variable'];
  5736. }
  5737. // Get session field values
  5738. $extra = new ExtraFieldValue('session');
  5739. $sessionFieldValueList = $extra->get_all(
  5740. array(
  5741. "field_id IN ( " . implode(", ", $variablePlaceHolders) . " )" => array_keys($fields),
  5742. )
  5743. );
  5744. foreach ($sessionFieldValueList as $sessionFieldValue) {
  5745. // Match session field values to session
  5746. if ($sessionFieldValue['item_id'] != $sessionId) {
  5747. continue;
  5748. }
  5749. // Check if session field value is set in session field list
  5750. if (!isset($fields[$sessionFieldValue['field_id']])) {
  5751. continue;
  5752. }
  5753. $extrafieldVariable = $fields[$sessionFieldValue['field_id']];
  5754. $extrafieldValue = $sessionFieldValue['value'];
  5755. $extraData[] = array(
  5756. 'variable' => $extrafieldVariable,
  5757. 'value' => $extrafieldValue,
  5758. );
  5759. }
  5760. return $extraData;
  5761. }
  5762. /**
  5763. * @param int $sessionId
  5764. *
  5765. * @return bool
  5766. */
  5767. public static function isValidId($sessionId)
  5768. {
  5769. $sessionId = intval($sessionId);
  5770. if ($sessionId > 0) {
  5771. $rows = Database::select(
  5772. 'id',
  5773. Database::get_main_table(TABLE_MAIN_SESSION),
  5774. array('where' => array('id = ?' => $sessionId))
  5775. );
  5776. if (!empty($rows)) {
  5777. return true;
  5778. }
  5779. }
  5780. return false;
  5781. }
  5782. /**
  5783. * Get list of sessions based on users of a group for a group admin
  5784. * @param int $userId The user id
  5785. * @return array
  5786. */
  5787. public static function getSessionsFollowedForGroupAdmin($userId)
  5788. {
  5789. $sessionList = array();
  5790. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  5791. $sessionUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  5792. $userGroup = new UserGroup();
  5793. $userIdList = $userGroup->getGroupUsersByUser($userId);
  5794. if (empty($userIdList)) {
  5795. return [];
  5796. }
  5797. $sql = "SELECT DISTINCT s.*
  5798. FROM $sessionTable s
  5799. INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
  5800. WHERE
  5801. (sru.id_user IN (" . implode(', ', $userIdList) . ")
  5802. AND sru.relation_type = 0
  5803. )";
  5804. if (api_is_multiple_url_enabled()) {
  5805. $sessionAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  5806. $accessUrlId = api_get_current_access_url_id();
  5807. if ($accessUrlId != -1) {
  5808. $sql = "SELECT DISTINCT s.*
  5809. FROM $sessionTable s
  5810. INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
  5811. INNER JOIN $sessionAccessUrlTable srau ON s.id = srau.session_id
  5812. WHERE
  5813. srau.access_url_id = $accessUrlId
  5814. AND (
  5815. sru.id_user IN (" . implode(', ', $userIdList) . ")
  5816. AND sru.relation_type = 0
  5817. )";
  5818. }
  5819. }
  5820. $result = Database::query($sql);
  5821. while ($row = Database::fetch_assoc($result)) {
  5822. $sessionList[] = $row;
  5823. }
  5824. return $sessionList;
  5825. }
  5826. /**
  5827. * @param array $sessionInfo
  5828. * @return string
  5829. */
  5830. public static function getSessionVisibility($sessionInfo)
  5831. {
  5832. switch($sessionInfo['visibility']) {
  5833. case 1:
  5834. return get_lang('ReadOnly');
  5835. case 2:
  5836. return get_lang('Visible');
  5837. case 3:
  5838. return api_ucfirst(get_lang('Invisible'));
  5839. }
  5840. }
  5841. /**
  5842. * Converts "start date" and "end date" to "From start date to end date" string
  5843. * @param string $startDate
  5844. * @param string $endDate
  5845. *
  5846. * @return string
  5847. */
  5848. private static function convertSessionDateToString($startDate, $endDate, $showTime, $dateHuman)
  5849. {
  5850. $startDateToLocal = '';
  5851. $endDateToLocal = '';
  5852. // This will clean the variables if 0000-00-00 00:00:00 the variable will be empty
  5853. if (isset($startDateToLocal)) {
  5854. $startDateToLocal = api_get_local_time($startDate, null, null, true, $showTime, $dateHuman);
  5855. }
  5856. if (isset($endDateToLocal)) {
  5857. $endDateToLocal = api_get_local_time($endDate, null, null, true, $showTime, $dateHuman);
  5858. }
  5859. $result = '';
  5860. if (!empty($startDateToLocal) && !empty($endDateToLocal)) {
  5861. $result = sprintf(get_lang('FromDateXToDateY'), $startDateToLocal, $endDateToLocal);
  5862. } else {
  5863. if (!empty($startDateToLocal)) {
  5864. $result = get_lang('From').' '.$startDateToLocal;
  5865. }
  5866. if (!empty($endDateToLocal)) {
  5867. $result = get_lang('Until').' '.$endDateToLocal;
  5868. }
  5869. }
  5870. if (empty($result)) {
  5871. $result = get_lang('NoTimeLimits');
  5872. }
  5873. return $result;
  5874. }
  5875. /**
  5876. * Returns a human readable string
  5877. * @params array $sessionInfo An array with all the session dates
  5878. * @return string
  5879. */
  5880. public static function parseSessionDates($sessionInfo)
  5881. {
  5882. $displayDates = self::convertSessionDateToString(
  5883. $sessionInfo['display_start_date'],
  5884. $sessionInfo['display_end_date'],
  5885. false,
  5886. true
  5887. );
  5888. $accessDates = self::convertSessionDateToString(
  5889. $sessionInfo['access_start_date'],
  5890. $sessionInfo['access_end_date'],
  5891. false,
  5892. true
  5893. );
  5894. $coachDates = self::convertSessionDateToString(
  5895. $sessionInfo['coach_access_start_date'],
  5896. $sessionInfo['coach_access_end_date'],
  5897. false,
  5898. true
  5899. );
  5900. $result = [
  5901. 'access' => $accessDates,
  5902. 'display' => $displayDates,
  5903. 'coach' => $coachDates,
  5904. ];
  5905. return $result;
  5906. }
  5907. /**
  5908. * @param FormValidator $form
  5909. *
  5910. * @return array
  5911. */
  5912. public static function setForm(FormValidator & $form, $sessionId = 0)
  5913. {
  5914. $categoriesList = SessionManager::get_all_session_category();
  5915. $userInfo = api_get_user_info();
  5916. $categoriesOptions = array(
  5917. '0' => get_lang('None')
  5918. );
  5919. if ($categoriesList != false) {
  5920. foreach ($categoriesList as $categoryItem) {
  5921. $categoriesOptions[$categoryItem['id']] = $categoryItem['name'];
  5922. }
  5923. }
  5924. // Database Table Definitions
  5925. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  5926. $form->addElement('text', 'name', get_lang('SessionName'), array(
  5927. 'maxlength' => 50,
  5928. ));
  5929. $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
  5930. $form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
  5931. if (!api_is_platform_admin() && api_is_teacher()) {
  5932. $form->addElement(
  5933. 'select',
  5934. 'coach_username',
  5935. get_lang('CoachName'),
  5936. [api_get_user_id() => $userInfo['complete_name']],
  5937. array(
  5938. 'id' => 'coach_username',
  5939. 'style' => 'width:370px;',
  5940. )
  5941. );
  5942. } else {
  5943. $sql = "SELECT COUNT(1) FROM $tbl_user WHERE status = 1";
  5944. $rs = Database::query($sql);
  5945. $countUsers = Database::result($rs, 0, 0);
  5946. if (intval($countUsers) < 50) {
  5947. $orderClause = "ORDER BY ";
  5948. $orderClause .= api_sort_by_first_name() ? "firstname, lastname, username" : "lastname, firstname, username";
  5949. $sql = "SELECT user_id, lastname, firstname, username
  5950. FROM $tbl_user
  5951. WHERE status = '1' ".
  5952. $orderClause;
  5953. if (api_is_multiple_url_enabled()) {
  5954. $userRelAccessUrlTable = Database::get_main_table(
  5955. TABLE_MAIN_ACCESS_URL_REL_USER
  5956. );
  5957. $accessUrlId = api_get_current_access_url_id();
  5958. if ($accessUrlId != -1) {
  5959. $sql = "SELECT user.user_id, username, lastname, firstname
  5960. FROM $tbl_user user
  5961. INNER JOIN $userRelAccessUrlTable url_user
  5962. ON (url_user.user_id = user.user_id)
  5963. WHERE
  5964. access_url_id = $accessUrlId AND
  5965. status = 1 "
  5966. .$orderClause;
  5967. }
  5968. }
  5969. $result = Database::query($sql);
  5970. $coachesList = Database::store_result($result);
  5971. $coachesOptions = array();
  5972. foreach ($coachesList as $coachItem) {
  5973. $coachesOptions[$coachItem['user_id']] =
  5974. api_get_person_name($coachItem['firstname'], $coachItem['lastname']).' ('.$coachItem['username'].')';
  5975. }
  5976. $form->addElement(
  5977. 'select',
  5978. 'coach_username',
  5979. get_lang('CoachName'),
  5980. $coachesOptions
  5981. );
  5982. } else {
  5983. $form->addElement(
  5984. 'select_ajax',
  5985. 'coach_username',
  5986. get_lang('CoachName'),
  5987. null,
  5988. [
  5989. 'url' => api_get_path(WEB_AJAX_PATH) . 'session.ajax.php?a=search_general_coach',
  5990. 'width' => '100%',
  5991. ]
  5992. );
  5993. }
  5994. }
  5995. $form->addRule('coach_username', get_lang('ThisFieldIsRequired'), 'required');
  5996. $form->addHtml('<div id="ajax_list_coachs"></div>');
  5997. $form->addButtonAdvancedSettings('advanced_params');
  5998. $form->addElement('html','<div id="advanced_params_options" style="display:none">');
  5999. if (empty($sessionId)) {
  6000. $sessions = SessionManager::get_sessions_admin();
  6001. $sessionList = [];
  6002. $sessionList[] = '';
  6003. foreach ($sessions as $session) {
  6004. $sessionList[$session['id']] = $session['name'];
  6005. }
  6006. $form->addSelect(
  6007. 'session_template',
  6008. get_lang('SessionTemplate'),
  6009. $sessionList,
  6010. ['id' => 'system_template']
  6011. );
  6012. }
  6013. $form->addSelect('session_category', get_lang('SessionCategory'), $categoriesOptions, array(
  6014. 'id' => 'session_category'
  6015. ));
  6016. $form->addHtmlEditor(
  6017. 'description',
  6018. get_lang('Description'),
  6019. false,
  6020. false,
  6021. array(
  6022. 'ToolbarSet' => 'Minimal',
  6023. )
  6024. );
  6025. $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'));
  6026. $visibilityGroup = array();
  6027. $visibilityGroup[] = $form->createElement('select', 'session_visibility', null, array(
  6028. SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
  6029. SESSION_VISIBLE => get_lang('SessionAccessible'),
  6030. SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible')),
  6031. ));
  6032. $form->addGroup($visibilityGroup, 'visibility_group', get_lang('SessionVisibility'), null, false);
  6033. $options = [
  6034. 0 => get_lang('ByDuration'),
  6035. 1 => get_lang('ByDates')
  6036. ];
  6037. $form->addSelect('access', get_lang('Access'), $options, array(
  6038. 'onchange' => 'accessSwitcher()',
  6039. 'id' => 'access'
  6040. ));
  6041. $form->addElement('html', '<div id="duration" style="display:none">');
  6042. $form->addElement(
  6043. 'number',
  6044. 'duration',
  6045. array(
  6046. get_lang('SessionDurationTitle'),
  6047. get_lang('SessionDurationDescription'),
  6048. ),
  6049. array(
  6050. 'maxlength' => 50,
  6051. )
  6052. );
  6053. $form->addElement('html', '</div>');
  6054. $form->addElement('html', '<div id="date_fields" style="display:none">');
  6055. // Dates
  6056. $form->addDateTimePicker(
  6057. 'access_start_date',
  6058. array(get_lang('SessionStartDate'), get_lang('SessionStartDateComment')),
  6059. array('id' => 'access_start_date')
  6060. );
  6061. $form->addDateTimePicker(
  6062. 'access_end_date',
  6063. array(get_lang('SessionEndDate'), get_lang('SessionEndDateComment')),
  6064. array('id' => 'access_end_date')
  6065. );
  6066. $form->addRule(
  6067. array('access_start_date', 'access_end_date'),
  6068. get_lang('StartDateMustBeBeforeTheEndDate'),
  6069. 'compare_datetime_text',
  6070. '< allow_empty'
  6071. );
  6072. $form->addDateTimePicker(
  6073. 'display_start_date',
  6074. array(
  6075. get_lang('SessionDisplayStartDate'),
  6076. get_lang('SessionDisplayStartDateComment'),
  6077. ),
  6078. array('id' => 'display_start_date')
  6079. );
  6080. $form->addDateTimePicker(
  6081. 'display_end_date',
  6082. array(
  6083. get_lang('SessionDisplayEndDate'),
  6084. get_lang('SessionDisplayEndDateComment'),
  6085. ),
  6086. array('id' => 'display_end_date')
  6087. );
  6088. $form->addRule(
  6089. array('display_start_date', 'display_end_date'),
  6090. get_lang('StartDateMustBeBeforeTheEndDate'),
  6091. 'compare_datetime_text',
  6092. '< allow_empty'
  6093. );
  6094. $form->addDateTimePicker(
  6095. 'coach_access_start_date',
  6096. array(
  6097. get_lang('SessionCoachStartDate'),
  6098. get_lang('SessionCoachStartDateComment'),
  6099. ),
  6100. array('id' => 'coach_access_start_date')
  6101. );
  6102. $form->addDateTimePicker(
  6103. 'coach_access_end_date',
  6104. array(
  6105. get_lang('SessionCoachEndDate'),
  6106. get_lang('SessionCoachEndDateComment'),
  6107. ),
  6108. array('id' => 'coach_access_end_date')
  6109. );
  6110. $form->addRule(
  6111. array('coach_access_start_date', 'coach_access_end_date'),
  6112. get_lang('StartDateMustBeBeforeTheEndDate'),
  6113. 'compare_datetime_text',
  6114. '< allow_empty'
  6115. );
  6116. $form->addElement('html', '</div>');
  6117. $form->addCheckBox(
  6118. 'send_subscription_notification',
  6119. [
  6120. get_lang('SendSubscriptionNotification'),
  6121. get_lang('SendAnEmailWhenAUserBeingSubscribed')
  6122. ]
  6123. );
  6124. // Extra fields
  6125. $extra_field = new ExtraField('session');
  6126. $extra = $extra_field->addElements($form, $sessionId);
  6127. $form->addElement('html','</div>');
  6128. $js = $extra['jquery_ready_content'];
  6129. return ['js' => $js];
  6130. }
  6131. /**
  6132. * Gets the number of rows in the session table filtered through the given
  6133. * array of parameters
  6134. * @param array Array of options/filters/keys
  6135. * @return integer The number of rows, or false on wrong param
  6136. * @assert ('a') === false
  6137. */
  6138. static function get_count_admin_complete($options = array())
  6139. {
  6140. if (!is_array($options)) {
  6141. return false;
  6142. }
  6143. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  6144. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  6145. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  6146. $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  6147. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  6148. $where = 'WHERE 1 = 1 ';
  6149. $user_id = api_get_user_id();
  6150. if (api_is_session_admin() &&
  6151. api_get_setting('allow_session_admins_to_see_all_sessions') == 'false'
  6152. ) {
  6153. $where.=" WHERE s.session_admin_id = $user_id ";
  6154. }
  6155. if (!empty($options['where'])) {
  6156. $options['where'] = str_replace('course_title', 'c.title', $options['where']);
  6157. $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
  6158. $options['where'] = str_replace(
  6159. array("AND session_active = '1' )", " AND ( session_active = '1' )"),
  6160. array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
  6161. , $options['where']
  6162. );
  6163. $options['where'] = str_replace(
  6164. array("AND session_active = '0' )", " AND ( session_active = '0' )"),
  6165. array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
  6166. $options['where']
  6167. );
  6168. if (!empty($options['extra'])) {
  6169. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  6170. $options['where'] = str_replace('AND', 'OR', $options['where']);
  6171. foreach ($options['extra'] as $extra) {
  6172. $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
  6173. }
  6174. }
  6175. $where .= ' AND '.$options['where'];
  6176. }
  6177. $today = api_get_utc_datetime();
  6178. $query_rows = "SELECT count(*) as total_rows, c.title as course_title, s.name,
  6179. IF (
  6180. (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
  6181. (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
  6182. (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
  6183. (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
  6184. ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
  6185. , 1, 0) as session_active
  6186. FROM $tbl_session s
  6187. LEFT JOIN $tbl_session_category sc
  6188. ON s.session_category_id = sc.id
  6189. INNER JOIN $tbl_user u
  6190. ON s.id_coach = u.user_id
  6191. INNER JOIN $sessionCourseUserTable scu
  6192. ON s.id = scu.session_id
  6193. INNER JOIN $courseTable c
  6194. ON c.id = scu.c_id
  6195. $where ";
  6196. if (api_is_multiple_url_enabled()) {
  6197. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  6198. $access_url_id = api_get_current_access_url_id();
  6199. if ($access_url_id != -1) {
  6200. $where.= " AND ar.access_url_id = $access_url_id ";
  6201. $query_rows = "SELECT count(*) as total_rows
  6202. FROM $tbl_session s
  6203. LEFT JOIN $tbl_session_category sc
  6204. ON s.session_category_id = sc.id
  6205. INNER JOIN $tbl_user u
  6206. ON s.id_coach = u.user_id
  6207. INNER JOIN $table_access_url_rel_session ar
  6208. ON ar.session_id = s.id $where ";
  6209. }
  6210. }
  6211. $result = Database::query($query_rows);
  6212. $num = 0;
  6213. if (Database::num_rows($result)) {
  6214. $rows = Database::fetch_array($result);
  6215. $num = $rows['total_rows'];
  6216. }
  6217. return $num;
  6218. }
  6219. /**
  6220. * @param string $list_type
  6221. * @return array
  6222. */
  6223. public static function getGridColumns($list_type = 'simple', $extraFields = array())
  6224. {
  6225. // Column config
  6226. $operators = array('cn', 'nc');
  6227. $date_operators = array('gt', 'ge', 'lt', 'le');
  6228. switch ($list_type) {
  6229. case 'simple':
  6230. $columns = array(
  6231. get_lang('Name'),
  6232. get_lang('Category'),
  6233. get_lang('SessionDisplayStartDate'),
  6234. get_lang('SessionDisplayEndDate'),
  6235. //get_lang('Coach'),
  6236. //get_lang('Status'),
  6237. //get_lang('CourseTitle'),
  6238. get_lang('Visibility'),
  6239. );
  6240. $column_model = array (
  6241. array('name'=>'name', 'index'=>'s.name', 'width'=>'160', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
  6242. array('name'=>'category_name', 'index'=>'category_name', 'width'=>'40', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
  6243. array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'50', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
  6244. array('name'=>'display_end_date', 'index'=>'display_end_date', 'width'=>'50', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_one_month', 'sopt' => $date_operators)),
  6245. array('name'=>'visibility', 'index'=>'visibility', 'width'=>'40', 'align'=>'left', 'search' => 'false'),
  6246. );
  6247. break;
  6248. case 'complete':
  6249. $columns = array(
  6250. get_lang('Name'),
  6251. get_lang('SessionDisplayStartDate'),
  6252. get_lang('SessionDisplayEndDate'),
  6253. get_lang('Coach'),
  6254. get_lang('Status'),
  6255. get_lang('Visibility'),
  6256. get_lang('CourseTitle'),
  6257. );
  6258. $column_model = array (
  6259. array('name'=>'name', 'index'=>'s.name', 'width'=>'200', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
  6260. array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
  6261. array('name'=>'display_end_date', 'index'=>'display_end_date', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_one_month', 'sopt' => $date_operators)),
  6262. array('name'=>'coach_name', 'index'=>'coach_name', 'width'=>'70', 'align'=>'left', 'search' => 'false', 'searchoptions' => array('sopt' => $operators)),
  6263. array('name'=>'session_active', 'index'=>'session_active', 'width'=>'25', 'align'=>'left', 'search' => 'true', 'stype'=>'select',
  6264. // for the bottom bar
  6265. 'searchoptions' => array(
  6266. 'defaultValue' => '1',
  6267. 'value' => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
  6268. // for the top bar
  6269. 'editoptions' => array('value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive')),
  6270. ),
  6271. array('name'=>'visibility', 'index'=>'visibility', 'width'=>'40', 'align'=>'left', 'search' => 'false'),
  6272. array('name'=>'course_title', 'index'=>'course_title', 'width'=>'50', 'hidden' => 'true', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true','sopt' => $operators)),
  6273. );
  6274. break;
  6275. }
  6276. if (!empty($extraFields)) {
  6277. foreach ($extraFields as $field) {
  6278. $columns[] = $field['display_text'];
  6279. $column_model[] = array(
  6280. 'name' => $field['variable'],
  6281. 'index' => $field['variable'],
  6282. 'width' => '80',
  6283. 'align' => 'left',
  6284. 'search' => 'false'
  6285. );
  6286. }
  6287. }
  6288. // Inject extra session fields
  6289. $session_field = new ExtraField('session');
  6290. $rules = $session_field->getRules($columns, $column_model);
  6291. $column_model[] = array(
  6292. 'name' => 'actions',
  6293. 'index' => 'actions',
  6294. 'width' => '80',
  6295. 'align' => 'left',
  6296. 'formatter' => 'action_formatter',
  6297. 'sortable' => 'false',
  6298. 'search' => 'false',
  6299. );
  6300. $columns[] = get_lang('Actions');
  6301. foreach ($column_model as $col_model) {
  6302. $simple_column_name[] = $col_model['name'];
  6303. }
  6304. $return_array = array(
  6305. 'columns' => $columns,
  6306. 'column_model' => $column_model,
  6307. 'rules' => $rules,
  6308. 'simple_column_name' => $simple_column_name,
  6309. );
  6310. return $return_array;
  6311. }
  6312. /**
  6313. * Converts all dates sent through the param array (given form) to correct dates with timezones
  6314. * @param array The dates The same array, with times converted
  6315. * @param boolean $applyFormat Whether apply the DATE_TIME_FORMAT_SHORT format for sessions
  6316. * @return array The same array, with times converted
  6317. */
  6318. static function convert_dates_to_local($params, $applyFormat = false)
  6319. {
  6320. if (!is_array($params)) {
  6321. return false;
  6322. }
  6323. $params['display_start_date'] = api_get_local_time($params['display_start_date'], null, null, true);
  6324. $params['display_end_date'] = api_get_local_time($params['display_end_date'], null, null, true);
  6325. $params['access_start_date'] = api_get_local_time($params['access_start_date'], null, null, true);
  6326. $params['access_end_date'] = api_get_local_time($params['access_end_date'], null, null, true);
  6327. $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_local_time($params['coach_access_start_date'], null, null, true) : null;
  6328. $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_local_time($params['coach_access_end_date'], null, null, true) : null;
  6329. if ($applyFormat) {
  6330. if (isset($params['display_start_date'])) {
  6331. $params['display_start_date'] = api_format_date($params['display_start_date'], DATE_TIME_FORMAT_SHORT);
  6332. }
  6333. if (isset($params['display_end_date'])) {
  6334. $params['display_end_date'] = api_format_date($params['display_end_date'], DATE_TIME_FORMAT_SHORT);
  6335. }
  6336. if (isset($params['access_start_date'])) {
  6337. $params[''] = api_format_date($params['access_start_date'], DATE_TIME_FORMAT_SHORT);
  6338. }
  6339. if (isset($params['access_end_date'])) {
  6340. $params['access_end_date'] = api_format_date($params['access_end_date'], DATE_TIME_FORMAT_SHORT);
  6341. }
  6342. if (isset($params['coach_access_start_date'])) {
  6343. $params['coach_access_start_date'] = api_format_date($params['coach_access_start_date'], DATE_TIME_FORMAT_SHORT);
  6344. }
  6345. if (isset($params['coach_access_end_date'])) {
  6346. $params['coach_access_end_date'] = api_format_date($params['coach_access_end_date'], DATE_TIME_FORMAT_SHORT);
  6347. }
  6348. }
  6349. return $params;
  6350. }
  6351. /**
  6352. * Gets the admin session list callback of the session/session_list.php
  6353. * page with all user/details in the right fomat
  6354. * @param array
  6355. * @result array Array of rows results
  6356. * @asset ('a') === false
  6357. */
  6358. public static function get_sessions_admin_complete($options = array())
  6359. {
  6360. if (!is_array($options)) {
  6361. return false;
  6362. }
  6363. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  6364. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  6365. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  6366. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  6367. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  6368. $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  6369. $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  6370. $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  6371. $where = 'WHERE 1 = 1 ';
  6372. $user_id = api_get_user_id();
  6373. if (!api_is_platform_admin()) {
  6374. if (api_is_session_admin() &&
  6375. api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
  6376. ) {
  6377. $where.=" AND s.session_admin_id = $user_id ";
  6378. }
  6379. }
  6380. $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
  6381. if (api_is_western_name_order()) {
  6382. $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
  6383. }
  6384. $today = api_get_utc_datetime();
  6385. $inject_extra_fields = null;
  6386. $extra_fields = array();
  6387. $extra_fields_info = array();
  6388. //for now only sessions
  6389. $extra_field = new ExtraField('session');
  6390. $double_fields = array();
  6391. $extra_field_option = new ExtraFieldOption('session');
  6392. if (isset($options['extra'])) {
  6393. $extra_fields = $options['extra'];
  6394. if (!empty($extra_fields)) {
  6395. foreach ($extra_fields as $extra) {
  6396. $inject_extra_fields .= " IF (fv.field_id = {$extra['id']}, fvo.option_display_text, NULL ) as {$extra['field']} , ";
  6397. if (isset($extra_fields_info[$extra['id']])) {
  6398. $info = $extra_fields_info[$extra['id']];
  6399. } else {
  6400. $info = $extra_field->get($extra['id']);
  6401. $extra_fields_info[$extra['id']] = $info;
  6402. }
  6403. if ($info['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
  6404. $double_fields[$info['id']] = $info;
  6405. }
  6406. }
  6407. }
  6408. }
  6409. $options_by_double = array();
  6410. foreach ($double_fields as $double) {
  6411. $my_options = $extra_field_option->get_field_options_by_field(
  6412. $double['id'],
  6413. true
  6414. );
  6415. $options_by_double['extra_'.$double['field_variable']] = $my_options;
  6416. }
  6417. //sc.name as category_name,
  6418. $select = "
  6419. SELECT * FROM (
  6420. SELECT DISTINCT
  6421. IF (
  6422. (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
  6423. (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
  6424. (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
  6425. (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
  6426. ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
  6427. , 1, 0) as session_active,
  6428. s.name,
  6429. s.nbr_courses,
  6430. s.nbr_users,
  6431. s.display_start_date,
  6432. s.display_end_date,
  6433. $coach_name,
  6434. access_start_date,
  6435. access_end_date,
  6436. s.visibility,
  6437. u.user_id,
  6438. $inject_extra_fields
  6439. c.title as course_title,
  6440. s.id ";
  6441. if (!empty($options['where'])) {
  6442. if (!empty($options['extra'])) {
  6443. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  6444. $options['where'] = str_replace('AND', 'OR', $options['where']);
  6445. foreach ($options['extra'] as $extra) {
  6446. $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
  6447. }
  6448. }
  6449. $options['where'] = str_replace('course_title', 'c.title', $options['where']);
  6450. $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
  6451. $options['where'] = str_replace(
  6452. array("AND session_active = '1' )", " AND ( session_active = '1' )"),
  6453. array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
  6454. , $options['where']
  6455. );
  6456. $options['where'] = str_replace(
  6457. array("AND session_active = '0' )", " AND ( session_active = '0' )"),
  6458. array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
  6459. $options['where']
  6460. );
  6461. $where .= ' AND '.$options['where'];
  6462. }
  6463. if (!empty($options['limit'])) {
  6464. $where .= " LIMIT ".$options['limit'];
  6465. }
  6466. $query = "$select FROM $tbl_session s
  6467. LEFT JOIN $tbl_session_field_values fv
  6468. ON (fv.item_id = s.id)
  6469. LEFT JOIN $extraFieldTable f
  6470. ON f.id = fv.field_id
  6471. LEFT JOIN $tbl_session_field_options fvo
  6472. ON (fv.field_id = fvo.field_id)
  6473. LEFT JOIN $tbl_session_rel_course src
  6474. ON (src.session_id = s.id)
  6475. LEFT JOIN $tbl_course c
  6476. ON (src.c_id = c.id)
  6477. LEFT JOIN $tbl_session_category sc
  6478. ON (s.session_category_id = sc.id)
  6479. INNER JOIN $tbl_user u
  6480. ON (s.id_coach = u.user_id) ".
  6481. $where;
  6482. if (api_is_multiple_url_enabled()) {
  6483. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  6484. $access_url_id = api_get_current_access_url_id();
  6485. if ($access_url_id != -1) {
  6486. $where.= " AND ar.access_url_id = $access_url_id ";
  6487. $query = "$select
  6488. FROM $tbl_session s
  6489. LEFT JOIN $tbl_session_field_values fv ON (fv.session_id = s.id)
  6490. LEFT JOIN $tbl_session_field_options fvo ON (fv.field_id = fvo.field_id)
  6491. LEFT JOIN $tbl_session_rel_course src ON (src.id_session = s.id)
  6492. LEFT JOIN $tbl_course c ON (src.c_id = c.id)
  6493. LEFT JOIN $tbl_session_category sc ON (s.session_category_id = sc.id)
  6494. INNER JOIN $tbl_user u ON (s.id_coach = u.user_id)
  6495. INNER JOIN $table_access_url_rel_session ar ON (ar.session_id = s.id)
  6496. $where";
  6497. }
  6498. }
  6499. $query .= ") AS session_table";
  6500. if (!empty($options['order'])) {
  6501. $query .= " ORDER BY ".$options['order'];
  6502. }
  6503. //error_log($query);
  6504. //echo $query;
  6505. $result = Database::query($query);
  6506. $formatted_sessions = array();
  6507. if (Database::num_rows($result)) {
  6508. $sessions = Database::store_result($result, 'ASSOC');
  6509. foreach ($sessions as $session) {
  6510. $session_id = $session['id'];
  6511. $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
  6512. $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
  6513. if ($session['session_active'] == 1) {
  6514. $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
  6515. } else {
  6516. $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
  6517. }
  6518. $session = self::convert_dates_to_local($session);
  6519. switch ($session['visibility']) {
  6520. case SESSION_VISIBLE_READ_ONLY: //1
  6521. $session['visibility'] = get_lang('ReadOnly');
  6522. break;
  6523. case SESSION_VISIBLE: //2
  6524. case SESSION_AVAILABLE: //4
  6525. $session['visibility'] = get_lang('Visible');
  6526. break;
  6527. case SESSION_INVISIBLE: //3
  6528. $session['visibility'] = api_ucfirst(get_lang('Invisible'));
  6529. break;
  6530. }
  6531. // Cleaning double selects
  6532. foreach ($session as $key => &$value) {
  6533. if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
  6534. $options = explode('::', $value);
  6535. }
  6536. $original_key = $key;
  6537. if (strpos($key, '_second') === false) {
  6538. } else {
  6539. $key = str_replace('_second', '', $key);
  6540. }
  6541. if (isset($options_by_double[$key])) {
  6542. if (isset($options[0])) {
  6543. if (isset($options_by_double[$key][$options[0]])) {
  6544. if (strpos($original_key, '_second') === false) {
  6545. $value = $options_by_double[$key][$options[0]]['option_display_text'];
  6546. } else {
  6547. $value = $options_by_double[$key][$options[1]]['option_display_text'];
  6548. }
  6549. }
  6550. }
  6551. }
  6552. }
  6553. // Magic filter
  6554. if (isset($formatted_sessions[$session_id])) {
  6555. $formatted_sessions[$session_id] = self::compareArraysToMerge($formatted_sessions[$session_id], $session);
  6556. } else {
  6557. $formatted_sessions[$session_id] = $session;
  6558. }
  6559. }
  6560. }
  6561. return $formatted_sessions;
  6562. }
  6563. /**
  6564. * Compare two arrays
  6565. * @param array $array1
  6566. * @param array $array2
  6567. *
  6568. * @return array
  6569. */
  6570. static function compareArraysToMerge($array1, $array2)
  6571. {
  6572. if (empty($array2)) {
  6573. return $array1;
  6574. }
  6575. foreach ($array1 as $key => $item) {
  6576. if (!isset($array1[$key])) {
  6577. //My string is empty try the other one
  6578. if (isset($array2[$key]) && !empty($array2[$key])) {
  6579. $array1[$key] = $array2[$key];
  6580. }
  6581. }
  6582. }
  6583. return $array1;
  6584. }
  6585. /**
  6586. * Get link to the admin page for this session
  6587. * @param int $id Session ID
  6588. * @return mixed URL to the admin page to manage the session, or false on error
  6589. */
  6590. public static function getAdminPath($id)
  6591. {
  6592. $id = intval($id);
  6593. $session = self::fetch($id);
  6594. if (empty($session)) {
  6595. return false;
  6596. }
  6597. return api_get_path(WEB_CODE_PATH) . 'session/resume_session.php?id_session=' . $id;
  6598. }
  6599. /**
  6600. * Get link to the user page for this session.
  6601. * If a course is provided, build the link to the course
  6602. * @param int $id Session ID
  6603. * @param int $courseId Course ID (optional) in case the link has to send straight to the course
  6604. * @return mixed URL to the page to use the session, or false on error
  6605. */
  6606. public static function getPath($id, $courseId = 0)
  6607. {
  6608. $id = intval($id);
  6609. $session = self::fetch($id);
  6610. if (empty($session)) {
  6611. return false;
  6612. }
  6613. if (empty($courseId)) {
  6614. return api_get_path(WEB_CODE_PATH) . 'session/index.php?session_id=' . $id;
  6615. } else {
  6616. $courseInfo = api_get_course_info_by_id($courseId);
  6617. if ($courseInfo) {
  6618. return $courseInfo['course_public_url'].'?id_session='.$id;
  6619. }
  6620. }
  6621. return false;
  6622. }
  6623. /**
  6624. * Return an associative array 'id_course' => [id_session1, id_session2...]
  6625. * where course id_course is in sessions id_session1, id_session2
  6626. * for course where user is coach
  6627. * i.e. coach for the course or
  6628. * main coach for a session the course is in
  6629. * for a session category (or woth no session category if empty)
  6630. *
  6631. * @param $userId
  6632. *
  6633. * @return array
  6634. */
  6635. public static function getSessionCourseForUser($userId)
  6636. {
  6637. // list of COURSES where user is COURSE session coach
  6638. $listCourseCourseCoachSession = self::getCoursesForCourseSessionCoach($userId);
  6639. // list of courses where user is MAIN session coach
  6640. $listCourseMainCoachSession = self::getCoursesForMainSessionCoach($userId);
  6641. // merge these 2 array
  6642. $listResCourseSession = $listCourseCourseCoachSession;
  6643. foreach ($listCourseMainCoachSession as $courseId2 => $listSessionId2) {
  6644. if (isset($listResCourseSession[$courseId2])) {
  6645. // if sessionId array exists for this course
  6646. // same courseId, merge the list of session
  6647. foreach ($listCourseMainCoachSession[$courseId2] as $i => $sessionId2) {
  6648. if (!in_array($sessionId2, $listResCourseSession[$courseId2])) {
  6649. $listResCourseSession[$courseId2][] = $sessionId2;
  6650. }
  6651. }
  6652. } else {
  6653. $listResCourseSession[$courseId2] = $listSessionId2;
  6654. }
  6655. }
  6656. return $listResCourseSession;
  6657. }
  6658. /**
  6659. * Return an associative array 'id_course' => [id_session1, id_session2...]
  6660. * where course id_course is in sessions id_session1, id_session2
  6661. * @param $userId
  6662. *
  6663. * @return array
  6664. */
  6665. public static function getCoursesForCourseSessionCoach($userId)
  6666. {
  6667. $listResCourseSession = array();
  6668. $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  6669. $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  6670. $sql = "SELECT session_id, c_id, c.id
  6671. FROM $tblSessionRelCourseRelUser srcru
  6672. LEFT JOIN $tblCourse c
  6673. ON c.id = srcru.c_id
  6674. WHERE
  6675. srcru.user_id =".intval($userId)." AND
  6676. srcru.status = 2";
  6677. $res = Database::query($sql);
  6678. while ($data = Database::fetch_assoc($res)) {
  6679. if (self::isSessionDateOkForCoach($data['session_id'])) {
  6680. if (!isset($listResCourseSession[$data['id']])) {
  6681. $listResCourseSession[$data['id']] = array();
  6682. }
  6683. $listResCourseSession[$data['id']][] = $data['session_id'];
  6684. }
  6685. }
  6686. return $listResCourseSession;
  6687. }
  6688. /**
  6689. * Return true if coach is allowed to access this session
  6690. * @param int $sessionId
  6691. * @return bool
  6692. */
  6693. public static function isSessionDateOkForCoach($sessionId)
  6694. {
  6695. return api_get_session_visibility($sessionId);
  6696. /*
  6697. $listSessionInfo = api_get_session_info($sessionId);
  6698. $dateStart = $listSessionInfo['date_start'];
  6699. $dateEnd = $listSessionInfo['date_end'];
  6700. $nbDaysAccessBeforeBeginning = $listSessionInfo['nb_days_access_before_beginning'];
  6701. $nbDaysAccessAfterEnd = $listSessionInfo['nb_days_access_after_end'];
  6702. // no start date
  6703. if ($dateStart == '0000-00-00') {
  6704. return true;
  6705. }
  6706. $now = time();
  6707. $dateStartForCoach = api_strtotime($dateStart.' 00:00:00') - ($nbDaysAccessBeforeBeginning * 86400);
  6708. $dateEndForCoach = api_strtotime($dateEnd.' 00:00:00') + ($nbDaysAccessAfterEnd * 86400);
  6709. if ($dateEnd == '0000-00-00') {
  6710. // start date but no end date
  6711. if ($dateStartForCoach <= $now) {
  6712. return true;
  6713. }
  6714. } else {
  6715. // start date and end date
  6716. if ($dateStartForCoach <= $now && $now <= $dateEndForCoach) {
  6717. return true;
  6718. }
  6719. }
  6720. return false;*/
  6721. }
  6722. /**
  6723. * Return an associative array 'id_course' => [id_session1, id_session2...]
  6724. * where course id_course is in sessions id_session1, id_session2
  6725. * @param $userId
  6726. *
  6727. * @return array
  6728. */
  6729. public static function getCoursesForMainSessionCoach($userId)
  6730. {
  6731. $listResCourseSession = array();
  6732. $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
  6733. // list of SESSION where user is session coach
  6734. $sql = "SELECT id FROM $tblSession
  6735. WHERE id_coach = ".intval($userId);
  6736. $res = Database::query($sql);
  6737. while ($data = Database::fetch_assoc($res)) {
  6738. $sessionId = $data['id'];
  6739. $listCoursesInSession = self::getCoursesInSession($sessionId);
  6740. foreach ($listCoursesInSession as $i => $courseId) {
  6741. if (self::isSessionDateOkForCoach($sessionId)) {
  6742. if (!isset($listResCourseSession[$courseId])) {
  6743. $listResCourseSession[$courseId] = array();
  6744. }
  6745. $listResCourseSession[$courseId][] = $sessionId;
  6746. }
  6747. }
  6748. }
  6749. return $listResCourseSession;
  6750. }
  6751. /**
  6752. * Return an array of course_id used in session $sessionId
  6753. * @param $sessionId
  6754. *
  6755. * @return array
  6756. */
  6757. public static function getCoursesInSession($sessionId)
  6758. {
  6759. $listResultsCourseId = array();
  6760. $tblSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  6761. $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  6762. // list of course in this session
  6763. $sql = "SELECT session_id, c.id
  6764. FROM $tblSessionRelCourse src
  6765. LEFT JOIN $tblCourse c
  6766. ON c.id = src.c_id
  6767. WHERE session_id = ".intval($sessionId);
  6768. $res = Database::query($sql);
  6769. while ($data = Database::fetch_assoc($res)) {
  6770. $listResultsCourseId[] = $data['id'];
  6771. }
  6772. return $listResultsCourseId;
  6773. }
  6774. /**
  6775. * Return an array of courses in session for user
  6776. * and for each courses the list of session that use this course for user
  6777. *
  6778. * [0] => array
  6779. * userCatId
  6780. * userCatTitle
  6781. * courseInUserCatList
  6782. * [0] => array
  6783. * courseId
  6784. * title
  6785. * courseCode
  6786. * sessionCatList
  6787. * [0] => array
  6788. * catSessionId
  6789. * catSessionName
  6790. * sessionList
  6791. * [0] => array
  6792. * sessionId
  6793. * sessionName
  6794. *
  6795. * @param $userId
  6796. *
  6797. * @return array
  6798. *
  6799. */
  6800. public static function getNamedSessionCourseForCoach($userId)
  6801. {
  6802. $listResults = array();
  6803. $listCourseSession = self::getSessionCourseForUser($userId);
  6804. foreach ($listCourseSession as $courseId => $listSessionId) {
  6805. // Course info
  6806. $courseInfo = api_get_course_info_by_id($courseId);
  6807. $listOneCourse = array();
  6808. $listOneCourse['courseId'] = $courseId;
  6809. $listOneCourse['title'] = $courseInfo['title'];
  6810. //$listOneCourse['courseCode'] = $courseInfo['code'];
  6811. $listOneCourse['course'] = $courseInfo;
  6812. $listOneCourse['sessionCatList'] = array();
  6813. $listCat = array();
  6814. foreach ($listSessionId as $i => $sessionId) {
  6815. // here we got all session for this course
  6816. // lets check there session categories
  6817. $sessionInfo = SessionManager::fetch($sessionId);
  6818. $catId = $sessionInfo['session_category_id'];
  6819. if (!isset($listCat[$catId])) {
  6820. $listCatInfo = self::get_session_category($catId);
  6821. $listCat[$catId] = array();
  6822. $listCat[$catId]['catSessionId'] = $catId;
  6823. $listCat[$catId]['catSessionName'] = $listCatInfo['name'];
  6824. $listCat[$catId]['sessionList'] = array();
  6825. }
  6826. $listSessionInfo = SessionManager::fetch($sessionId);
  6827. $listSessionIdName = array(
  6828. "sessionId" => $sessionId,
  6829. "sessionName" => $listSessionInfo['name'],
  6830. );
  6831. $listCat[$catId]['sessionList'][] = $listSessionIdName;
  6832. }
  6833. // sort $listCat by catSessionName
  6834. usort($listCat, 'self::compareBySessionName');
  6835. // in each catSession sort sessionList by sessionName
  6836. foreach($listCat as $i => $listCatSessionInfo) {
  6837. $listSessionList = $listCatSessionInfo['sessionList'];
  6838. usort($listSessionList, 'self::compareCatSessionInfo');
  6839. $listCat[$i]['sessionList'] = $listSessionList;
  6840. }
  6841. $listOneCourse['sessionCatList'] = $listCat;
  6842. // user course category
  6843. list($userCatId, $userCatTitle) = CourseManager::getUserCourseCategoryForCourse(
  6844. $userId,
  6845. $courseId
  6846. );
  6847. $userCatId = intval($userCatId);
  6848. $listResults[$userCatId]['courseInUserCategoryId'] = $userCatId;
  6849. $listResults[$userCatId]['courseInUserCategoryTitle'] = $userCatTitle;
  6850. $listResults[$userCatId]['courseInUserCatList'][] = $listOneCourse;
  6851. }
  6852. // sort by user course cat
  6853. uasort($listResults, 'self::compareByUserCourseCat');
  6854. // sort by course title
  6855. foreach ($listResults as $userCourseCatId => $tabCoursesInCat) {
  6856. $courseInUserCatList = $tabCoursesInCat['courseInUserCatList'];
  6857. uasort($courseInUserCatList, 'self::compareByCourse');
  6858. $listResults[$userCourseCatId]['courseInUserCatList'] = $courseInUserCatList;
  6859. }
  6860. return $listResults;
  6861. }
  6862. /**
  6863. * @param array $listA
  6864. * @param array $listB
  6865. * @return int
  6866. */
  6867. private static function compareCatSessionInfo($listA, $listB)
  6868. {
  6869. if ($listA['sessionName'] == $listB['sessionName']) {
  6870. return 0;
  6871. } else if($listA['sessionName'] > $listB['sessionName']) {
  6872. return 1;
  6873. } else {
  6874. return -1;
  6875. }
  6876. }
  6877. /**
  6878. * @param array $listA
  6879. * @param array $listB
  6880. * @return int
  6881. */
  6882. private static function compareBySessionName($listA, $listB)
  6883. {
  6884. if ($listB['catSessionName'] == '') {
  6885. return -1;
  6886. } else if ($listA['catSessionName'] == '') {
  6887. return 1;
  6888. } else if ($listA['catSessionName'] == $listB['catSessionName']) {
  6889. return 0;
  6890. } else if($listA['catSessionName'] > $listB['catSessionName']) {
  6891. return 1;
  6892. } else {
  6893. return -1;
  6894. }
  6895. }
  6896. /**
  6897. * @param array $listA
  6898. * @param array $listB
  6899. * @return int
  6900. */
  6901. private static function compareByUserCourseCat($listA, $listB)
  6902. {
  6903. if ($listA['courseInUserCategoryTitle'] == $listB['courseInUserCategoryTitle']) {
  6904. return 0;
  6905. } else if($listA['courseInUserCategoryTitle'] > $listB['courseInUserCategoryTitle']) {
  6906. return 1;
  6907. } else {
  6908. return -1;
  6909. }
  6910. }
  6911. /**
  6912. * @param array $listA
  6913. * @param array $listB
  6914. * @return int
  6915. */
  6916. private static function compareByCourse($listA, $listB)
  6917. {
  6918. if ($listA['title'] == $listB['title']) {
  6919. return 0;
  6920. } else if($listA['title'] > $listB['title']) {
  6921. return 1;
  6922. } else {
  6923. return -1;
  6924. }
  6925. }
  6926. /**
  6927. * Return HTML code for displaying session_course_for_coach
  6928. * @param $userId
  6929. * @return string
  6930. */
  6931. public static function getHtmlNamedSessionCourseForCoach($userId)
  6932. {
  6933. $htmlRes = '';
  6934. $listInfo = self::getNamedSessionCourseForCoach($userId);
  6935. foreach ($listInfo as $i => $listCoursesInfo) {
  6936. $courseInfo = $listCoursesInfo['course'];
  6937. $courseCode = $listCoursesInfo['course']['code'];
  6938. $listParamsCourse = array();
  6939. $listParamsCourse['icon'] = '<div style="float:left">
  6940. <input style="border:none;" type="button" onclick="$(\'#course-'.$courseCode.'\').toggle(\'fast\')" value="+" /></div>'.
  6941. Display::return_icon('blackboard.png', $courseInfo['title'], array(), ICON_SIZE_LARGE);
  6942. $listParamsCourse['link'] = '';
  6943. $listParamsCourse['title'] = Display::tag(
  6944. 'a',
  6945. $courseInfo['title'],
  6946. array('href' => $listParamsCourse['link'])
  6947. );
  6948. $htmlCourse = '<div class="well" style="border-color:#27587D">'.
  6949. CourseManager::course_item_html($listParamsCourse, true);
  6950. // for each category of session
  6951. $htmlCatSessions = '';
  6952. foreach ($listCoursesInfo['sessionCatList'] as $j => $listCatSessionsInfo) {
  6953. // we got an array of session categories
  6954. $catSessionId = $listCoursesInfo['sessionCatList'][$j]['catSessionId'];
  6955. $catSessionName = $listCoursesInfo['sessionCatList'][$j]['catSessionName'];
  6956. $listParamsCatSession['icon'] = Display::return_icon('folder_blue.png', $catSessionName, array(), ICON_SIZE_LARGE);
  6957. $listParamsCatSession['link'] = '';
  6958. $listParamsCatSession['title'] = $catSessionName;
  6959. $marginShift = 20;
  6960. if ($catSessionName != '') {
  6961. $htmlCatSessions .= '<div style="margin-left:'.$marginShift.'px;">' .
  6962. CourseManager::course_item_html($listParamsCatSession, true) . '</div>';
  6963. $marginShift = 40;
  6964. }
  6965. // for each sessions
  6966. $listCatSessionSessionList = $listCoursesInfo['sessionCatList'][$j]['sessionList'];
  6967. $htmlSession = '';
  6968. foreach ($listCatSessionSessionList as $k => $listSessionInfo) {
  6969. // we got an array of session info
  6970. $sessionId = $listSessionInfo['sessionId'];
  6971. $sessionName = $listSessionInfo['sessionName'];
  6972. $listParamsSession['icon'] = Display::return_icon('blackboard_blue.png', $sessionName, array(), ICON_SIZE_LARGE);
  6973. $listParamsSession['link'] = '';
  6974. $linkToCourseSession = $courseInfo['course_public_url'].'?id_session='.$sessionId;
  6975. $listParamsSession['title'] =
  6976. $sessionName.'<div style="font-weight:normal; font-style:italic">
  6977. <a href="'.$linkToCourseSession.'">'.get_lang('GoToCourseInsideSession').'</a>
  6978. </div>';
  6979. $htmlSession .= '<div style="margin-left:'.$marginShift.'px;">'.
  6980. CourseManager::course_item_html($listParamsSession, true).'</div>';
  6981. }
  6982. $htmlCatSessions .= $htmlSession;
  6983. }
  6984. $htmlRes .= $htmlCourse.'<div style="display:none" id="course-'.$courseCode.'">'.$htmlCatSessions.'</div></div>';
  6985. }
  6986. return $htmlRes;
  6987. }
  6988. }