sessionmanager.lib.php 342 KB

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