sessionmanager.lib.php 344 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274
  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 = (int) $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. $subscribe = (int) api_get_course_setting('subscribe_users_to_forum_notifications', $courseInfo);
  2023. $forums = [];
  2024. if ($subscribe === 1) {
  2025. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  2026. $forums = get_forums(0, $course_code, true, $session_id);
  2027. }
  2028. if ($removeUsersNotInList) {
  2029. $currentUsers = self::getUsersByCourseSession($session_id, $courseInfo, 0);
  2030. if (!empty($user_list)) {
  2031. $userToDelete = array_diff($currentUsers, $user_list);
  2032. } else {
  2033. $userToDelete = $currentUsers;
  2034. }
  2035. if (!empty($userToDelete)) {
  2036. self::removeUsersFromCourseSession(
  2037. $userToDelete,
  2038. $session_id,
  2039. $courseInfo,
  2040. 0,
  2041. true
  2042. );
  2043. }
  2044. }
  2045. $nbr_users = 0;
  2046. foreach ($user_list as $enreg_user) {
  2047. $enreg_user = (int) $enreg_user;
  2048. // Checking if user exists in session - course - user table.
  2049. $sql = "SELECT count(user_id) as count
  2050. FROM $tbl_session_rel_course_rel_user
  2051. WHERE
  2052. session_id = $session_id AND
  2053. c_id = $courseId and
  2054. user_id = $enreg_user ";
  2055. $result = Database::query($sql);
  2056. $count = 0;
  2057. if (Database::num_rows($result) > 0) {
  2058. $row = Database::fetch_array($result, 'ASSOC');
  2059. $count = $row['count'];
  2060. }
  2061. if ($count == 0) {
  2062. $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility)
  2063. VALUES ($session_id, $courseId, $enreg_user, $session_visibility)";
  2064. $result = Database::query($sql);
  2065. if (Database::affected_rows($result)) {
  2066. $nbr_users++;
  2067. }
  2068. }
  2069. if (!empty($forums)) {
  2070. $userInfo = api_get_user_info($enreg_user);
  2071. foreach ($forums as $forum) {
  2072. $forumId = $forum['iid'];
  2073. set_notification('forum', $forumId, false, $userInfo, $courseInfo);
  2074. }
  2075. }
  2076. // Checking if user exists in session - user table.
  2077. $sql = "SELECT count(user_id) as count
  2078. FROM $tbl_session_rel_user
  2079. WHERE session_id = $session_id AND user_id = $enreg_user ";
  2080. $result = Database::query($sql);
  2081. $count = 0;
  2082. if (Database::num_rows($result) > 0) {
  2083. $row = Database::fetch_array($result, 'ASSOC');
  2084. $count = $row['count'];
  2085. }
  2086. if (empty($count)) {
  2087. // If user is not registered to a session then add it.
  2088. $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, registered_at)
  2089. VALUES ($session_id, $enreg_user, '".api_get_utc_datetime()."')";
  2090. Database::query($sql);
  2091. $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + 1
  2092. WHERE id = $session_id ";
  2093. Database::query($sql);
  2094. }
  2095. }
  2096. // count users in this session-course relation
  2097. $sql = "SELECT COUNT(user_id) as nbUsers
  2098. FROM $tbl_session_rel_course_rel_user
  2099. WHERE session_id = $session_id AND c_id = $courseId AND status <> 2";
  2100. $rs = Database::query($sql);
  2101. list($nbr_users) = Database::fetch_array($rs);
  2102. // update the session-course relation to add the users total
  2103. $sql = "UPDATE $tbl_session_rel_course
  2104. SET nbr_users = $nbr_users
  2105. WHERE session_id = $session_id AND c_id = $courseId";
  2106. Database::query($sql);
  2107. }
  2108. /**
  2109. * Unsubscribe user from session.
  2110. *
  2111. * @param int Session id
  2112. * @param int User id
  2113. *
  2114. * @return bool True in case of success, false in case of error
  2115. */
  2116. public static function unsubscribe_user_from_session($session_id, $user_id)
  2117. {
  2118. $session_id = (int) $session_id;
  2119. $user_id = (int) $user_id;
  2120. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2121. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2122. $sql = "DELETE FROM $tbl_session_rel_user
  2123. WHERE
  2124. session_id = $session_id AND
  2125. user_id = $user_id AND
  2126. relation_type <> ".SESSION_RELATION_TYPE_RRHH;
  2127. $result = Database::query($sql);
  2128. $return = Database::affected_rows($result);
  2129. // Update number of users
  2130. $sql = "UPDATE $tbl_session
  2131. SET nbr_users = nbr_users - $return
  2132. WHERE id = $session_id ";
  2133. Database::query($sql);
  2134. Event::addEvent(
  2135. LOG_SESSION_DELETE_USER,
  2136. LOG_USER_ID,
  2137. $user_id,
  2138. api_get_utc_datetime(),
  2139. api_get_user_id(),
  2140. null,
  2141. $session_id
  2142. );
  2143. // Get the list of courses related to this session
  2144. $course_list = self::get_course_list_by_session_id($session_id);
  2145. if (!empty($course_list)) {
  2146. foreach ($course_list as $course) {
  2147. self::unSubscribeUserFromCourseSession($user_id, $course['id'], $session_id);
  2148. }
  2149. }
  2150. return true;
  2151. }
  2152. /**
  2153. * @param int $user_id
  2154. * @param int $courseId
  2155. * @param int $session_id
  2156. */
  2157. public static function unSubscribeUserFromCourseSession($user_id, $courseId, $session_id)
  2158. {
  2159. $user_id = (int) $user_id;
  2160. $courseId = (int) $courseId;
  2161. $session_id = (int) $session_id;
  2162. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2163. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2164. // Delete user from course
  2165. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  2166. WHERE session_id = $session_id AND c_id = $courseId AND user_id = $user_id";
  2167. $result = Database::query($sql);
  2168. if (Database::affected_rows($result)) {
  2169. // Update number of users in this relation
  2170. $sql = "UPDATE $tbl_session_rel_course SET
  2171. nbr_users = nbr_users - 1
  2172. WHERE session_id = $session_id AND c_id = $courseId";
  2173. Database::query($sql);
  2174. }
  2175. Event::addEvent(
  2176. LOG_SESSION_DELETE_USER_COURSE,
  2177. LOG_USER_ID,
  2178. $user_id,
  2179. api_get_utc_datetime(),
  2180. api_get_user_id(),
  2181. $courseId,
  2182. $session_id
  2183. );
  2184. }
  2185. /**
  2186. * Subscribes courses to the given session and optionally (default)
  2187. * unsubscribe previous users.
  2188. *
  2189. * @author Carlos Vargas from existing code
  2190. *
  2191. * @param int $sessionId
  2192. * @param array $courseList List of courses int ids
  2193. * @param bool $removeExistingCoursesWithUsers Whether to unsubscribe
  2194. * existing courses and users (true, default) or not (false)
  2195. * @param bool $copyEvaluation from base course to session course
  2196. * @param bool $copyCourseTeachersAsCoach
  2197. *
  2198. * @throws Exception
  2199. *
  2200. * @return bool False on failure, true otherwise
  2201. * */
  2202. public static function add_courses_to_session(
  2203. $sessionId,
  2204. $courseList,
  2205. $removeExistingCoursesWithUsers = true,
  2206. $copyEvaluation = false,
  2207. $copyCourseTeachersAsCoach = false
  2208. ) {
  2209. $sessionId = (int) $sessionId;
  2210. if (empty($sessionId) || empty($courseList)) {
  2211. return false;
  2212. }
  2213. $em = Database::getManager();
  2214. /** @var Session $session */
  2215. $session = $em->find('ChamiloCoreBundle:Session', $sessionId);
  2216. if (!$session) {
  2217. return false;
  2218. }
  2219. $sessionVisibility = $session->getVisibility();
  2220. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2221. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2222. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2223. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2224. // Get list of courses subscribed to this session
  2225. $sql = "SELECT c_id
  2226. FROM $tbl_session_rel_course
  2227. WHERE session_id = $sessionId";
  2228. $rs = Database::query($sql);
  2229. $existingCourses = Database::store_result($rs);
  2230. $nbr_courses = count($existingCourses);
  2231. // Get list of users subscribed to this session
  2232. $sql = "SELECT user_id
  2233. FROM $tbl_session_rel_user
  2234. WHERE
  2235. session_id = $sessionId AND
  2236. relation_type<>".SESSION_RELATION_TYPE_RRHH;
  2237. $result = Database::query($sql);
  2238. $user_list = Database::store_result($result);
  2239. // Remove existing courses from the session.
  2240. if ($removeExistingCoursesWithUsers === true && !empty($existingCourses)) {
  2241. foreach ($existingCourses as $existingCourse) {
  2242. if (!in_array($existingCourse['c_id'], $courseList)) {
  2243. $sql = "DELETE FROM $tbl_session_rel_course
  2244. WHERE
  2245. c_id = ".$existingCourse['c_id']." AND
  2246. session_id = $sessionId";
  2247. Database::query($sql);
  2248. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  2249. WHERE
  2250. c_id = ".$existingCourse['c_id']." AND
  2251. session_id = $sessionId";
  2252. Database::query($sql);
  2253. Event::addEvent(
  2254. LOG_SESSION_DELETE_COURSE,
  2255. LOG_COURSE_ID,
  2256. $existingCourse['c_id'],
  2257. api_get_utc_datetime(),
  2258. api_get_user_id(),
  2259. $existingCourse['c_id'],
  2260. $sessionId
  2261. );
  2262. CourseManager::remove_course_ranking(
  2263. $existingCourse['c_id'],
  2264. $sessionId
  2265. );
  2266. $nbr_courses--;
  2267. }
  2268. }
  2269. }
  2270. // Pass through the courses list we want to add to the session
  2271. foreach ($courseList as $courseId) {
  2272. $courseInfo = api_get_course_info_by_id($courseId);
  2273. // If course doesn't exists continue!
  2274. if (empty($courseInfo)) {
  2275. continue;
  2276. }
  2277. $exists = false;
  2278. // check if the course we want to add is already subscribed
  2279. foreach ($existingCourses as $existingCourse) {
  2280. if ($courseId == $existingCourse['c_id']) {
  2281. $exists = true;
  2282. }
  2283. }
  2284. if (!$exists) {
  2285. // Copy gradebook categories and links (from base course)
  2286. // to the new course session
  2287. if ($copyEvaluation) {
  2288. $cats = Category::load(null, null, $courseInfo['code']);
  2289. if (!empty($cats)) {
  2290. $sessionCategory = Category:: load(
  2291. null,
  2292. null,
  2293. $courseInfo['code'],
  2294. null,
  2295. null,
  2296. $sessionId,
  2297. false
  2298. );
  2299. // @todo remove commented code
  2300. if (empty($sessionCategory)) {
  2301. // There is no category for this course+session, so create one
  2302. $cat = new Category();
  2303. $sessionName = $session->getName();
  2304. $cat->set_name($courseInfo['code'].' - '.get_lang('Session').' '.$sessionName);
  2305. $cat->set_session_id($sessionId);
  2306. $cat->set_course_code($courseInfo['code']);
  2307. $cat->set_description(null);
  2308. //$cat->set_user_id($stud_id);
  2309. $cat->set_parent_id(0);
  2310. $cat->set_weight(100);
  2311. $cat->set_visible(0);
  2312. $cat->set_certificate_min_score(75);
  2313. $cat->add();
  2314. $sessionGradeBookCategoryId = $cat->get_id();
  2315. } else {
  2316. if (!empty($sessionCategory[0])) {
  2317. $sessionGradeBookCategoryId = $sessionCategory[0]->get_id();
  2318. }
  2319. }
  2320. $categoryIdList = [];
  2321. /** @var Category $cat */
  2322. foreach ($cats as $cat) {
  2323. $categoryIdList[$cat->get_id()] = $cat->get_id();
  2324. }
  2325. $newCategoryIdList = [];
  2326. foreach ($cats as $cat) {
  2327. $links = $cat->get_links(
  2328. null,
  2329. false,
  2330. $courseInfo['code'],
  2331. 0
  2332. );
  2333. //$cat->set_session_id($sessionId);
  2334. //$oldCategoryId = $cat->get_id();
  2335. //$newId = $cat->add();
  2336. //$newCategoryIdList[$oldCategoryId] = $newId;
  2337. //$parentId = $cat->get_parent_id();
  2338. /*if (!empty($parentId)) {
  2339. $newParentId = $newCategoryIdList[$parentId];
  2340. $cat->set_parent_id($newParentId);
  2341. $cat->save();
  2342. }*/
  2343. if (!empty($links)) {
  2344. /** @var AbstractLink $link */
  2345. foreach ($links as $link) {
  2346. //$newCategoryId = $newCategoryIdList[$link->get_category_id()];
  2347. $link->set_category_id($sessionGradeBookCategoryId);
  2348. $link->add();
  2349. }
  2350. }
  2351. $evaluationList = $cat->get_evaluations(
  2352. null,
  2353. false,
  2354. $courseInfo['code'],
  2355. 0
  2356. );
  2357. if (!empty($evaluationList)) {
  2358. /** @var Evaluation $evaluation */
  2359. foreach ($evaluationList as $evaluation) {
  2360. //$evaluationId = $newCategoryIdList[$evaluation->get_category_id()];
  2361. $evaluation->set_category_id($sessionGradeBookCategoryId);
  2362. $evaluation->add();
  2363. }
  2364. }
  2365. }
  2366. // Create
  2367. DocumentManager::generateDefaultCertificate(
  2368. $courseInfo,
  2369. true,
  2370. $sessionId
  2371. );
  2372. }
  2373. }
  2374. // If the course isn't subscribed yet
  2375. $sql = "INSERT INTO $tbl_session_rel_course (session_id, c_id, nbr_users, position)
  2376. VALUES ($sessionId, $courseId, 0, 0)";
  2377. Database::query($sql);
  2378. Event::addEvent(
  2379. LOG_SESSION_ADD_COURSE,
  2380. LOG_COURSE_ID,
  2381. $courseId,
  2382. api_get_utc_datetime(),
  2383. api_get_user_id(),
  2384. $courseId,
  2385. $sessionId
  2386. );
  2387. // We add the current course in the existing courses array,
  2388. // to avoid adding another time the current course
  2389. $existingCourses[] = ['c_id' => $courseId];
  2390. $nbr_courses++;
  2391. // Subscribe all the users from the session to this course inside the session
  2392. $nbr_users = 0;
  2393. foreach ($user_list as $enreg_user) {
  2394. $enreg_user_id = (int) $enreg_user['user_id'];
  2395. $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility)
  2396. VALUES ($sessionId, $courseId, $enreg_user_id, $sessionVisibility)";
  2397. $result = Database::query($sql);
  2398. Event::addEvent(
  2399. LOG_SESSION_ADD_USER_COURSE,
  2400. LOG_USER_ID,
  2401. $enreg_user_id,
  2402. api_get_utc_datetime(),
  2403. api_get_user_id(),
  2404. $courseId,
  2405. $sessionId
  2406. );
  2407. if (Database::affected_rows($result)) {
  2408. $nbr_users++;
  2409. }
  2410. }
  2411. $sql = "UPDATE $tbl_session_rel_course
  2412. SET nbr_users = $nbr_users
  2413. WHERE session_id = $sessionId AND c_id = $courseId";
  2414. Database::query($sql);
  2415. }
  2416. if ($copyCourseTeachersAsCoach) {
  2417. $teachers = CourseManager::get_teacher_list_from_course_code($courseInfo['code']);
  2418. if (!empty($teachers)) {
  2419. foreach ($teachers as $teacher) {
  2420. self::updateCoaches(
  2421. $sessionId,
  2422. $courseId,
  2423. [$teacher['user_id']],
  2424. false
  2425. );
  2426. }
  2427. }
  2428. }
  2429. }
  2430. $sql = "UPDATE $tbl_session SET nbr_courses = $nbr_courses WHERE id = $sessionId";
  2431. Database::query($sql);
  2432. return true;
  2433. }
  2434. /**
  2435. * Unsubscribe course from a session.
  2436. *
  2437. * @param int $session_id
  2438. * @param int $course_id
  2439. *
  2440. * @return bool True in case of success, false otherwise
  2441. */
  2442. public static function unsubscribe_course_from_session($session_id, $course_id)
  2443. {
  2444. $session_id = (int) $session_id;
  2445. $course_id = (int) $course_id;
  2446. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2447. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2448. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2449. // Get course code
  2450. $course_code = CourseManager::get_course_code_from_course_id($course_id);
  2451. if (empty($course_code)) {
  2452. return false;
  2453. }
  2454. // Unsubscribe course
  2455. $sql = "DELETE FROM $tbl_session_rel_course
  2456. WHERE c_id = $course_id AND session_id = $session_id";
  2457. $result = Database::query($sql);
  2458. $nb_affected = Database::affected_rows($result);
  2459. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  2460. WHERE c_id = $course_id AND session_id = $session_id";
  2461. Database::query($sql);
  2462. Event::addEvent(
  2463. LOG_SESSION_DELETE_COURSE,
  2464. LOG_COURSE_ID,
  2465. $course_id,
  2466. api_get_utc_datetime(),
  2467. api_get_user_id(),
  2468. $course_id,
  2469. $session_id
  2470. );
  2471. if ($nb_affected > 0) {
  2472. // Update number of courses in the session
  2473. $sql = "UPDATE $tbl_session SET nbr_courses= nbr_courses - $nb_affected
  2474. WHERE id = $session_id";
  2475. Database::query($sql);
  2476. return true;
  2477. }
  2478. return false;
  2479. }
  2480. /**
  2481. * Creates a new extra field for a given session.
  2482. *
  2483. * @param string $variable Field's internal variable name
  2484. * @param int $fieldType Field's type
  2485. * @param string $displayText Field's language var name
  2486. * @param string $default Field's default value
  2487. *
  2488. * @return int new extra field id
  2489. */
  2490. public static function create_session_extra_field(
  2491. $variable,
  2492. $fieldType,
  2493. $displayText,
  2494. $default = ''
  2495. ) {
  2496. $extraField = new ExtraFieldModel('session');
  2497. $params = [
  2498. 'variable' => $variable,
  2499. 'field_type' => $fieldType,
  2500. 'display_text' => $displayText,
  2501. 'default_value' => $default,
  2502. ];
  2503. return $extraField->save($params);
  2504. }
  2505. /**
  2506. * Update an extra field value for a given session.
  2507. *
  2508. * @param int $sessionId Session ID
  2509. * @param string $variable Field variable name
  2510. * @param string $value Optional. Default field value
  2511. *
  2512. * @return bool|int An integer when register a new extra field. And boolean when update the extrafield
  2513. */
  2514. public static function update_session_extra_field_value($sessionId, $variable, $value = '')
  2515. {
  2516. $extraFieldValue = new ExtraFieldValue('session');
  2517. $params = [
  2518. 'item_id' => $sessionId,
  2519. 'variable' => $variable,
  2520. 'value' => $value,
  2521. ];
  2522. return $extraFieldValue->save($params);
  2523. }
  2524. /**
  2525. * Checks the relationship between a session and a course.
  2526. *
  2527. * @param int $session_id
  2528. * @param int $courseId
  2529. *
  2530. * @return bool returns TRUE if the session and the course are related, FALSE otherwise
  2531. * */
  2532. public static function relation_session_course_exist($session_id, $courseId)
  2533. {
  2534. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2535. $return_value = false;
  2536. $sql = "SELECT c_id FROM $tbl_session_course
  2537. WHERE
  2538. session_id = ".intval($session_id)." AND
  2539. c_id = ".intval($courseId);
  2540. $result = Database::query($sql);
  2541. $num = Database::num_rows($result);
  2542. if ($num > 0) {
  2543. $return_value = true;
  2544. }
  2545. return $return_value;
  2546. }
  2547. /**
  2548. * Get the session information by name.
  2549. *
  2550. * @param string $name
  2551. *
  2552. * @return mixed false if the session does not exist, array if the session exist
  2553. */
  2554. public static function get_session_by_name($name)
  2555. {
  2556. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2557. $name = Database::escape_string(trim($name));
  2558. if (empty($name)) {
  2559. return false;
  2560. }
  2561. $sql = 'SELECT *
  2562. FROM '.$tbl_session.'
  2563. WHERE name = "'.$name.'"';
  2564. $result = Database::query($sql);
  2565. $num = Database::num_rows($result);
  2566. if ($num > 0) {
  2567. return Database::fetch_array($result);
  2568. } else {
  2569. return false;
  2570. }
  2571. }
  2572. /**
  2573. * @param int $sessionId
  2574. * @param int $name
  2575. *
  2576. * @return bool
  2577. */
  2578. public static function sessionNameExistBesidesMySession($sessionId, $name)
  2579. {
  2580. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  2581. $name = Database::escape_string(trim($name));
  2582. $sessionId = (int) $sessionId;
  2583. if (empty($name)) {
  2584. return false;
  2585. }
  2586. $sql = "SELECT *
  2587. FROM $table
  2588. WHERE name = '$name' AND id <> $sessionId ";
  2589. $result = Database::query($sql);
  2590. $num = Database::num_rows($result);
  2591. if ($num > 0) {
  2592. return true;
  2593. }
  2594. return false;
  2595. }
  2596. /**
  2597. * Create a session category.
  2598. *
  2599. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
  2600. *
  2601. * @param string name
  2602. * @param int year_start
  2603. * @param int month_start
  2604. * @param int day_start
  2605. * @param int year_end
  2606. * @param int month_end
  2607. * @param int day_end
  2608. *
  2609. * @return int session ID
  2610. * */
  2611. public static function create_category_session(
  2612. $sname,
  2613. $syear_start,
  2614. $smonth_start,
  2615. $sday_start,
  2616. $syear_end,
  2617. $smonth_end,
  2618. $sday_end
  2619. ) {
  2620. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2621. $name = trim($sname);
  2622. $year_start = intval($syear_start);
  2623. $month_start = intval($smonth_start);
  2624. $day_start = intval($sday_start);
  2625. $year_end = intval($syear_end);
  2626. $month_end = intval($smonth_end);
  2627. $day_end = intval($sday_end);
  2628. $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start);
  2629. $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end);
  2630. if (empty($name)) {
  2631. $msg = get_lang('SessionCategoryNameIsRequired');
  2632. return $msg;
  2633. } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
  2634. $msg = get_lang('InvalidStartDate');
  2635. return $msg;
  2636. } elseif (!$month_end && !$day_end && !$year_end) {
  2637. $date_end = '';
  2638. } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
  2639. $msg = get_lang('InvalidEndDate');
  2640. return $msg;
  2641. } elseif ($date_start >= $date_end) {
  2642. $msg = get_lang('StartDateShouldBeBeforeEndDate');
  2643. return $msg;
  2644. }
  2645. $access_url_id = api_get_current_access_url_id();
  2646. $params = [
  2647. 'name' => $name,
  2648. 'date_start' => $date_start,
  2649. 'access_url_id' => $access_url_id,
  2650. ];
  2651. if (!empty($date_end)) {
  2652. $params['date_end'] = $date_end;
  2653. }
  2654. $id = Database::insert($tbl_session_category, $params);
  2655. // Add event to system log
  2656. $user_id = api_get_user_id();
  2657. Event::addEvent(
  2658. LOG_SESSION_CATEGORY_CREATE,
  2659. LOG_SESSION_CATEGORY_ID,
  2660. $id,
  2661. api_get_utc_datetime(),
  2662. $user_id
  2663. );
  2664. return $id;
  2665. }
  2666. /**
  2667. * Edit a sessions category.
  2668. *
  2669. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,from existing code
  2670. *
  2671. * @param int id
  2672. * @param string name
  2673. * @param int year_start
  2674. * @param int month_start
  2675. * @param int day_start
  2676. * @param int year_end
  2677. * @param int month_end
  2678. * @param int day_end
  2679. *
  2680. * @return bool
  2681. * The parameter id is a primary key
  2682. * */
  2683. public static function edit_category_session(
  2684. $id,
  2685. $sname,
  2686. $syear_start,
  2687. $smonth_start,
  2688. $sday_start,
  2689. $syear_end,
  2690. $smonth_end,
  2691. $sday_end
  2692. ) {
  2693. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2694. $name = trim($sname);
  2695. $year_start = intval($syear_start);
  2696. $month_start = intval($smonth_start);
  2697. $day_start = intval($sday_start);
  2698. $year_end = intval($syear_end);
  2699. $month_end = intval($smonth_end);
  2700. $day_end = intval($sday_end);
  2701. $id = intval($id);
  2702. $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start);
  2703. $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end);
  2704. if (empty($name)) {
  2705. $msg = get_lang('SessionCategoryNameIsRequired');
  2706. return $msg;
  2707. } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
  2708. $msg = get_lang('InvalidStartDate');
  2709. return $msg;
  2710. } elseif (!$month_end && !$day_end && !$year_end) {
  2711. $date_end = null;
  2712. } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
  2713. $msg = get_lang('InvalidEndDate');
  2714. return $msg;
  2715. } elseif ($date_start >= $date_end) {
  2716. $msg = get_lang('StartDateShouldBeBeforeEndDate');
  2717. return $msg;
  2718. }
  2719. if ($date_end != null) {
  2720. $sql = "UPDATE $tbl_session_category
  2721. SET
  2722. name = '".Database::escape_string($name)."',
  2723. date_start = '$date_start' ,
  2724. date_end = '$date_end'
  2725. WHERE id= $id";
  2726. } else {
  2727. $sql = "UPDATE $tbl_session_category SET
  2728. name = '".Database::escape_string($name)."',
  2729. date_start = '$date_start',
  2730. date_end = NULL
  2731. WHERE id= $id";
  2732. }
  2733. $result = Database::query($sql);
  2734. return $result ? true : false;
  2735. }
  2736. /**
  2737. * Delete sessions categories.
  2738. *
  2739. * @param array|int $categoryId
  2740. * @param bool $deleteSessions Optional. Include delete session.
  2741. * @param bool $fromWs Optional. True if the function is called by a webservice, false otherwise.
  2742. *
  2743. * @return bool Nothing, or false on error
  2744. * The parameters is a array to delete sessions
  2745. *
  2746. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
  2747. */
  2748. public static function delete_session_category($categoryId, $deleteSessions = false, $fromWs = false)
  2749. {
  2750. $tblSessionCategory = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2751. $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
  2752. if (is_array($categoryId)) {
  2753. $categoryId = array_map('intval', $categoryId);
  2754. } else {
  2755. $categoryId = [(int) $categoryId];
  2756. }
  2757. $categoryId = implode(', ', $categoryId);
  2758. if ($deleteSessions) {
  2759. $sql = "SELECT id FROM $tblSession WHERE session_category_id IN ($categoryId)";
  2760. $result = Database::query($sql);
  2761. while ($rows = Database::fetch_array($result)) {
  2762. $sessionId = $rows['id'];
  2763. self::delete($sessionId, $fromWs);
  2764. }
  2765. } else {
  2766. $sql = "UPDATE $tblSession SET session_category_id = NULL WHERE session_category_id IN ($categoryId)";
  2767. Database::query($sql);
  2768. }
  2769. $sql = "DELETE FROM $tblSessionCategory WHERE id IN ($categoryId)";
  2770. Database::query($sql);
  2771. // Add event to system log
  2772. Event::addEvent(
  2773. LOG_SESSION_CATEGORY_DELETE,
  2774. LOG_SESSION_CATEGORY_ID,
  2775. $categoryId,
  2776. api_get_utc_datetime(),
  2777. api_get_user_id()
  2778. );
  2779. return true;
  2780. }
  2781. /**
  2782. * Get a list of sessions of which the given conditions match with an = 'cond'.
  2783. *
  2784. * @param array $conditions a list of condition example :
  2785. * array('status' => STUDENT) or
  2786. * array('s.name' => array('operator' => 'LIKE', value = '%$needle%'))
  2787. * @param array $order_by a list of fields on which sort
  2788. * @param int $urlId
  2789. * @param array $onlyThisSessionList
  2790. *
  2791. * @return array an array with all sessions of the platform
  2792. *
  2793. * @todo optional course code parameter, optional sorting parameters...
  2794. */
  2795. public static function get_sessions_list(
  2796. $conditions = [],
  2797. $order_by = [],
  2798. $from = null,
  2799. $to = null,
  2800. $urlId = 0,
  2801. $onlyThisSessionList = []
  2802. ) {
  2803. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  2804. $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2805. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  2806. $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2807. $session_course_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2808. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  2809. $urlId = empty($urlId) ? api_get_current_access_url_id() : (int) $urlId;
  2810. $return_array = [];
  2811. $sql_query = " SELECT
  2812. DISTINCT(s.id),
  2813. s.name,
  2814. s.nbr_courses,
  2815. s.access_start_date,
  2816. s.access_end_date,
  2817. u.firstname,
  2818. u.lastname,
  2819. sc.name as category_name,
  2820. s.promotion_id
  2821. FROM $session_table s
  2822. INNER JOIN $user_table u ON s.id_coach = u.user_id
  2823. INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
  2824. LEFT JOIN $session_category_table sc ON s.session_category_id = sc.id
  2825. LEFT JOIN $session_course_table sco ON (sco.session_id = s.id)
  2826. INNER JOIN $course_table c ON sco.c_id = c.id
  2827. WHERE ar.access_url_id = $urlId ";
  2828. $availableFields = [
  2829. 's.id',
  2830. 's.name',
  2831. 'c.id',
  2832. ];
  2833. $availableOperator = [
  2834. 'like',
  2835. '>=',
  2836. '<=',
  2837. '=',
  2838. ];
  2839. if (count($conditions) > 0) {
  2840. foreach ($conditions as $field => $options) {
  2841. $operator = strtolower($options['operator']);
  2842. $value = Database::escape_string($options['value']);
  2843. $sql_query .= ' AND ';
  2844. if (in_array($field, $availableFields) && in_array($operator, $availableOperator)) {
  2845. $sql_query .= $field." $operator '".$value."'";
  2846. }
  2847. }
  2848. }
  2849. if (!empty($onlyThisSessionList)) {
  2850. $onlyThisSessionList = array_map('intval', $onlyThisSessionList);
  2851. $onlyThisSessionList = implode("','", $onlyThisSessionList);
  2852. $sql_query .= " AND s.id IN ('$onlyThisSessionList') ";
  2853. }
  2854. $orderAvailableList = ['name'];
  2855. if (count($order_by) > 0) {
  2856. $order = null;
  2857. $direction = null;
  2858. if (isset($order_by[0]) && in_array($order_by[0], $orderAvailableList)) {
  2859. $order = $order_by[0];
  2860. }
  2861. if (isset($order_by[1]) && in_array(strtolower($order_by[1]), ['desc', 'asc'])) {
  2862. $direction = $order_by[1];
  2863. }
  2864. if (!empty($order)) {
  2865. $sql_query .= " ORDER BY $order $direction ";
  2866. }
  2867. }
  2868. if (!is_null($from) && !is_null($to)) {
  2869. $to = (int) $to;
  2870. $from = (int) $from;
  2871. $sql_query .= "LIMIT $from, $to";
  2872. }
  2873. $sql_result = Database::query($sql_query);
  2874. if (Database::num_rows($sql_result) > 0) {
  2875. while ($result = Database::fetch_array($sql_result)) {
  2876. $return_array[$result['id']] = $result;
  2877. }
  2878. }
  2879. return $return_array;
  2880. }
  2881. /**
  2882. * Get the session category information by id.
  2883. *
  2884. * @param string session category ID
  2885. *
  2886. * @return mixed false if the session category does not exist, array if the session category exists
  2887. */
  2888. public static function get_session_category($id)
  2889. {
  2890. $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2891. $id = (int) $id;
  2892. $sql = "SELECT id, name, date_start, date_end
  2893. FROM $table
  2894. WHERE id= $id";
  2895. $result = Database::query($sql);
  2896. $num = Database::num_rows($result);
  2897. if ($num > 0) {
  2898. return Database::fetch_array($result);
  2899. } else {
  2900. return false;
  2901. }
  2902. }
  2903. /**
  2904. * Get Hot Sessions (limit 8).
  2905. *
  2906. * @return array with sessions
  2907. */
  2908. public static function getHotSessions()
  2909. {
  2910. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2911. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2912. $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
  2913. $tbl_extra_fields = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2914. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2915. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2916. $extraField = new ExtraFieldModel('session');
  2917. $field = $extraField->get_handler_field_info_by_field_variable('image');
  2918. $sql = "SELECT
  2919. s.id,
  2920. s.name,
  2921. s.id_coach,
  2922. u.firstname,
  2923. u.lastname,
  2924. s.session_category_id,
  2925. c.name as category_name,
  2926. s.description,
  2927. (SELECT COUNT(*) FROM $tbl_session_user WHERE session_id = s.id) as users,
  2928. (SELECT COUNT(*) FROM $tbl_lp WHERE session_id = s.id) as lessons ";
  2929. if ($field !== false) {
  2930. $fieldId = $field['id'];
  2931. $sql .= ",(SELECT value FROM $tbl_extra_fields WHERE field_id = $fieldId AND item_id = s.id) as image ";
  2932. }
  2933. $sql .= " FROM $tbl_session s
  2934. LEFT JOIN $tbl_session_category c
  2935. ON s.session_category_id = c.id
  2936. INNER JOIN $tbl_users u
  2937. ON s.id_coach = u.id
  2938. ORDER BY 9 DESC
  2939. LIMIT 8";
  2940. $result = Database::query($sql);
  2941. if (Database::num_rows($result) > 0) {
  2942. $plugin = BuyCoursesPlugin::create();
  2943. $checker = $plugin->isEnabled();
  2944. $sessions = [];
  2945. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2946. if (!isset($row['image'])) {
  2947. $row['image'] = '';
  2948. }
  2949. $row['on_sale'] = '';
  2950. if ($checker) {
  2951. $row['on_sale'] = $plugin->getItemByProduct(
  2952. $row['id'],
  2953. BuyCoursesPlugin::PRODUCT_TYPE_SESSION
  2954. );
  2955. }
  2956. $sessions[] = $row;
  2957. }
  2958. return $sessions;
  2959. }
  2960. return false;
  2961. }
  2962. /**
  2963. * Get all session categories (filter by access_url_id).
  2964. *
  2965. * @return mixed false if the session category does not exist, array if the session category exists
  2966. */
  2967. public static function get_all_session_category()
  2968. {
  2969. $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2970. $id = api_get_current_access_url_id();
  2971. $sql = 'SELECT * FROM '.$table.'
  2972. WHERE access_url_id = '.$id.'
  2973. ORDER BY name ASC';
  2974. $result = Database::query($sql);
  2975. if (Database::num_rows($result) > 0) {
  2976. $data = Database::store_result($result, 'ASSOC');
  2977. return $data;
  2978. }
  2979. return false;
  2980. }
  2981. /**
  2982. * Assign a coach to course in session with status = 2.
  2983. *
  2984. * @param int $userId
  2985. * @param int $sessionId
  2986. * @param int $courseId
  2987. * @param bool $noCoach optional, if is true the user don't be a coach now,
  2988. * otherwise it'll assign a coach
  2989. *
  2990. * @return bool true if there are affected rows, otherwise false
  2991. */
  2992. public static function set_coach_to_course_session(
  2993. $userId,
  2994. $sessionId = 0,
  2995. $courseId = 0,
  2996. $noCoach = false
  2997. ) {
  2998. // Definition of variables
  2999. $userId = (int) $userId;
  3000. $sessionId = !empty($sessionId) ? (int) $sessionId : api_get_session_id();
  3001. $courseId = !empty($courseId) ? (int) $courseId : api_get_course_id();
  3002. if (empty($sessionId) || empty($courseId) || empty($userId)) {
  3003. return false;
  3004. }
  3005. // Table definition
  3006. $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3007. $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3008. $tblUser = Database::get_main_table(TABLE_MAIN_USER);
  3009. // check if user is a teacher
  3010. $sql = "SELECT * FROM $tblUser
  3011. WHERE status = 1 AND user_id = $userId";
  3012. $rsCheckUser = Database::query($sql);
  3013. if (Database::num_rows($rsCheckUser) <= 0) {
  3014. return false;
  3015. }
  3016. if ($noCoach) {
  3017. // check if user_id exists in session_rel_user (if the user is
  3018. // subscribed to the session in any manner)
  3019. $sql = "SELECT user_id FROM $tblSessionRelUser
  3020. WHERE
  3021. session_id = $sessionId AND
  3022. user_id = $userId";
  3023. $res = Database::query($sql);
  3024. if (Database::num_rows($res) > 0) {
  3025. // The user is already subscribed to the session. Change the
  3026. // record so the user is NOT a coach for this course anymore
  3027. // and then exit
  3028. $sql = "UPDATE $tblSessionRelCourseRelUser
  3029. SET status = 0
  3030. WHERE
  3031. session_id = $sessionId AND
  3032. c_id = $courseId AND
  3033. user_id = $userId ";
  3034. $result = Database::query($sql);
  3035. return Database::affected_rows($result) > 0;
  3036. }
  3037. // The user is not subscribed to the session, so make sure
  3038. // he isn't subscribed to a course in this session either
  3039. // and then exit
  3040. $sql = "DELETE FROM $tblSessionRelCourseRelUser
  3041. WHERE
  3042. session_id = $sessionId AND
  3043. c_id = $courseId AND
  3044. user_id = $userId ";
  3045. $result = Database::query($sql);
  3046. return Database::affected_rows($result) > 0;
  3047. }
  3048. // Assign user as a coach to course
  3049. // First check if the user is registered to the course
  3050. $sql = "SELECT user_id FROM $tblSessionRelCourseRelUser
  3051. WHERE
  3052. session_id = $sessionId AND
  3053. c_id = $courseId AND
  3054. user_id = $userId";
  3055. $rs_check = Database::query($sql);
  3056. // Then update or insert.
  3057. if (Database::num_rows($rs_check) > 0) {
  3058. $sql = "UPDATE $tblSessionRelCourseRelUser SET status = 2
  3059. WHERE
  3060. session_id = $sessionId AND
  3061. c_id = $courseId AND
  3062. user_id = $userId ";
  3063. $result = Database::query($sql);
  3064. return Database::affected_rows($result) > 0;
  3065. }
  3066. $sql = "INSERT INTO $tblSessionRelCourseRelUser(session_id, c_id, user_id, status)
  3067. VALUES($sessionId, $courseId, $userId, 2)";
  3068. $result = Database::query($sql);
  3069. return Database::affected_rows($result) > 0;
  3070. }
  3071. /**
  3072. * @param int $sessionId
  3073. *
  3074. * @return bool
  3075. */
  3076. public static function removeAllDrhFromSession($sessionId)
  3077. {
  3078. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3079. $sessionId = (int) $sessionId;
  3080. if (empty($sessionId)) {
  3081. return false;
  3082. }
  3083. $sql = "DELETE FROM $tbl_session_rel_user
  3084. WHERE
  3085. session_id = $sessionId AND
  3086. relation_type =".SESSION_RELATION_TYPE_RRHH;
  3087. Database::query($sql);
  3088. return true;
  3089. }
  3090. /**
  3091. * Subscribes sessions to human resource manager (Dashboard feature).
  3092. *
  3093. * @param array $userInfo Human Resource Manager info
  3094. * @param array $sessions_list Sessions id
  3095. * @param bool $sendEmail
  3096. * @param bool $removeSessionsFromUser
  3097. *
  3098. * @return int
  3099. * */
  3100. public static function subscribeSessionsToDrh(
  3101. $userInfo,
  3102. $sessions_list,
  3103. $sendEmail = false,
  3104. $removeSessionsFromUser = true
  3105. ) {
  3106. // Database Table Definitions
  3107. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3108. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3109. if (empty($userInfo)) {
  3110. return 0;
  3111. }
  3112. $userId = $userInfo['user_id'];
  3113. // Only subscribe DRH users.
  3114. $rolesAllowed = [
  3115. DRH,
  3116. SESSIONADMIN,
  3117. PLATFORM_ADMIN,
  3118. COURSE_TUTOR,
  3119. ];
  3120. $isAdmin = api_is_platform_admin_by_id($userInfo['user_id']);
  3121. if (!$isAdmin && !in_array($userInfo['status'], $rolesAllowed)) {
  3122. return 0;
  3123. }
  3124. $affected_rows = 0;
  3125. // Deleting assigned sessions to hrm_id.
  3126. if ($removeSessionsFromUser) {
  3127. if (api_is_multiple_url_enabled()) {
  3128. $sql = "SELECT s.session_id
  3129. FROM $tbl_session_rel_user s
  3130. INNER JOIN $tbl_session_rel_access_url a
  3131. ON (a.session_id = s.session_id)
  3132. WHERE
  3133. s.user_id = $userId AND
  3134. relation_type = ".SESSION_RELATION_TYPE_RRHH." AND
  3135. access_url_id = ".api_get_current_access_url_id();
  3136. } else {
  3137. $sql = "SELECT s.session_id
  3138. FROM $tbl_session_rel_user s
  3139. WHERE user_id = $userId AND relation_type=".SESSION_RELATION_TYPE_RRHH;
  3140. }
  3141. $result = Database::query($sql);
  3142. if (Database::num_rows($result) > 0) {
  3143. while ($row = Database::fetch_array($result)) {
  3144. $sql = "DELETE FROM $tbl_session_rel_user
  3145. WHERE
  3146. session_id = {$row['session_id']} AND
  3147. user_id = $userId AND
  3148. relation_type =".SESSION_RELATION_TYPE_RRHH;
  3149. Database::query($sql);
  3150. }
  3151. }
  3152. }
  3153. // Inserting new sessions list.
  3154. if (!empty($sessions_list) && is_array($sessions_list)) {
  3155. foreach ($sessions_list as $session_id) {
  3156. $session_id = intval($session_id);
  3157. $sql = "SELECT session_id
  3158. FROM $tbl_session_rel_user
  3159. WHERE
  3160. session_id = $session_id AND
  3161. user_id = $userId AND
  3162. relation_type = '".SESSION_RELATION_TYPE_RRHH."'";
  3163. $result = Database::query($sql);
  3164. if (Database::num_rows($result) == 0) {
  3165. $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, relation_type, registered_at)
  3166. VALUES (
  3167. $session_id,
  3168. $userId,
  3169. '".SESSION_RELATION_TYPE_RRHH."',
  3170. '".api_get_utc_datetime()."'
  3171. )";
  3172. Database::query($sql);
  3173. $affected_rows++;
  3174. }
  3175. }
  3176. }
  3177. return $affected_rows;
  3178. }
  3179. /**
  3180. * @param int $sessionId
  3181. *
  3182. * @return array
  3183. */
  3184. public static function getDrhUsersInSession($sessionId)
  3185. {
  3186. return self::get_users_by_session($sessionId, SESSION_RELATION_TYPE_RRHH);
  3187. }
  3188. /**
  3189. * @param int $userId
  3190. * @param int $sessionId
  3191. *
  3192. * @return array
  3193. */
  3194. public static function getSessionFollowedByDrh($userId, $sessionId)
  3195. {
  3196. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3197. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3198. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3199. $userId = (int) $userId;
  3200. $sessionId = (int) $sessionId;
  3201. $select = " SELECT * ";
  3202. if (api_is_multiple_url_enabled()) {
  3203. $sql = " $select FROM $tbl_session s
  3204. INNER JOIN $tbl_session_rel_user sru ON (sru.session_id = s.id)
  3205. LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
  3206. WHERE
  3207. sru.user_id = '$userId' AND
  3208. sru.session_id = '$sessionId' AND
  3209. sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
  3210. access_url_id = ".api_get_current_access_url_id()."
  3211. ";
  3212. } else {
  3213. $sql = "$select FROM $tbl_session s
  3214. INNER JOIN $tbl_session_rel_user sru
  3215. ON
  3216. sru.session_id = s.id AND
  3217. sru.user_id = '$userId' AND
  3218. sru.session_id = '$sessionId' AND
  3219. sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
  3220. ";
  3221. }
  3222. $result = Database::query($sql);
  3223. if (Database::num_rows($result)) {
  3224. $row = Database::fetch_array($result, 'ASSOC');
  3225. $row['course_list'] = self::get_course_list_by_session_id($sessionId);
  3226. return $row;
  3227. }
  3228. return [];
  3229. }
  3230. /**
  3231. * Get sessions followed by human resources manager.
  3232. *
  3233. * @param int $userId
  3234. * @param int $start
  3235. * @param int $limit
  3236. * @param bool $getCount
  3237. * @param bool $getOnlySessionId
  3238. * @param bool $getSql
  3239. * @param string $orderCondition
  3240. * @param string $keyword
  3241. * @param string $description
  3242. * @param array $options
  3243. *
  3244. * @return array sessions
  3245. */
  3246. public static function get_sessions_followed_by_drh(
  3247. $userId,
  3248. $start = null,
  3249. $limit = null,
  3250. $getCount = false,
  3251. $getOnlySessionId = false,
  3252. $getSql = false,
  3253. $orderCondition = null,
  3254. $keyword = '',
  3255. $description = '',
  3256. $options = []
  3257. ) {
  3258. return self::getSessionsFollowedByUser(
  3259. $userId,
  3260. DRH,
  3261. $start,
  3262. $limit,
  3263. $getCount,
  3264. $getOnlySessionId,
  3265. $getSql,
  3266. $orderCondition,
  3267. $keyword,
  3268. $description,
  3269. $options
  3270. );
  3271. }
  3272. /**
  3273. * Get sessions followed by human resources manager.
  3274. *
  3275. * @param int $userId
  3276. * @param int $status DRH Optional
  3277. * @param int $start
  3278. * @param int $limit
  3279. * @param bool $getCount
  3280. * @param bool $getOnlySessionId
  3281. * @param bool $getSql
  3282. * @param string $orderCondition
  3283. * @param string $keyword
  3284. * @param string $description
  3285. * @param array $options
  3286. *
  3287. * @return array sessions
  3288. */
  3289. public static function getSessionsFollowedByUser(
  3290. $userId,
  3291. $status = null,
  3292. $start = null,
  3293. $limit = null,
  3294. $getCount = false,
  3295. $getOnlySessionId = false,
  3296. $getSql = false,
  3297. $orderCondition = null,
  3298. $keyword = '',
  3299. $description = '',
  3300. $options = []
  3301. ) {
  3302. // Database Table Definitions
  3303. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3304. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3305. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3306. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3307. $extraFieldModel = new ExtraFieldModel('session');
  3308. $conditions = $extraFieldModel->parseConditions($options);
  3309. $sqlInjectJoins = $conditions['inject_joins'];
  3310. $extraFieldsConditions = $conditions['where'];
  3311. $sqlInjectWhere = $conditions['inject_where'];
  3312. $injectExtraFields = $conditions['inject_extra_fields'];
  3313. if (!empty($injectExtraFields)) {
  3314. $injectExtraFields = ' , '.$injectExtraFields.' s.id';
  3315. }
  3316. $userId = (int) $userId;
  3317. $select = ' SELECT DISTINCT * '.$injectExtraFields;
  3318. if ($getCount) {
  3319. $select = ' SELECT count(DISTINCT(s.id)) as count ';
  3320. }
  3321. if ($getOnlySessionId) {
  3322. $select = ' SELECT DISTINCT(s.id) ';
  3323. }
  3324. $limitCondition = null;
  3325. if (!is_null($start) && !is_null($limit)) {
  3326. $limitCondition = " LIMIT ".intval($start).", ".intval($limit);
  3327. }
  3328. if (empty($orderCondition)) {
  3329. $orderCondition = ' ORDER BY s.name ';
  3330. }
  3331. $whereConditions = null;
  3332. $sessionCourseConditions = null;
  3333. $sessionConditions = null;
  3334. $sessionQuery = '';
  3335. $courseSessionQuery = null;
  3336. switch ($status) {
  3337. case DRH:
  3338. $sessionQuery = "SELECT sru.session_id
  3339. FROM
  3340. $tbl_session_rel_user sru
  3341. WHERE
  3342. sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
  3343. sru.user_id = $userId";
  3344. break;
  3345. case COURSEMANAGER:
  3346. $courseSessionQuery = "
  3347. SELECT scu.session_id as id
  3348. FROM $tbl_session_rel_course_rel_user scu
  3349. WHERE (scu.status = 2 AND scu.user_id = $userId)";
  3350. $whereConditions = " OR (s.id_coach = $userId) ";
  3351. break;
  3352. default:
  3353. $sessionQuery = "SELECT sru.session_id
  3354. FROM
  3355. $tbl_session_rel_user sru
  3356. WHERE
  3357. sru.user_id = $userId";
  3358. break;
  3359. }
  3360. $keywordCondition = '';
  3361. if (!empty($keyword)) {
  3362. $keyword = Database::escape_string($keyword);
  3363. $keywordCondition = " AND (s.name LIKE '%$keyword%' ) ";
  3364. if (!empty($description)) {
  3365. $description = Database::escape_string($description);
  3366. $keywordCondition = " AND (s.name LIKE '%$keyword%' OR s.description LIKE '%$description%' ) ";
  3367. }
  3368. }
  3369. $whereConditions .= $keywordCondition;
  3370. $subQuery = $sessionQuery.$courseSessionQuery;
  3371. $sql = " $select
  3372. FROM $tbl_session s
  3373. INNER JOIN $tbl_session_rel_access_url a
  3374. ON (s.id = a.session_id)
  3375. $sqlInjectJoins
  3376. WHERE
  3377. access_url_id = ".api_get_current_access_url_id()." AND
  3378. s.id IN (
  3379. $subQuery
  3380. )
  3381. $whereConditions
  3382. $extraFieldsConditions
  3383. $sqlInjectWhere
  3384. $orderCondition
  3385. $limitCondition";
  3386. if ($getSql) {
  3387. return $sql;
  3388. }
  3389. $result = Database::query($sql);
  3390. if ($getCount) {
  3391. $row = Database::fetch_array($result);
  3392. return $row['count'];
  3393. }
  3394. $sessions = [];
  3395. if (Database::num_rows($result) > 0) {
  3396. $sysUploadPath = api_get_path(SYS_UPLOAD_PATH).'sessions/';
  3397. $webUploadPath = api_get_path(WEB_UPLOAD_PATH).'sessions/';
  3398. $imgPath = Display::return_icon(
  3399. 'session_default_small.png',
  3400. null,
  3401. [],
  3402. ICON_SIZE_SMALL,
  3403. false,
  3404. true
  3405. );
  3406. while ($row = Database::fetch_array($result)) {
  3407. if ($getOnlySessionId) {
  3408. $sessions[$row['id']] = $row;
  3409. continue;
  3410. }
  3411. $imageFilename = ExtraFieldModel::FIELD_TYPE_FILE_IMAGE.'_'.$row['id'].'.png';
  3412. $row['image'] = is_file($sysUploadPath.$imageFilename) ? $webUploadPath.$imageFilename : $imgPath;
  3413. if ($row['display_start_date'] == '0000-00-00 00:00:00' || $row['display_start_date'] == '0000-00-00') {
  3414. $row['display_start_date'] = null;
  3415. }
  3416. if ($row['display_end_date'] == '0000-00-00 00:00:00' || $row['display_end_date'] == '0000-00-00') {
  3417. $row['display_end_date'] = null;
  3418. }
  3419. if ($row['access_start_date'] == '0000-00-00 00:00:00' || $row['access_start_date'] == '0000-00-00') {
  3420. $row['access_start_date'] = null;
  3421. }
  3422. if ($row['access_end_date'] == '0000-00-00 00:00:00' || $row['access_end_date'] == '0000-00-00') {
  3423. $row['access_end_date'] = null;
  3424. }
  3425. if ($row['coach_access_start_date'] == '0000-00-00 00:00:00' ||
  3426. $row['coach_access_start_date'] == '0000-00-00'
  3427. ) {
  3428. $row['coach_access_start_date'] = null;
  3429. }
  3430. if ($row['coach_access_end_date'] == '0000-00-00 00:00:00' ||
  3431. $row['coach_access_end_date'] == '0000-00-00'
  3432. ) {
  3433. $row['coach_access_end_date'] = null;
  3434. }
  3435. $sessions[$row['id']] = $row;
  3436. }
  3437. }
  3438. return $sessions;
  3439. }
  3440. /**
  3441. * Gets the list (or the count) of courses by session filtered by access_url.
  3442. *
  3443. * @param int $session_id The session id
  3444. * @param string $course_name The course code
  3445. * @param string $orderBy Field to order the data
  3446. * @param bool $getCount Optional. Count the session courses
  3447. *
  3448. * @return array|int List of courses. Whether $getCount is true, return the count
  3449. */
  3450. public static function get_course_list_by_session_id(
  3451. $session_id,
  3452. $course_name = '',
  3453. $orderBy = null,
  3454. $getCount = false
  3455. ) {
  3456. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3457. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3458. $session_id = (int) $session_id;
  3459. $sqlSelect = '*, c.id, c.id as real_id, c.code as course_code';
  3460. if ($getCount) {
  3461. $sqlSelect = 'COUNT(1) as count';
  3462. }
  3463. // select the courses
  3464. $sql = "SELECT $sqlSelect
  3465. FROM $tbl_course c
  3466. INNER JOIN $tbl_session_rel_course src
  3467. ON (c.id = src.c_id)
  3468. WHERE src.session_id = '$session_id' ";
  3469. if (!empty($course_name)) {
  3470. $course_name = Database::escape_string($course_name);
  3471. $sql .= " AND c.title LIKE '%$course_name%' ";
  3472. }
  3473. if (!empty($orderBy)) {
  3474. $orderBy = Database::escape_string($orderBy);
  3475. $orderBy = " ORDER BY $orderBy";
  3476. } else {
  3477. if (self::orderCourseIsEnabled()) {
  3478. $orderBy .= ' ORDER BY position ';
  3479. } else {
  3480. $orderBy .= ' ORDER BY title ';
  3481. }
  3482. }
  3483. $sql .= Database::escape_string($orderBy);
  3484. $result = Database::query($sql);
  3485. $num_rows = Database::num_rows($result);
  3486. $courses = [];
  3487. if ($num_rows > 0) {
  3488. if ($getCount) {
  3489. $count = Database::fetch_assoc($result);
  3490. return (int) $count['count'];
  3491. }
  3492. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3493. $courses[$row['real_id']] = $row;
  3494. }
  3495. }
  3496. return $courses;
  3497. }
  3498. /**
  3499. * Gets the list of courses by session filtered by access_url.
  3500. *
  3501. * @param $userId
  3502. * @param $sessionId
  3503. * @param null $from
  3504. * @param null $limit
  3505. * @param null $column
  3506. * @param null $direction
  3507. * @param bool $getCount
  3508. * @param string $keyword
  3509. *
  3510. * @return array
  3511. */
  3512. public static function getAllCoursesFollowedByUser(
  3513. $userId,
  3514. $sessionId,
  3515. $from = null,
  3516. $limit = null,
  3517. $column = null,
  3518. $direction = null,
  3519. $getCount = false,
  3520. $keyword = ''
  3521. ) {
  3522. if (empty($sessionId)) {
  3523. $sessionsSQL = self::get_sessions_followed_by_drh(
  3524. $userId,
  3525. null,
  3526. null,
  3527. null,
  3528. true,
  3529. true
  3530. );
  3531. } else {
  3532. $sessionsSQL = intval($sessionId);
  3533. }
  3534. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3535. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3536. if ($getCount) {
  3537. $select = "SELECT COUNT(DISTINCT(c.code)) as count ";
  3538. } else {
  3539. $select = "SELECT DISTINCT c.* ";
  3540. }
  3541. $keywordCondition = null;
  3542. if (!empty($keyword)) {
  3543. $keyword = Database::escape_string($keyword);
  3544. $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
  3545. }
  3546. // Select the courses
  3547. $sql = "$select
  3548. FROM $tbl_course c
  3549. INNER JOIN $tbl_session_rel_course src
  3550. ON c.id = src.c_id
  3551. WHERE
  3552. src.session_id IN ($sessionsSQL)
  3553. $keywordCondition
  3554. ";
  3555. if ($getCount) {
  3556. $result = Database::query($sql);
  3557. $row = Database::fetch_array($result, 'ASSOC');
  3558. return $row['count'];
  3559. }
  3560. if (isset($from) && isset($limit)) {
  3561. $from = intval($from);
  3562. $limit = intval($limit);
  3563. $sql .= " LIMIT $from, $limit";
  3564. }
  3565. $result = Database::query($sql);
  3566. $num_rows = Database::num_rows($result);
  3567. $courses = [];
  3568. if ($num_rows > 0) {
  3569. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3570. $courses[$row['id']] = $row;
  3571. }
  3572. }
  3573. return $courses;
  3574. }
  3575. /**
  3576. * Gets the list of courses by session filtered by access_url.
  3577. *
  3578. * @param int $session_id
  3579. * @param string $course_name
  3580. *
  3581. * @return array list of courses
  3582. */
  3583. public static function get_course_list_by_session_id_like($session_id, $course_name = '')
  3584. {
  3585. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3586. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3587. $session_id = (int) $session_id;
  3588. $course_name = Database::escape_string($course_name);
  3589. // select the courses
  3590. $sql = "SELECT c.id, c.title FROM $tbl_course c
  3591. INNER JOIN $tbl_session_rel_course src
  3592. ON c.id = src.c_id
  3593. WHERE ";
  3594. if (!empty($session_id)) {
  3595. $sql .= "src.session_id LIKE '$session_id' AND ";
  3596. }
  3597. if (!empty($course_name)) {
  3598. $sql .= "UPPER(c.title) LIKE UPPER('%$course_name%') ";
  3599. }
  3600. $sql .= "ORDER BY title;";
  3601. $result = Database::query($sql);
  3602. $num_rows = Database::num_rows($result);
  3603. $courses = [];
  3604. if ($num_rows > 0) {
  3605. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3606. $courses[$row['id']] = $row;
  3607. }
  3608. }
  3609. return $courses;
  3610. }
  3611. /**
  3612. * Gets the count of courses by session filtered by access_url.
  3613. *
  3614. * @param int session id
  3615. * @param string $keyword
  3616. *
  3617. * @return array list of courses
  3618. */
  3619. public static function getCourseCountBySessionId($session_id, $keyword = '')
  3620. {
  3621. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3622. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3623. $session_id = (int) $session_id;
  3624. // select the courses
  3625. $sql = "SELECT COUNT(c.code) count
  3626. FROM $tbl_course c
  3627. INNER JOIN $tbl_session_rel_course src
  3628. ON c.id = src.c_id
  3629. WHERE src.session_id = '$session_id' ";
  3630. $keywordCondition = null;
  3631. if (!empty($keyword)) {
  3632. $keyword = Database::escape_string($keyword);
  3633. $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
  3634. }
  3635. $sql .= $keywordCondition;
  3636. $result = Database::query($sql);
  3637. $num_rows = Database::num_rows($result);
  3638. if ($num_rows > 0) {
  3639. $row = Database::fetch_array($result, 'ASSOC');
  3640. return $row['count'];
  3641. }
  3642. return null;
  3643. }
  3644. /**
  3645. * Get the session id based on the original id and field name in the extra fields.
  3646. * Returns 0 if session was not found.
  3647. *
  3648. * @param string $value Original session id
  3649. * @param string $variable Original field name
  3650. *
  3651. * @return int Session id
  3652. */
  3653. public static function getSessionIdFromOriginalId($value, $variable)
  3654. {
  3655. $extraFieldValue = new ExtraFieldValue('session');
  3656. $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  3657. $variable,
  3658. $value
  3659. );
  3660. if (!empty($result)) {
  3661. return $result['item_id'];
  3662. }
  3663. return 0;
  3664. }
  3665. /**
  3666. * Get users by session.
  3667. *
  3668. * @param int $id session id
  3669. * @param int $status filter by status coach = 2
  3670. * @param bool $getCount Optional. Allow get the number of rows from the result
  3671. * @param int $urlId
  3672. *
  3673. * @return array|int A list with an user list. If $getCount is true then return a the count of registers
  3674. */
  3675. public static function get_users_by_session(
  3676. $id,
  3677. $status = null,
  3678. $getCount = false,
  3679. $urlId = 0
  3680. ) {
  3681. if (empty($id)) {
  3682. return [];
  3683. }
  3684. $id = (int) $id;
  3685. $urlId = empty($urlId) ? api_get_current_access_url_id() : (int) $urlId;
  3686. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3687. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3688. $table_access_url_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3689. $selectedField = '
  3690. u.user_id, u.lastname, u.firstname, u.username, su.relation_type, au.access_url_id,
  3691. su.moved_to, su.moved_status, su.moved_at, su.registered_at
  3692. ';
  3693. if ($getCount) {
  3694. $selectedField = 'count(1) AS count';
  3695. }
  3696. $sql = "SELECT $selectedField
  3697. FROM $tbl_user u
  3698. INNER JOIN $tbl_session_rel_user su
  3699. ON u.user_id = su.user_id AND
  3700. su.session_id = $id
  3701. LEFT OUTER JOIN $table_access_url_user au
  3702. ON (au.user_id = u.user_id)
  3703. ";
  3704. if (is_numeric($status)) {
  3705. $status = (int) $status;
  3706. $sql .= " WHERE su.relation_type = $status AND (au.access_url_id = $urlId OR au.access_url_id is null)";
  3707. } else {
  3708. $sql .= " WHERE (au.access_url_id = $urlId OR au.access_url_id is null )";
  3709. }
  3710. $sql .= ' ORDER BY su.relation_type, ';
  3711. $sql .= api_sort_by_first_name() ? ' u.firstname, u.lastname' : ' u.lastname, u.firstname';
  3712. $result = Database::query($sql);
  3713. if ($getCount) {
  3714. $count = Database::fetch_assoc($result);
  3715. return $count['count'];
  3716. }
  3717. $return = [];
  3718. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3719. $return[] = $row;
  3720. }
  3721. return $return;
  3722. }
  3723. /**
  3724. * The general coach (field: session.id_coach).
  3725. *
  3726. * @param int $user_id user id
  3727. * @param bool $asPlatformAdmin The user is platform admin, return everything
  3728. *
  3729. * @return array
  3730. */
  3731. public static function get_sessions_by_general_coach($user_id, $asPlatformAdmin = false)
  3732. {
  3733. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3734. $user_id = (int) $user_id;
  3735. // Session where we are general coach
  3736. $sql = "SELECT DISTINCT *
  3737. FROM $session_table";
  3738. if (!$asPlatformAdmin) {
  3739. $sql .= " WHERE id_coach = $user_id";
  3740. }
  3741. if (api_is_multiple_url_enabled()) {
  3742. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3743. $access_url_id = api_get_current_access_url_id();
  3744. $sqlCoach = '';
  3745. if (!$asPlatformAdmin) {
  3746. $sqlCoach = " id_coach = $user_id AND ";
  3747. }
  3748. if ($access_url_id != -1) {
  3749. $sql = 'SELECT DISTINCT session.*
  3750. FROM '.$session_table.' session INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
  3751. ON (session.id = session_rel_url.session_id)
  3752. WHERE '.$sqlCoach.' access_url_id = '.$access_url_id;
  3753. }
  3754. }
  3755. $sql .= ' ORDER by name';
  3756. $result = Database::query($sql);
  3757. return Database::store_result($result, 'ASSOC');
  3758. }
  3759. /**
  3760. * @param int $user_id
  3761. *
  3762. * @return array
  3763. *
  3764. * @deprecated use get_sessions_by_general_coach()
  3765. */
  3766. public static function get_sessions_by_coach($user_id)
  3767. {
  3768. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3769. return Database::select(
  3770. '*',
  3771. $session_table,
  3772. ['where' => ['id_coach = ?' => $user_id]]
  3773. );
  3774. }
  3775. /**
  3776. * @param int $user_id
  3777. * @param int $courseId
  3778. * @param int $session_id
  3779. *
  3780. * @return array|bool
  3781. */
  3782. public static function get_user_status_in_course_session($user_id, $courseId, $session_id)
  3783. {
  3784. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3785. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3786. $sql = "SELECT session_rcru.status
  3787. FROM $table session_rcru
  3788. INNER JOIN $tbl_user user
  3789. ON (session_rcru.user_id = user.user_id)
  3790. WHERE
  3791. session_rcru.session_id = '".intval($session_id)."' AND
  3792. session_rcru.c_id ='".intval($courseId)."' AND
  3793. user.user_id = ".intval($user_id);
  3794. $result = Database::query($sql);
  3795. $status = false;
  3796. if (Database::num_rows($result)) {
  3797. $status = Database::fetch_row($result);
  3798. $status = $status['0'];
  3799. }
  3800. return $status;
  3801. }
  3802. /**
  3803. * Gets user status within a session.
  3804. *
  3805. * @param int $userId
  3806. * @param int $sessionId
  3807. *
  3808. * @return SessionRelUser
  3809. */
  3810. public static function getUserStatusInSession($userId, $sessionId)
  3811. {
  3812. $em = Database::getManager();
  3813. $subscriptions = $em
  3814. ->getRepository('ChamiloCoreBundle:SessionRelUser')
  3815. ->findBy(['session' => $sessionId, 'user' => $userId]);
  3816. /** @var SessionRelUser $subscription */
  3817. $subscription = current($subscriptions);
  3818. return $subscription;
  3819. }
  3820. /**
  3821. * @param int $id
  3822. *
  3823. * @return array
  3824. */
  3825. public static function get_all_sessions_by_promotion($id)
  3826. {
  3827. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  3828. return Database::select(
  3829. '*',
  3830. $table,
  3831. ['where' => ['promotion_id = ?' => $id]]
  3832. );
  3833. }
  3834. /**
  3835. * @param int $promotion_id
  3836. * @param array $list
  3837. */
  3838. public static function subscribe_sessions_to_promotion($promotion_id, $list)
  3839. {
  3840. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  3841. $params = [];
  3842. $params['promotion_id'] = 0;
  3843. Database::update(
  3844. $table,
  3845. $params,
  3846. ['promotion_id = ?' => $promotion_id]
  3847. );
  3848. $params['promotion_id'] = $promotion_id;
  3849. if (!empty($list)) {
  3850. foreach ($list as $session_id) {
  3851. $session_id = (int) $session_id;
  3852. Database::update($table, $params, ['id = ?' => $session_id]);
  3853. }
  3854. }
  3855. }
  3856. /**
  3857. * Updates a session status.
  3858. *
  3859. * @param int session id
  3860. * @param int status
  3861. */
  3862. public static function set_session_status($session_id, $status)
  3863. {
  3864. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  3865. $params['visibility'] = $status;
  3866. Database::update($t, $params, ['id = ?' => $session_id]);
  3867. }
  3868. /**
  3869. * Copies a session with the same data to a new session.
  3870. * The new copy is not assigned to the same promotion.
  3871. *
  3872. *
  3873. * @param int $id Session ID
  3874. * @param bool $copy_courses Whether to copy the relationship with courses
  3875. * @param bool $copyTeachersAndDrh
  3876. * @param bool $create_new_courses New courses will be created
  3877. * @param bool $set_exercises_lp_invisible Set exercises and LPs in the new session to invisible by default
  3878. *
  3879. * @return int The new session ID on success, 0 otherwise
  3880. *
  3881. * @see subscribe_sessions_to_promotions() for that.
  3882. *
  3883. * @todo make sure the extra session fields are copied too
  3884. */
  3885. public static function copy(
  3886. $id,
  3887. $copy_courses = true,
  3888. $copyTeachersAndDrh = true,
  3889. $create_new_courses = false,
  3890. $set_exercises_lp_invisible = false
  3891. ) {
  3892. $id = (int) $id;
  3893. $s = self::fetch($id);
  3894. if (empty($s)) {
  3895. return false;
  3896. }
  3897. // Check all dates before copying
  3898. // Get timestamp for now in UTC - see http://php.net/manual/es/function.time.php#117251
  3899. $now = time() - date('Z');
  3900. // Timestamp in one month
  3901. $inOneMonth = $now + (30 * 24 * 3600);
  3902. $inOneMonth = api_get_local_time($inOneMonth);
  3903. if (api_strtotime($s['access_start_date']) < $now) {
  3904. $s['access_start_date'] = api_get_local_time($now);
  3905. }
  3906. if (api_strtotime($s['display_start_date']) < $now) {
  3907. $s['display_start_date'] = api_get_local_time($now);
  3908. }
  3909. if (api_strtotime($s['coach_access_start_date']) < $now) {
  3910. $s['coach_access_start_date'] = api_get_local_time($now);
  3911. }
  3912. if (api_strtotime($s['access_end_date']) < $now) {
  3913. $s['access_end_date'] = $inOneMonth;
  3914. }
  3915. if (api_strtotime($s['display_end_date']) < $now) {
  3916. $s['display_end_date'] = $inOneMonth;
  3917. }
  3918. if (api_strtotime($s['coach_access_end_date']) < $now) {
  3919. $s['coach_access_end_date'] = $inOneMonth;
  3920. }
  3921. $extraFieldValue = new ExtraFieldValue('session');
  3922. $extraFieldsValues = $extraFieldValue->getAllValuesByItem($id);
  3923. $extraFieldsValuesToCopy = [];
  3924. if (!empty($extraFieldsValues)) {
  3925. foreach ($extraFieldsValues as $extraFieldValue) {
  3926. //$extraFieldsValuesToCopy['extra_'.$extraFieldValue['variable']] = $extraFieldValue['value'];
  3927. $extraFieldsValuesToCopy['extra_'.$extraFieldValue['variable']]['extra_'.$extraFieldValue['variable']] = $extraFieldValue['value'];
  3928. }
  3929. }
  3930. // Now try to create the session
  3931. $sid = self::create_session(
  3932. $s['name'].' '.get_lang('CopyLabelSuffix'),
  3933. $s['access_start_date'],
  3934. $s['access_end_date'],
  3935. $s['display_start_date'],
  3936. $s['display_end_date'],
  3937. $s['coach_access_start_date'],
  3938. $s['coach_access_end_date'],
  3939. (int) $s['id_coach'],
  3940. $s['session_category_id'],
  3941. (int) $s['visibility'],
  3942. true,
  3943. $s['duration'],
  3944. $s['description'],
  3945. $s['show_description'],
  3946. $extraFieldsValuesToCopy
  3947. );
  3948. if (!is_numeric($sid) || empty($sid)) {
  3949. return false;
  3950. }
  3951. if ($copy_courses) {
  3952. // Register courses from the original session to the new session
  3953. $courses = self::get_course_list_by_session_id($id);
  3954. $short_courses = $new_short_courses = [];
  3955. if (is_array($courses) && count($courses) > 0) {
  3956. foreach ($courses as $course) {
  3957. $short_courses[] = $course;
  3958. }
  3959. }
  3960. // We will copy the current courses of the session to new courses
  3961. if (!empty($short_courses)) {
  3962. if ($create_new_courses) {
  3963. api_set_more_memory_and_time_limits();
  3964. $params = [];
  3965. $params['skip_lp_dates'] = true;
  3966. foreach ($short_courses as $course_data) {
  3967. $course_info = CourseManager::copy_course_simple(
  3968. $course_data['title'].' '.get_lang(
  3969. 'CopyLabelSuffix'
  3970. ),
  3971. $course_data['course_code'],
  3972. $id,
  3973. $sid,
  3974. $params
  3975. );
  3976. if ($course_info) {
  3977. //By default new elements are invisible
  3978. if ($set_exercises_lp_invisible) {
  3979. $list = new LearnpathList('', $course_info, $sid);
  3980. $flat_list = $list->get_flat_list();
  3981. if (!empty($flat_list)) {
  3982. foreach ($flat_list as $lp_id => $data) {
  3983. api_item_property_update(
  3984. $course_info,
  3985. TOOL_LEARNPATH,
  3986. $lp_id,
  3987. 'invisible',
  3988. api_get_user_id(),
  3989. 0,
  3990. 0,
  3991. 0,
  3992. 0,
  3993. $sid
  3994. );
  3995. }
  3996. }
  3997. $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
  3998. $course_id = $course_info['real_id'];
  3999. //@todo check this query
  4000. $sql = "UPDATE $quiz_table SET active = 0
  4001. WHERE c_id = $course_id AND session_id = $sid";
  4002. Database::query($sql);
  4003. }
  4004. $new_short_courses[] = $course_info['real_id'];
  4005. }
  4006. }
  4007. } else {
  4008. foreach ($short_courses as $course_data) {
  4009. $new_short_courses[] = $course_data['id'];
  4010. }
  4011. }
  4012. $short_courses = $new_short_courses;
  4013. self::add_courses_to_session($sid, $short_courses, true);
  4014. if ($create_new_courses === false && $copyTeachersAndDrh) {
  4015. foreach ($short_courses as $course) {
  4016. $coachList = self::getCoachesByCourseSession($id, $course['id']);
  4017. foreach ($coachList as $userId) {
  4018. self::set_coach_to_course_session($userId, $sid, $course['id']);
  4019. }
  4020. }
  4021. }
  4022. }
  4023. }
  4024. if ($copyTeachersAndDrh) {
  4025. // Register users from the original session to the new session
  4026. $users = self::get_users_by_session($id);
  4027. if (!empty($users)) {
  4028. $userListByStatus = [];
  4029. foreach ($users as $userData) {
  4030. $userData['relation_type'] = (int) $userData['relation_type'];
  4031. $userListByStatus[$userData['relation_type']][] = $userData;
  4032. }
  4033. foreach ($userListByStatus as $status => $userList) {
  4034. $userList = array_column($userList, 'user_id');
  4035. switch ($status) {
  4036. case 0:
  4037. /*self::subscribeUsersToSession(
  4038. $sid,
  4039. $userList,
  4040. SESSION_VISIBLE_READ_ONLY,
  4041. false,
  4042. true
  4043. );*/
  4044. break;
  4045. case 1:
  4046. // drh users
  4047. foreach ($userList as $drhId) {
  4048. $userInfo = api_get_user_info($drhId);
  4049. self::subscribeSessionsToDrh($userInfo, [$sid], false, false);
  4050. }
  4051. break;
  4052. }
  4053. }
  4054. }
  4055. }
  4056. return $sid;
  4057. }
  4058. /**
  4059. * @param int $user_id
  4060. * @param int $session_id
  4061. *
  4062. * @return bool
  4063. */
  4064. public static function user_is_general_coach($user_id, $session_id)
  4065. {
  4066. $session_id = (int) $session_id;
  4067. $user_id = (int) $user_id;
  4068. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  4069. $sql = "SELECT DISTINCT id
  4070. FROM $table
  4071. WHERE session.id_coach = '".$user_id."' AND id = '$session_id'";
  4072. $result = Database::query($sql);
  4073. if ($result && Database::num_rows($result)) {
  4074. return true;
  4075. }
  4076. return false;
  4077. }
  4078. /**
  4079. * Get the number of sessions.
  4080. *
  4081. * @param int ID of the URL we want to filter on (optional)
  4082. *
  4083. * @return int Number of sessions
  4084. */
  4085. public static function count_sessions($access_url_id = null)
  4086. {
  4087. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  4088. $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  4089. $sql = "SELECT count(s.id) FROM $session_table s";
  4090. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  4091. $sql .= ", $access_url_rel_session_table u ".
  4092. " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
  4093. }
  4094. $res = Database::query($sql);
  4095. $row = Database::fetch_row($res);
  4096. return $row[0];
  4097. }
  4098. /**
  4099. * Return a COUNT from Session table.
  4100. *
  4101. * @param string $date in Y-m-d format
  4102. *
  4103. * @return int
  4104. */
  4105. public static function countSessionsByEndDate($date = null)
  4106. {
  4107. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  4108. $url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  4109. $date = Database::escape_string($date);
  4110. $urlId = api_get_current_access_url_id();
  4111. $dateFilter = '';
  4112. if (!empty($date)) {
  4113. $dateFilter = <<<SQL
  4114. AND ('$date' BETWEEN s.access_start_date AND s.access_end_date)
  4115. OR (s.access_end_date IS NULL)
  4116. OR (
  4117. s.access_start_date IS NULL AND
  4118. s.access_end_date IS NOT NULL AND s.access_end_date > '$date'
  4119. )
  4120. SQL;
  4121. }
  4122. $sql = "SELECT COUNT(*)
  4123. FROM $sessionTable s
  4124. INNER JOIN $url u
  4125. ON (s.id = u.session_id)
  4126. WHERE u.access_url_id = $urlId $dateFilter";
  4127. $res = Database::query($sql);
  4128. $count = 0;
  4129. if ($res !== false && Database::num_rows($res) > 0) {
  4130. $count = (int) current(Database::fetch_row($res));
  4131. }
  4132. return $count;
  4133. }
  4134. /**
  4135. * @param int $id
  4136. * @param bool $checkSession
  4137. *
  4138. * @return bool
  4139. */
  4140. public static function cantEditSession($id, $checkSession = true)
  4141. {
  4142. if (!self::allowToManageSessions()) {
  4143. return false;
  4144. }
  4145. if (api_is_platform_admin() && self::allowed($id)) {
  4146. return true;
  4147. }
  4148. if ($checkSession) {
  4149. if (self::allowed($id)) {
  4150. return true;
  4151. }
  4152. return false;
  4153. }
  4154. return true;
  4155. }
  4156. /**
  4157. * Protect a session to be edited.
  4158. *
  4159. * @param int $id
  4160. * @param bool $checkSession
  4161. *
  4162. * @return mixed | bool true if pass the check, api_not_allowed otherwise
  4163. */
  4164. public static function protectSession($id, $checkSession = true)
  4165. {
  4166. if (!self::cantEditSession($id, $checkSession)) {
  4167. api_not_allowed(true);
  4168. }
  4169. }
  4170. /**
  4171. * @return bool
  4172. */
  4173. public static function allowToManageSessions()
  4174. {
  4175. if (self::allowManageAllSessions()) {
  4176. return true;
  4177. }
  4178. $setting = api_get_setting('allow_teachers_to_create_sessions');
  4179. if (api_is_teacher() && $setting == 'true') {
  4180. return true;
  4181. }
  4182. return false;
  4183. }
  4184. /**
  4185. * @return bool
  4186. */
  4187. public static function allowOnlyMySessions()
  4188. {
  4189. if (self::allowToManageSessions() &&
  4190. !api_is_platform_admin() &&
  4191. api_is_teacher()
  4192. ) {
  4193. return true;
  4194. }
  4195. return false;
  4196. }
  4197. /**
  4198. * @return bool
  4199. */
  4200. public static function allowManageAllSessions()
  4201. {
  4202. if (api_is_platform_admin() || api_is_session_admin()) {
  4203. return true;
  4204. }
  4205. return false;
  4206. }
  4207. /**
  4208. * @param $id
  4209. *
  4210. * @return bool
  4211. */
  4212. public static function protect_teacher_session_edit($id)
  4213. {
  4214. if (!api_is_coach($id) && !api_is_platform_admin()) {
  4215. api_not_allowed(true);
  4216. } else {
  4217. return true;
  4218. }
  4219. }
  4220. /**
  4221. * @param int $courseId
  4222. *
  4223. * @return array
  4224. */
  4225. public static function get_session_by_course($courseId)
  4226. {
  4227. $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  4228. $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
  4229. $url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  4230. $courseId = (int) $courseId;
  4231. $urlId = api_get_current_access_url_id();
  4232. if (empty($courseId)) {
  4233. return [];
  4234. }
  4235. $sql = "SELECT name, s.id
  4236. FROM $table_session_course sc
  4237. INNER JOIN $table_session s
  4238. ON (sc.session_id = s.id)
  4239. INNER JOIN $url u
  4240. ON (u.session_id = s.id)
  4241. WHERE
  4242. u.access_url_id = $urlId AND
  4243. sc.c_id = '$courseId' ";
  4244. $result = Database::query($sql);
  4245. return Database::store_result($result);
  4246. }
  4247. /**
  4248. * @param int $userId
  4249. * @param bool $ignoreVisibilityForAdmins
  4250. * @param bool $ignoreTimeLimit
  4251. *
  4252. * @return array
  4253. */
  4254. public static function get_sessions_by_user(
  4255. $userId,
  4256. $ignoreVisibilityForAdmins = false,
  4257. $ignoreTimeLimit = false
  4258. ) {
  4259. $sessionCategories = UserManager::get_sessions_by_category(
  4260. $userId,
  4261. false,
  4262. $ignoreVisibilityForAdmins,
  4263. $ignoreTimeLimit
  4264. );
  4265. $sessionArray = [];
  4266. if (!empty($sessionCategories)) {
  4267. foreach ($sessionCategories as $category) {
  4268. if (isset($category['sessions'])) {
  4269. foreach ($category['sessions'] as $session) {
  4270. $sessionArray[] = $session;
  4271. }
  4272. }
  4273. }
  4274. }
  4275. return $sessionArray;
  4276. }
  4277. /**
  4278. * @param string $file
  4279. * @param bool $updateSession true: if the session exists it will be updated.
  4280. * false: if session exists a new session will be created adding a counter session1, session2, etc
  4281. * @param int $defaultUserId
  4282. * @param Logger $logger
  4283. * @param array $extraFields convert a file row to an extra field. Example in CSV file there's a SessionID
  4284. * then it will converted to extra_external_session_id if you set: array('SessionId' => 'extra_external_session_id')
  4285. * @param string $extraFieldId
  4286. * @param int $daysCoachAccessBeforeBeginning
  4287. * @param int $daysCoachAccessAfterBeginning
  4288. * @param int $sessionVisibility
  4289. * @param array $fieldsToAvoidUpdate
  4290. * @param bool $deleteUsersNotInList
  4291. * @param bool $updateCourseCoaches
  4292. * @param bool $sessionWithCoursesModifier
  4293. * @param bool $addOriginalCourseTeachersAsCourseSessionCoaches
  4294. * @param bool $removeAllTeachersFromCourse
  4295. * @param int $showDescription
  4296. * @param array $teacherBackupList
  4297. * @param array $groupBackup
  4298. *
  4299. * @return array
  4300. */
  4301. public static function importCSV(
  4302. $file,
  4303. $updateSession,
  4304. $defaultUserId = null,
  4305. $logger = null,
  4306. $extraFields = [],
  4307. $extraFieldId = null,
  4308. $daysCoachAccessBeforeBeginning = null,
  4309. $daysCoachAccessAfterBeginning = null,
  4310. $sessionVisibility = 1,
  4311. $fieldsToAvoidUpdate = [],
  4312. $deleteUsersNotInList = false,
  4313. $updateCourseCoaches = false,
  4314. $sessionWithCoursesModifier = false,
  4315. $addOriginalCourseTeachersAsCourseSessionCoaches = true,
  4316. $removeAllTeachersFromCourse = true,
  4317. $showDescription = null,
  4318. &$teacherBackupList = [],
  4319. &$groupBackup = []
  4320. ) {
  4321. $content = file($file);
  4322. $error_message = null;
  4323. $session_counter = 0;
  4324. $defaultUserId = empty($defaultUserId) ? api_get_user_id() : (int) $defaultUserId;
  4325. $eol = PHP_EOL;
  4326. if (PHP_SAPI != 'cli') {
  4327. $eol = '<br />';
  4328. }
  4329. $debug = false;
  4330. if (isset($logger)) {
  4331. $debug = true;
  4332. }
  4333. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  4334. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  4335. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  4336. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4337. $sessions = [];
  4338. if (!api_strstr($content[0], ';')) {
  4339. $error_message = get_lang('NotCSV');
  4340. } else {
  4341. $tag_names = [];
  4342. foreach ($content as $key => $enreg) {
  4343. $enreg = explode(';', trim($enreg));
  4344. if ($key) {
  4345. foreach ($tag_names as $tag_key => $tag_name) {
  4346. if (isset($enreg[$tag_key])) {
  4347. $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
  4348. }
  4349. }
  4350. } else {
  4351. foreach ($enreg as $tag_name) {
  4352. $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
  4353. }
  4354. if (!in_array('SessionName', $tag_names) ||
  4355. !in_array('DateStart', $tag_names) ||
  4356. !in_array('DateEnd', $tag_names)
  4357. ) {
  4358. $error_message = get_lang('NoNeededData');
  4359. break;
  4360. }
  4361. }
  4362. }
  4363. $sessionList = [];
  4364. $report = [];
  4365. // Looping the sessions.
  4366. foreach ($sessions as $enreg) {
  4367. $user_counter = 0;
  4368. $course_counter = 0;
  4369. if (isset($extraFields) && !empty($extraFields)) {
  4370. foreach ($extraFields as $original => $to) {
  4371. $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
  4372. }
  4373. }
  4374. $session_name = $enreg['SessionName'];
  4375. if ($debug) {
  4376. $logger->addInfo('---------------------------------------');
  4377. $logger->addInfo("Sessions - Start process of session: $session_name");
  4378. $logger->addInfo('---------------------------------------');
  4379. }
  4380. // Default visibility
  4381. $visibilityAfterExpirationPerSession = $sessionVisibility;
  4382. if (isset($enreg['VisibilityAfterExpiration'])) {
  4383. $visibility = $enreg['VisibilityAfterExpiration'];
  4384. switch ($visibility) {
  4385. case 'read_only':
  4386. $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
  4387. break;
  4388. case 'accessible':
  4389. $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
  4390. break;
  4391. case 'not_accessible':
  4392. $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
  4393. break;
  4394. }
  4395. }
  4396. if (empty($session_name)) {
  4397. continue;
  4398. }
  4399. $displayAccessStartDate = isset($enreg['DisplayStartDate']) ? $enreg['DisplayStartDate'] : $enreg['DateStart'];
  4400. $displayAccessEndDate = isset($enreg['DisplayEndDate']) ? $enreg['DisplayEndDate'] : $enreg['DateEnd'];
  4401. $coachAccessStartDate = isset($enreg['CoachStartDate']) ? $enreg['CoachStartDate'] : $enreg['DateStart'];
  4402. $coachAccessEndDate = isset($enreg['CoachEndDate']) ? $enreg['CoachEndDate'] : $enreg['DateEnd'];
  4403. // We assume the dates are already in UTC
  4404. $dateStart = explode('/', $enreg['DateStart']);
  4405. $dateEnd = explode('/', $enreg['DateEnd']);
  4406. $dateStart = $dateStart[0].'-'.$dateStart[1].'-'.$dateStart[2].' 00:00:00';
  4407. $dateEnd = $dateEnd[0].'-'.$dateEnd[1].'-'.$dateEnd[2].' 23:59:59';
  4408. $displayAccessStartDate = explode('/', $displayAccessStartDate);
  4409. $displayAccessStartDate = implode('-', $displayAccessStartDate).' 00:00:00';
  4410. $displayAccessEndDate = explode('/', $displayAccessEndDate);
  4411. $displayAccessEndDate = implode('-', $displayAccessEndDate).' 23:59:59';
  4412. $coachAccessStartDate = explode('/', $coachAccessStartDate);
  4413. $coachAccessStartDate = implode('-', $coachAccessStartDate).' 00:00:00';
  4414. $coachAccessEndDate = explode('/', $coachAccessEndDate);
  4415. $coachAccessEndDate = implode('-', $coachAccessEndDate).' 23:59:59';
  4416. $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
  4417. $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
  4418. $classes = isset($enreg['Classes']) ? explode('|', $enreg['Classes']) : [];
  4419. $extraParams = [];
  4420. if (!is_null($showDescription)) {
  4421. $extraParams['show_description'] = intval($showDescription);
  4422. }
  4423. $coachBefore = '';
  4424. $coachAfter = '';
  4425. if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
  4426. $date = new \DateTime($dateStart);
  4427. $interval = new DateInterval('P'.$daysCoachAccessBeforeBeginning.'D');
  4428. $date->sub($interval);
  4429. $coachBefore = $date->format('Y-m-d h:i');
  4430. $coachAccessStartDate = $coachBefore;
  4431. $coachBefore = api_get_utc_datetime($coachBefore);
  4432. $date = new \DateTime($dateEnd);
  4433. $interval = new DateInterval('P'.$daysCoachAccessAfterBeginning.'D');
  4434. $date->add($interval);
  4435. $coachAfter = $date->format('Y-m-d h:i');
  4436. $coachAccessEndDate = $coachAfter;
  4437. $coachAfter = api_get_utc_datetime($coachAfter);
  4438. }
  4439. $dateStart = api_get_utc_datetime($dateStart);
  4440. $dateEnd = api_get_utc_datetime($dateEnd);
  4441. $displayAccessStartDate = api_get_utc_datetime($displayAccessStartDate);
  4442. $displayAccessEndDate = api_get_utc_datetime($displayAccessEndDate);
  4443. $coachAccessStartDate = api_get_utc_datetime($coachAccessStartDate);
  4444. $coachAccessEndDate = api_get_utc_datetime($coachAccessEndDate);
  4445. if (!empty($sessionDescription)) {
  4446. $extraParams['description'] = $sessionDescription;
  4447. }
  4448. if (!empty($session_category_id)) {
  4449. $extraParams['session_category_id'] = $session_category_id;
  4450. }
  4451. // Searching a general coach.
  4452. if (!empty($enreg['Coach'])) {
  4453. $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
  4454. if ($coach_id === false) {
  4455. // If the coach-user does not exist - I'm the coach.
  4456. $coach_id = $defaultUserId;
  4457. }
  4458. } else {
  4459. $coach_id = $defaultUserId;
  4460. }
  4461. $users = explode('|', $enreg['Users']);
  4462. $courses = explode('|', $enreg['Courses']);
  4463. $deleteOnlyCourseCoaches = false;
  4464. if (count($courses) == 1) {
  4465. if ($logger) {
  4466. $logger->addInfo('Only one course delete old coach list');
  4467. }
  4468. $deleteOnlyCourseCoaches = true;
  4469. }
  4470. if (!$updateSession) {
  4471. // Create a session.
  4472. $unique_name = false;
  4473. $i = 0;
  4474. // Change session name, verify that session doesn't exist.
  4475. $suffix = null;
  4476. while (!$unique_name) {
  4477. if ($i > 1) {
  4478. $suffix = ' - '.$i;
  4479. }
  4480. $sql = 'SELECT 1 FROM '.$tbl_session.'
  4481. WHERE name="'.Database::escape_string($session_name).$suffix.'"';
  4482. $rs = Database::query($sql);
  4483. if (Database::result($rs, 0, 0)) {
  4484. $i++;
  4485. } else {
  4486. $unique_name = true;
  4487. $session_name .= $suffix;
  4488. }
  4489. }
  4490. $sessionParams = [
  4491. 'name' => $session_name,
  4492. 'id_coach' => $coach_id,
  4493. 'access_start_date' => $dateStart,
  4494. 'access_end_date' => $dateEnd,
  4495. 'display_start_date' => $displayAccessStartDate,
  4496. 'display_end_date' => $displayAccessEndDate,
  4497. 'coach_access_start_date' => $coachAccessStartDate,
  4498. 'coach_access_end_date' => $coachAccessEndDate,
  4499. 'visibility' => $visibilityAfterExpirationPerSession,
  4500. 'session_admin_id' => $defaultUserId,
  4501. ];
  4502. if (!empty($extraParams)) {
  4503. $sessionParams = array_merge($sessionParams, $extraParams);
  4504. }
  4505. // Creating the session.
  4506. $session_id = Database::insert($tbl_session, $sessionParams);
  4507. if ($debug) {
  4508. if ($session_id) {
  4509. foreach ($enreg as $key => $value) {
  4510. if (substr($key, 0, 6) == 'extra_') { //an extra field
  4511. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  4512. }
  4513. }
  4514. $logger->addInfo("Session created: #$session_id - $session_name");
  4515. } else {
  4516. $message = "Sessions - Session NOT created: $session_name";
  4517. $logger->addError($message);
  4518. $report[] = $message;
  4519. }
  4520. }
  4521. $session_counter++;
  4522. } else {
  4523. $sessionId = null;
  4524. if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_'.$extraFieldId])) {
  4525. $sessionId = self::getSessionIdFromOriginalId($enreg['extra_'.$extraFieldId], $extraFieldId);
  4526. if (empty($sessionId)) {
  4527. $my_session_result = false;
  4528. } else {
  4529. $my_session_result = true;
  4530. }
  4531. } else {
  4532. $my_session_result = self::get_session_by_name($enreg['SessionName']);
  4533. }
  4534. if ($my_session_result === false) {
  4535. // One more check
  4536. $sessionExistsWithName = self::get_session_by_name($session_name);
  4537. if ($sessionExistsWithName) {
  4538. if ($debug) {
  4539. $message = "Skip Session - Trying to update a session, but name already exists: $session_name";
  4540. $logger->addError($message);
  4541. $report[] = $message;
  4542. }
  4543. continue;
  4544. }
  4545. $sessionParams = [
  4546. 'name' => $session_name,
  4547. 'id_coach' => $coach_id,
  4548. 'access_start_date' => $dateStart,
  4549. 'access_end_date' => $dateEnd,
  4550. 'display_start_date' => $displayAccessStartDate,
  4551. 'display_end_date' => $displayAccessEndDate,
  4552. 'coach_access_start_date' => $coachAccessStartDate,
  4553. 'coach_access_end_date' => $coachAccessEndDate,
  4554. 'visibility' => $visibilityAfterExpirationPerSession,
  4555. 'session_admin_id' => $defaultUserId,
  4556. ];
  4557. if (!empty($extraParams)) {
  4558. $sessionParams = array_merge($sessionParams, $extraParams);
  4559. }
  4560. Database::insert($tbl_session, $sessionParams);
  4561. // We get the last insert id.
  4562. $my_session_result = self::get_session_by_name($session_name);
  4563. $session_id = $my_session_result['id'];
  4564. if ($session_id) {
  4565. foreach ($enreg as $key => $value) {
  4566. if (substr($key, 0, 6) == 'extra_') { //an extra field
  4567. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  4568. }
  4569. }
  4570. if ($debug) {
  4571. $logger->addInfo("Sessions - #$session_id created: $session_name");
  4572. }
  4573. // Delete session-user relation only for students
  4574. $sql = "DELETE FROM $tbl_session_user
  4575. WHERE session_id = '$session_id' AND relation_type <> ".SESSION_RELATION_TYPE_RRHH;
  4576. Database::query($sql);
  4577. $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
  4578. Database::query($sql);
  4579. // Delete session-course-user relationships students and coaches.
  4580. if ($updateCourseCoaches) {
  4581. $sql = "DELETE FROM $tbl_session_course_user
  4582. WHERE session_id = '$session_id' AND status in ('0', '2')";
  4583. Database::query($sql);
  4584. } else {
  4585. // Delete session-course-user relation ships *only* for students.
  4586. $sql = "DELETE FROM $tbl_session_course_user
  4587. WHERE session_id = '$session_id' AND status <> 2";
  4588. Database::query($sql);
  4589. }
  4590. if ($deleteOnlyCourseCoaches) {
  4591. $sql = "DELETE FROM $tbl_session_course_user
  4592. WHERE session_id = '$session_id' AND status in ('2')";
  4593. Database::query($sql);
  4594. }
  4595. }
  4596. } else {
  4597. // Updating the session.
  4598. $params = [
  4599. 'id_coach' => $coach_id,
  4600. 'access_start_date' => $dateStart,
  4601. 'access_end_date' => $dateEnd,
  4602. 'display_start_date' => $displayAccessStartDate,
  4603. 'display_end_date' => $displayAccessEndDate,
  4604. 'coach_access_start_date' => $coachAccessStartDate,
  4605. 'coach_access_end_date' => $coachAccessEndDate,
  4606. 'visibility' => $visibilityAfterExpirationPerSession,
  4607. 'session_category_id' => $session_category_id,
  4608. ];
  4609. if (!empty($sessionDescription)) {
  4610. $params['description'] = $sessionDescription;
  4611. }
  4612. if (!empty($fieldsToAvoidUpdate)) {
  4613. foreach ($fieldsToAvoidUpdate as $field) {
  4614. unset($params[$field]);
  4615. }
  4616. }
  4617. if (isset($sessionId) && !empty($sessionId)) {
  4618. $session_id = $sessionId;
  4619. if (!empty($enreg['SessionName'])) {
  4620. $sessionExistsWithName = self::get_session_by_name($session_name);
  4621. if ($sessionExistsWithName === false) {
  4622. $sessionName = Database::escape_string($enreg['SessionName']);
  4623. $sql = "UPDATE $tbl_session SET name = '$sessionName' WHERE id = $session_id";
  4624. Database::query($sql);
  4625. $logger->addInfo(
  4626. "Session #$session_id name IS updated with: '$session_name' External id: ".$enreg['extra_'.$extraFieldId]
  4627. );
  4628. } else {
  4629. $sessionExistsBesidesMe = self::sessionNameExistBesidesMySession(
  4630. $session_id,
  4631. $session_name
  4632. );
  4633. if ($sessionExistsBesidesMe === true) {
  4634. if ($debug) {
  4635. $message = "Skip Session. Error when update session Session #$session_id Name: '$session_name'. Other session has the same name. External id: ".$enreg['extra_'.$extraFieldId];
  4636. $logger->addError($message);
  4637. $report[] = $message;
  4638. }
  4639. continue;
  4640. } else {
  4641. if ($debug) {
  4642. $logger->addInfo(
  4643. "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]
  4644. );
  4645. }
  4646. }
  4647. }
  4648. }
  4649. } else {
  4650. $my_session_result = self::get_session_by_name($session_name);
  4651. $session_id = $my_session_result['id'];
  4652. }
  4653. if ($debug) {
  4654. $logger->addInfo("Session #$session_id to be updated: '$session_name'");
  4655. }
  4656. if ($session_id) {
  4657. $sessionInfo = api_get_session_info($session_id);
  4658. $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
  4659. if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
  4660. if (empty($sessionInfo['nb_days_access_before_beginning']) ||
  4661. (!empty($sessionInfo['nb_days_access_before_beginning']) &&
  4662. $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning)
  4663. ) {
  4664. $params['coach_access_start_date'] = $coachBefore;
  4665. }
  4666. if (empty($sessionInfo['nb_days_access_after_end']) ||
  4667. (!empty($sessionInfo['nb_days_access_after_end']) &&
  4668. $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning)
  4669. ) {
  4670. $params['coach_access_end_date'] = $coachAfter;
  4671. }
  4672. }
  4673. Database::update($tbl_session, $params, ['id = ?' => $session_id]);
  4674. foreach ($enreg as $key => $value) {
  4675. if (substr($key, 0, 6) == 'extra_') { //an extra field
  4676. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  4677. }
  4678. }
  4679. if ($debug) {
  4680. $logger->addInfo("Session updated #$session_id");
  4681. }
  4682. // Delete session-user relation only for students
  4683. $sql = "DELETE FROM $tbl_session_user
  4684. WHERE session_id = '$session_id' AND relation_type <> ".SESSION_RELATION_TYPE_RRHH;
  4685. Database::query($sql);
  4686. $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
  4687. Database::query($sql);
  4688. // Delete session-course-user relationships students and coaches.
  4689. if ($updateCourseCoaches) {
  4690. $sql = "DELETE FROM $tbl_session_course_user
  4691. WHERE session_id = '$session_id' AND status in ('0', '2')";
  4692. Database::query($sql);
  4693. } else {
  4694. // Delete session-course-user relation ships *only* for students.
  4695. $sql = "DELETE FROM $tbl_session_course_user
  4696. WHERE session_id = '$session_id' AND status <> 2";
  4697. Database::query($sql);
  4698. }
  4699. if ($deleteOnlyCourseCoaches) {
  4700. $sql = "DELETE FROM $tbl_session_course_user
  4701. WHERE session_id = '$session_id' AND status in ('2')";
  4702. Database::query($sql);
  4703. }
  4704. } else {
  4705. if ($debug) {
  4706. $logger->addError(
  4707. "Sessions - Session not found"
  4708. );
  4709. }
  4710. }
  4711. }
  4712. $session_counter++;
  4713. }
  4714. $sessionList[] = $session_id;
  4715. // Adding the relationship "Session - User" for students
  4716. $userList = [];
  4717. if (is_array($users)) {
  4718. foreach ($users as $user) {
  4719. $user_id = UserManager::get_user_id_from_username($user);
  4720. if ($user_id !== false) {
  4721. $userList[] = $user_id;
  4722. // Insert new users.
  4723. $sql = "INSERT IGNORE INTO $tbl_session_user SET
  4724. user_id = '$user_id',
  4725. session_id = '$session_id',
  4726. registered_at = '".api_get_utc_datetime()."'";
  4727. Database::query($sql);
  4728. if ($debug) {
  4729. $logger->addInfo("Adding User #$user_id ($user) to session #$session_id");
  4730. }
  4731. $user_counter++;
  4732. }
  4733. }
  4734. }
  4735. if ($deleteUsersNotInList) {
  4736. // Getting user in DB in order to compare to the new list.
  4737. $usersListInDatabase = self::get_users_by_session($session_id, 0);
  4738. if (!empty($usersListInDatabase)) {
  4739. if (empty($userList)) {
  4740. foreach ($usersListInDatabase as $userInfo) {
  4741. self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
  4742. }
  4743. } else {
  4744. foreach ($usersListInDatabase as $userInfo) {
  4745. if (!in_array($userInfo['user_id'], $userList)) {
  4746. self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
  4747. }
  4748. }
  4749. }
  4750. }
  4751. }
  4752. // See BT#6449
  4753. $onlyAddFirstCoachOrTeacher = false;
  4754. if ($sessionWithCoursesModifier) {
  4755. if (count($courses) >= 2) {
  4756. // Only first teacher in course session;
  4757. $onlyAddFirstCoachOrTeacher = true;
  4758. // Remove all teachers from course.
  4759. $removeAllTeachersFromCourse = false;
  4760. }
  4761. }
  4762. foreach ($courses as $course) {
  4763. $courseArray = bracketsToArray($course);
  4764. $course_code = $courseArray[0];
  4765. if (CourseManager::course_exists($course_code)) {
  4766. $courseInfo = api_get_course_info($course_code);
  4767. $courseId = $courseInfo['real_id'];
  4768. // Adding the course to a session.
  4769. $sql = "INSERT IGNORE INTO $tbl_session_course
  4770. SET c_id = '$courseId', session_id='$session_id'";
  4771. Database::query($sql);
  4772. self::installCourse($session_id, $courseInfo['real_id']);
  4773. if ($debug) {
  4774. $logger->addInfo("Adding course '$course_code' to session #$session_id");
  4775. }
  4776. $course_counter++;
  4777. $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
  4778. $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
  4779. $course_users = explode(',', $course_users);
  4780. $course_coaches = explode(',', $course_coaches);
  4781. // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
  4782. $addTeachersToSession = true;
  4783. if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
  4784. $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
  4785. }
  4786. // If any user provided for a course, use the users array.
  4787. if (empty($course_users)) {
  4788. if (!empty($userList)) {
  4789. self::subscribe_users_to_session_course(
  4790. $userList,
  4791. $session_id,
  4792. $course_code
  4793. );
  4794. if ($debug) {
  4795. $msg = "Adding student list ".implode(', #', $userList)." to course: '$course_code' and session #$session_id";
  4796. $logger->addInfo($msg);
  4797. }
  4798. }
  4799. }
  4800. // Adding coaches to session course user.
  4801. if (!empty($course_coaches)) {
  4802. $savedCoaches = [];
  4803. // only edit if add_teachers_to_sessions_courses is set.
  4804. if ($addTeachersToSession) {
  4805. if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
  4806. // Adding course teachers as course session teachers.
  4807. $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code(
  4808. $course_code
  4809. );
  4810. if (!empty($alreadyAddedTeachers)) {
  4811. $teachersToAdd = [];
  4812. foreach ($alreadyAddedTeachers as $user) {
  4813. $teachersToAdd[] = $user['username'];
  4814. }
  4815. $course_coaches = array_merge(
  4816. $course_coaches,
  4817. $teachersToAdd
  4818. );
  4819. }
  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. // Just insert new coaches
  4825. self::updateCoaches(
  4826. $session_id,
  4827. $courseId,
  4828. [$coach_id],
  4829. false
  4830. );
  4831. if ($debug) {
  4832. $logger->addInfo("Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  4833. }
  4834. $savedCoaches[] = $coach_id;
  4835. } else {
  4836. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  4837. }
  4838. }
  4839. }
  4840. // Custom courses/session coaches
  4841. $teacherToAdd = null;
  4842. // Only one coach is added.
  4843. if ($onlyAddFirstCoachOrTeacher == true) {
  4844. if ($debug) {
  4845. $logger->addInfo("onlyAddFirstCoachOrTeacher : true");
  4846. }
  4847. foreach ($course_coaches as $course_coach) {
  4848. $coach_id = UserManager::get_user_id_from_username($course_coach);
  4849. if ($coach_id !== false) {
  4850. $teacherToAdd = $coach_id;
  4851. break;
  4852. }
  4853. }
  4854. // Un subscribe everyone that's not in the list.
  4855. $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
  4856. if (!empty($teacherList)) {
  4857. foreach ($teacherList as $teacher) {
  4858. if ($teacherToAdd != $teacher['user_id']) {
  4859. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  4860. WHERE
  4861. user_id = ".$teacher['user_id']." AND
  4862. c_id = '".$courseId."'
  4863. ";
  4864. $result = Database::query($sql);
  4865. $rows = Database::num_rows($result);
  4866. if ($rows > 0) {
  4867. $userCourseData = Database::fetch_array($result, 'ASSOC');
  4868. if (!empty($userCourseData)) {
  4869. $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
  4870. }
  4871. }
  4872. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  4873. WHERE
  4874. user_id = ".$teacher['user_id']." AND
  4875. c_id = '".$courseInfo['real_id']."'
  4876. ";
  4877. $result = Database::query($sql);
  4878. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4879. $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4880. }
  4881. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  4882. WHERE
  4883. user_id = ".$teacher['user_id']." AND
  4884. c_id = '".$courseInfo['real_id']."'
  4885. ";
  4886. $result = Database::query($sql);
  4887. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4888. $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4889. }
  4890. CourseManager::unsubscribe_user(
  4891. $teacher['user_id'],
  4892. $course_code
  4893. );
  4894. if ($debug) {
  4895. $logger->addInfo("Delete user #".$teacher['user_id']." from base course: $course_code");
  4896. }
  4897. }
  4898. }
  4899. }
  4900. if (!empty($teacherToAdd)) {
  4901. self::updateCoaches(
  4902. $session_id,
  4903. $courseId,
  4904. [$teacherToAdd],
  4905. true
  4906. );
  4907. if ($debug) {
  4908. $logger->addInfo("Add coach #$teacherToAdd to course $courseId and session $session_id");
  4909. }
  4910. $userCourseCategory = '';
  4911. if (isset($teacherBackupList[$teacherToAdd]) &&
  4912. isset($teacherBackupList[$teacherToAdd][$course_code])
  4913. ) {
  4914. $courseUserData = $teacherBackupList[$teacherToAdd][$course_code];
  4915. $userCourseCategory = $courseUserData['user_course_cat'];
  4916. }
  4917. CourseManager::subscribeUser(
  4918. $teacherToAdd,
  4919. $course_code,
  4920. COURSEMANAGER,
  4921. 0,
  4922. $userCourseCategory
  4923. );
  4924. if ($debug) {
  4925. $logger->addInfo("Subscribe user #$teacherToAdd as teacher in course $course_code with user userCourseCategory $userCourseCategory");
  4926. }
  4927. if (isset($groupBackup['user'][$teacherToAdd]) &&
  4928. isset($groupBackup['user'][$teacherToAdd][$course_code]) &&
  4929. !empty($groupBackup['user'][$teacherToAdd][$course_code])
  4930. ) {
  4931. foreach ($groupBackup['user'][$teacherToAdd][$course_code] as $data) {
  4932. $groupInfo = GroupManager::get_group_properties($data['group_id']);
  4933. GroupManager::subscribe_users(
  4934. $teacherToAdd,
  4935. $groupInfo,
  4936. $data['c_id']
  4937. );
  4938. }
  4939. }
  4940. if (isset($groupBackup['tutor'][$teacherToAdd]) &&
  4941. isset($groupBackup['tutor'][$teacherToAdd][$course_code]) &&
  4942. !empty($groupBackup['tutor'][$teacherToAdd][$course_code])
  4943. ) {
  4944. foreach ($groupBackup['tutor'][$teacherToAdd][$course_code] as $data) {
  4945. $groupInfo = GroupManager::get_group_properties($data['group_id']);
  4946. GroupManager::subscribe_tutors(
  4947. $teacherToAdd,
  4948. $groupInfo,
  4949. $data['c_id']
  4950. );
  4951. }
  4952. }
  4953. }
  4954. }
  4955. // See BT#6449#note-195
  4956. // All coaches are added.
  4957. if ($removeAllTeachersFromCourse) {
  4958. if ($debug) {
  4959. $logger->addInfo("removeAllTeachersFromCourse true");
  4960. }
  4961. $teacherToAdd = null;
  4962. foreach ($course_coaches as $course_coach) {
  4963. $coach_id = UserManager::get_user_id_from_username(
  4964. $course_coach
  4965. );
  4966. if ($coach_id !== false) {
  4967. $teacherToAdd[] = $coach_id;
  4968. }
  4969. }
  4970. if (!empty($teacherToAdd)) {
  4971. // Deleting all course teachers and adding the only coach as teacher.
  4972. $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
  4973. if (!empty($teacherList)) {
  4974. foreach ($teacherList as $teacher) {
  4975. if (!in_array($teacher['user_id'], $teacherToAdd)) {
  4976. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  4977. WHERE
  4978. user_id = ".$teacher['user_id']." AND
  4979. c_id = '".$courseId."'
  4980. ";
  4981. $result = Database::query($sql);
  4982. $rows = Database::num_rows($result);
  4983. if ($rows > 0) {
  4984. $userCourseData = Database::fetch_array($result, 'ASSOC');
  4985. if (!empty($userCourseData)) {
  4986. $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
  4987. }
  4988. }
  4989. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  4990. WHERE
  4991. user_id = ".$teacher['user_id']." AND
  4992. c_id = '".$courseInfo['real_id']."'
  4993. ";
  4994. $result = Database::query($sql);
  4995. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4996. $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4997. }
  4998. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  4999. WHERE
  5000. user_id = ".$teacher['user_id']." AND
  5001. c_id = '".$courseInfo['real_id']."'
  5002. ";
  5003. $result = Database::query($sql);
  5004. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  5005. $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  5006. }
  5007. CourseManager::unsubscribe_user(
  5008. $teacher['user_id'],
  5009. $course_code
  5010. );
  5011. if ($debug) {
  5012. $logger->addInfo("Delete user #".$teacher['user_id']." from base course: $course_code");
  5013. }
  5014. }
  5015. }
  5016. }
  5017. foreach ($teacherToAdd as $teacherId) {
  5018. $userCourseCategory = '';
  5019. if (isset($teacherBackupList[$teacherId]) &&
  5020. isset($teacherBackupList[$teacherId][$course_code])
  5021. ) {
  5022. $courseUserData = $teacherBackupList[$teacherId][$course_code];
  5023. $userCourseCategory = $courseUserData['user_course_cat'];
  5024. }
  5025. CourseManager::subscribeUser(
  5026. $teacherId,
  5027. $course_code,
  5028. COURSEMANAGER,
  5029. 0,
  5030. $userCourseCategory
  5031. );
  5032. if ($debug) {
  5033. $logger->addInfo("Add user as teacher #".$teacherId." in base course: $course_code with userCourseCategory: $userCourseCategory");
  5034. }
  5035. if (isset($groupBackup['user'][$teacherId]) &&
  5036. isset($groupBackup['user'][$teacherId][$course_code]) &&
  5037. !empty($groupBackup['user'][$teacherId][$course_code])
  5038. ) {
  5039. foreach ($groupBackup['user'][$teacherId][$course_code] as $data) {
  5040. $groupInfo = GroupManager::get_group_properties($data['group_id']);
  5041. GroupManager::subscribe_users(
  5042. $teacherId,
  5043. $groupInfo,
  5044. $data['c_id']
  5045. );
  5046. }
  5047. }
  5048. if (isset($groupBackup['tutor'][$teacherId]) &&
  5049. isset($groupBackup['tutor'][$teacherId][$course_code]) &&
  5050. !empty($groupBackup['tutor'][$teacherId][$course_code])
  5051. ) {
  5052. foreach ($groupBackup['tutor'][$teacherId][$course_code] as $data) {
  5053. $groupInfo = GroupManager::get_group_properties($data['group_id']);
  5054. GroupManager::subscribe_tutors(
  5055. $teacherId,
  5056. $groupInfo,
  5057. $data['c_id']
  5058. );
  5059. }
  5060. }
  5061. }
  5062. }
  5063. }
  5064. // Continue default behaviour.
  5065. if ($onlyAddFirstCoachOrTeacher == false) {
  5066. // Checking one more time see BT#6449#note-149
  5067. $coaches = self::getCoachesByCourseSession($session_id, $courseId);
  5068. // Update coaches if only there's 1 course see BT#6449#note-189
  5069. if (empty($coaches) || count($courses) == 1) {
  5070. foreach ($course_coaches as $course_coach) {
  5071. $course_coach = trim($course_coach);
  5072. $coach_id = UserManager::get_user_id_from_username($course_coach);
  5073. if ($coach_id !== false) {
  5074. // Just insert new coaches
  5075. self::updateCoaches(
  5076. $session_id,
  5077. $courseId,
  5078. [$coach_id],
  5079. false
  5080. );
  5081. if ($debug) {
  5082. $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  5083. }
  5084. $savedCoaches[] = $coach_id;
  5085. } else {
  5086. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  5087. }
  5088. }
  5089. }
  5090. }
  5091. }
  5092. // Adding Students, updating relationship "Session - Course - User".
  5093. $course_users = array_filter($course_users);
  5094. if (!empty($course_users)) {
  5095. foreach ($course_users as $user) {
  5096. $user_id = UserManager::get_user_id_from_username($user);
  5097. if ($user_id !== false) {
  5098. self::subscribe_users_to_session_course(
  5099. [$user_id],
  5100. $session_id,
  5101. $course_code
  5102. );
  5103. if ($debug) {
  5104. $logger->addInfo("Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
  5105. }
  5106. } else {
  5107. $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
  5108. }
  5109. }
  5110. }
  5111. $inserted_in_course[$course_code] = $courseInfo['title'];
  5112. }
  5113. }
  5114. $access_url_id = api_get_current_access_url_id();
  5115. UrlManager::add_session_to_url($session_id, $access_url_id);
  5116. $sql = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter'
  5117. WHERE id = '$session_id'";
  5118. Database::query($sql);
  5119. self::addClassesByName($session_id, $classes, false);
  5120. if ($debug) {
  5121. $logger->addInfo("End process session #$session_id -------------------- ");
  5122. }
  5123. }
  5124. if (!empty($report)) {
  5125. if ($debug) {
  5126. $logger->addInfo("--Summary--");
  5127. foreach ($report as $line) {
  5128. $logger->addInfo($line);
  5129. }
  5130. }
  5131. }
  5132. }
  5133. return [
  5134. 'error_message' => $error_message,
  5135. 'session_counter' => $session_counter,
  5136. 'session_list' => $sessionList,
  5137. ];
  5138. }
  5139. /**
  5140. * @param int $sessionId
  5141. * @param int $courseId
  5142. *
  5143. * @return array
  5144. */
  5145. public static function getCoachesByCourseSession($sessionId, $courseId)
  5146. {
  5147. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5148. $sessionId = (int) $sessionId;
  5149. $courseId = (int) $courseId;
  5150. $sql = "SELECT user_id FROM $table
  5151. WHERE
  5152. session_id = '$sessionId' AND
  5153. c_id = '$courseId' AND
  5154. status = 2";
  5155. $result = Database::query($sql);
  5156. $coaches = [];
  5157. if (Database::num_rows($result) > 0) {
  5158. while ($row = Database::fetch_array($result)) {
  5159. $coaches[] = $row['user_id'];
  5160. }
  5161. }
  5162. return $coaches;
  5163. }
  5164. /**
  5165. * @param int $sessionId
  5166. * @param int $courseId
  5167. * @param string $separator
  5168. *
  5169. * @return string
  5170. */
  5171. public static function getCoachesByCourseSessionToString(
  5172. $sessionId,
  5173. $courseId,
  5174. $separator = ''
  5175. ) {
  5176. $coaches = self::getCoachesByCourseSession($sessionId, $courseId);
  5177. $list = [];
  5178. if (!empty($coaches)) {
  5179. foreach ($coaches as $coachId) {
  5180. $userInfo = api_get_user_info($coachId);
  5181. if ($userInfo) {
  5182. $list[] = $userInfo['complete_name'];
  5183. }
  5184. }
  5185. }
  5186. $separator = empty($separator) ? CourseManager::USER_SEPARATOR : $separator;
  5187. return array_to_string($list, $separator);
  5188. }
  5189. /**
  5190. * Get all coaches added in the session - course relationship.
  5191. *
  5192. * @param int $sessionId
  5193. *
  5194. * @return array
  5195. */
  5196. public static function getCoachesBySession($sessionId)
  5197. {
  5198. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5199. $sessionId = intval($sessionId);
  5200. $sql = "SELECT DISTINCT user_id
  5201. FROM $table
  5202. WHERE session_id = '$sessionId' AND status = 2";
  5203. $result = Database::query($sql);
  5204. $coaches = [];
  5205. if (Database::num_rows($result) > 0) {
  5206. while ($row = Database::fetch_array($result)) {
  5207. $coaches[] = $row['user_id'];
  5208. }
  5209. }
  5210. return $coaches;
  5211. }
  5212. /**
  5213. * @param int $userId
  5214. *
  5215. * @return array
  5216. */
  5217. public static function getAllCoursesFromAllSessionFromDrh($userId)
  5218. {
  5219. $sessions = self::get_sessions_followed_by_drh($userId);
  5220. $coursesFromSession = [];
  5221. if (!empty($sessions)) {
  5222. foreach ($sessions as $session) {
  5223. $courseList = self::get_course_list_by_session_id($session['id']);
  5224. foreach ($courseList as $course) {
  5225. $coursesFromSession[] = $course['code'];
  5226. }
  5227. }
  5228. }
  5229. return $coursesFromSession;
  5230. }
  5231. /**
  5232. * getAllCoursesFromAllSessions.
  5233. *
  5234. * @return array
  5235. */
  5236. public static function getAllCoursesFromAllSessions()
  5237. {
  5238. $sessions = self::get_sessions_list();
  5239. $coursesFromSession = [];
  5240. if (!empty($sessions)) {
  5241. foreach ($sessions as $session) {
  5242. $courseList = self::get_course_list_by_session_id($session['id']);
  5243. foreach ($courseList as $course) {
  5244. $coursesFromSession[$course['code'].':'.$session['id']] = $course['visual_code'].' - '.$course['title'].' ('.$session['name'].')';
  5245. }
  5246. }
  5247. }
  5248. return $coursesFromSession;
  5249. }
  5250. /**
  5251. * Return user id list or count of users depending of the $getCount parameter.
  5252. *
  5253. * @param string $status
  5254. * @param int $userId
  5255. * @param bool $getCount
  5256. * @param int $from
  5257. * @param int $numberItems
  5258. * @param int $column
  5259. * @param string $direction
  5260. * @param string $keyword
  5261. * @param string $active
  5262. * @param string $lastConnectionDate
  5263. * @param array $sessionIdList
  5264. * @param array $studentIdList
  5265. * @param int $filterByStatus
  5266. *
  5267. * @return array|int
  5268. */
  5269. public static function getAllUsersFromCoursesFromAllSessionFromStatus(
  5270. $status,
  5271. $userId,
  5272. $getCount = false,
  5273. $from = null,
  5274. $numberItems = null,
  5275. $column = 1,
  5276. $direction = 'asc',
  5277. $keyword = null,
  5278. $active = null,
  5279. $lastConnectionDate = null,
  5280. $sessionIdList = [],
  5281. $studentIdList = [],
  5282. $filterByStatus = null
  5283. ) {
  5284. $filterByStatus = (int) $filterByStatus;
  5285. $userId = (int) $userId;
  5286. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  5287. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  5288. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  5289. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5290. $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  5291. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  5292. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5293. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  5294. $direction = in_array(strtolower($direction), ['asc', 'desc']) ? $direction : 'asc';
  5295. $column = Database::escape_string($column);
  5296. $limitCondition = '';
  5297. if (isset($from) && isset($numberItems)) {
  5298. $from = (int) $from;
  5299. $numberItems = (int) $numberItems;
  5300. $limitCondition = "LIMIT $from, $numberItems";
  5301. }
  5302. $urlId = api_get_current_access_url_id();
  5303. $sessionConditions = '';
  5304. $courseConditions = '';
  5305. $userConditions = '';
  5306. if (isset($active)) {
  5307. $active = (int) $active;
  5308. $userConditions .= " AND active = $active";
  5309. }
  5310. $courseList = CourseManager::get_courses_followed_by_drh($userId, DRH);
  5311. if (!empty($courseList)) {
  5312. $courseIdList = array_column($courseList, 'id');
  5313. $courseConditions = ' AND c.id IN ("'.implode('","', $courseIdList).'")';
  5314. }
  5315. $userConditionsFromDrh = '';
  5316. // Classic DRH
  5317. if (empty($studentIdList)) {
  5318. $studentListSql = UserManager::get_users_followed_by_drh(
  5319. $userId,
  5320. $filterByStatus,
  5321. true,
  5322. false
  5323. );
  5324. if (!empty($studentListSql)) {
  5325. $studentIdList = array_keys($studentListSql);
  5326. $studentListSql = "'".implode("','", $studentIdList)."'";
  5327. }
  5328. } else {
  5329. $studentIdList = array_map('intval', $studentIdList);
  5330. $studentListSql = "'".implode("','", $studentIdList)."'";
  5331. }
  5332. if (!empty($studentListSql)) {
  5333. $userConditionsFromDrh = " AND u.user_id IN ($studentListSql) ";
  5334. }
  5335. switch ($status) {
  5336. case 'drh':
  5337. break;
  5338. case 'drh_all':
  5339. // Show all by DRH
  5340. if (empty($sessionIdList)) {
  5341. $sessionsListSql = self::get_sessions_followed_by_drh(
  5342. $userId,
  5343. null,
  5344. null,
  5345. false,
  5346. true,
  5347. true
  5348. );
  5349. } else {
  5350. $sessionIdList = array_map('intval', $sessionIdList);
  5351. $sessionsListSql = "'".implode("','", $sessionIdList)."'";
  5352. }
  5353. if (!empty($sessionsListSql)) {
  5354. $sessionConditions = " AND s.id IN ($sessionsListSql) ";
  5355. }
  5356. break;
  5357. case 'session_admin':
  5358. $sessionConditions = " AND s.id_coach = $userId ";
  5359. $userConditionsFromDrh = '';
  5360. break;
  5361. case 'admin':
  5362. break;
  5363. case 'teacher':
  5364. $sessionConditions = " AND s.id_coach = $userId ";
  5365. $userConditionsFromDrh = '';
  5366. break;
  5367. }
  5368. $select = 'SELECT DISTINCT u.* ';
  5369. $masterSelect = 'SELECT DISTINCT user_id FROM ';
  5370. if ($getCount) {
  5371. $select = 'SELECT DISTINCT u.user_id ';
  5372. $masterSelect = 'SELECT COUNT(DISTINCT(user_id)) as count FROM ';
  5373. }
  5374. if (!empty($filterByStatus)) {
  5375. $userConditions .= " AND u.status = $filterByStatus";
  5376. }
  5377. if (!empty($lastConnectionDate)) {
  5378. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  5379. $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
  5380. }
  5381. if (!empty($keyword)) {
  5382. $keyword = Database::escape_string($keyword);
  5383. $userConditions .= " AND (
  5384. u.username LIKE '%$keyword%' OR
  5385. u.firstname LIKE '%$keyword%' OR
  5386. u.lastname LIKE '%$keyword%' OR
  5387. u.official_code LIKE '%$keyword%' OR
  5388. u.email LIKE '%$keyword%'
  5389. )";
  5390. }
  5391. $where = " WHERE
  5392. access_url_id = $urlId
  5393. $userConditions
  5394. ";
  5395. $userUnion = '';
  5396. if (!empty($userConditionsFromDrh)) {
  5397. $userUnion = "
  5398. UNION (
  5399. $select
  5400. FROM $tbl_user u
  5401. INNER JOIN $tbl_user_rel_access_url url ON (url.user_id = u.id)
  5402. $where
  5403. $userConditionsFromDrh
  5404. )";
  5405. }
  5406. $sql = "$masterSelect (
  5407. ($select
  5408. FROM $tbl_session s
  5409. INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.session_id)
  5410. INNER JOIN $tbl_user u ON (u.user_id = su.user_id)
  5411. INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
  5412. $where
  5413. $sessionConditions
  5414. $userConditionsFromDrh
  5415. ) UNION (
  5416. $select
  5417. FROM $tbl_course c
  5418. INNER JOIN $tbl_course_user cu ON (cu.c_id = c.id)
  5419. INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
  5420. INNER JOIN $tbl_course_rel_access_url url ON (url.c_id = c.id)
  5421. $where
  5422. $courseConditions
  5423. $userConditionsFromDrh
  5424. ) $userUnion
  5425. ) as t1
  5426. ";
  5427. if ($getCount) {
  5428. $result = Database::query($sql);
  5429. $count = 0;
  5430. if (Database::num_rows($result)) {
  5431. $rows = Database::fetch_array($result);
  5432. $count = $rows['count'];
  5433. }
  5434. return $count;
  5435. }
  5436. if (!empty($column) && !empty($direction)) {
  5437. $column = str_replace('u.', '', $column);
  5438. $sql .= " ORDER BY $column $direction ";
  5439. }
  5440. $sql .= $limitCondition;
  5441. $result = Database::query($sql);
  5442. $result = Database::store_result($result);
  5443. return $result;
  5444. }
  5445. /**
  5446. * @param int $sessionId
  5447. * @param int $courseId
  5448. * @param array $coachList
  5449. * @param bool $deleteCoachesNotInList
  5450. */
  5451. public static function updateCoaches(
  5452. $sessionId,
  5453. $courseId,
  5454. $coachList,
  5455. $deleteCoachesNotInList = false
  5456. ) {
  5457. $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseId);
  5458. if (!empty($coachList)) {
  5459. foreach ($coachList as $userId) {
  5460. self::set_coach_to_course_session($userId, $sessionId, $courseId);
  5461. }
  5462. }
  5463. if ($deleteCoachesNotInList) {
  5464. if (!empty($coachList)) {
  5465. $coachesToDelete = array_diff($currentCoaches, $coachList);
  5466. } else {
  5467. $coachesToDelete = $currentCoaches;
  5468. }
  5469. if (!empty($coachesToDelete)) {
  5470. foreach ($coachesToDelete as $userId) {
  5471. self::set_coach_to_course_session(
  5472. $userId,
  5473. $sessionId,
  5474. $courseId,
  5475. true
  5476. );
  5477. }
  5478. }
  5479. }
  5480. }
  5481. /**
  5482. * @param array $sessions
  5483. * @param array $sessionsDestination
  5484. *
  5485. * @return array
  5486. */
  5487. public static function copyStudentsFromSession($sessions, $sessionsDestination)
  5488. {
  5489. $messages = [];
  5490. if (!empty($sessions)) {
  5491. foreach ($sessions as $sessionId) {
  5492. $sessionInfo = self::fetch($sessionId);
  5493. $userList = self::get_users_by_session($sessionId, 0);
  5494. if (!empty($userList)) {
  5495. $newUserList = [];
  5496. $userToString = null;
  5497. foreach ($userList as $userInfo) {
  5498. $newUserList[] = $userInfo['user_id'];
  5499. $userToString .= $userInfo['firstname'].' '.$userInfo['lastname'].'<br />';
  5500. }
  5501. if (!empty($sessionsDestination)) {
  5502. foreach ($sessionsDestination as $sessionDestinationId) {
  5503. $sessionDestinationInfo = self::fetch($sessionDestinationId);
  5504. $messages[] = Display::return_message(
  5505. sprintf(
  5506. get_lang(
  5507. 'AddingStudentsFromSessionXToSessionY'
  5508. ),
  5509. $sessionInfo['name'],
  5510. $sessionDestinationInfo['name']
  5511. ),
  5512. 'info',
  5513. false
  5514. );
  5515. if ($sessionId == $sessionDestinationId) {
  5516. $messages[] = Display::return_message(
  5517. sprintf(
  5518. get_lang('SessionXSkipped'),
  5519. $sessionDestinationId
  5520. ),
  5521. 'warning',
  5522. false
  5523. );
  5524. continue;
  5525. }
  5526. $messages[] = Display::return_message(get_lang('StudentList').'<br />'.$userToString, 'info', false);
  5527. self::subscribeUsersToSession(
  5528. $sessionDestinationId,
  5529. $newUserList,
  5530. SESSION_VISIBLE_READ_ONLY,
  5531. false
  5532. );
  5533. }
  5534. } else {
  5535. $messages[] = Display::return_message(get_lang('NoDestinationSessionProvided'), 'warning');
  5536. }
  5537. } else {
  5538. $messages[] = Display::return_message(
  5539. get_lang('NoStudentsFoundForSession').' #'.$sessionInfo['name'],
  5540. 'warning'
  5541. );
  5542. }
  5543. }
  5544. } else {
  5545. $messages[] = Display::return_message(get_lang('NoData'), 'warning');
  5546. }
  5547. return $messages;
  5548. }
  5549. /**
  5550. * Assign coaches of a session(s) as teachers to a given course (or courses).
  5551. *
  5552. * @param array A list of session IDs
  5553. * @param array A list of course IDs
  5554. *
  5555. * @return string
  5556. */
  5557. public static function copyCoachesFromSessionToCourse($sessions, $courses)
  5558. {
  5559. $coachesPerSession = [];
  5560. foreach ($sessions as $sessionId) {
  5561. $coaches = self::getCoachesBySession($sessionId);
  5562. $coachesPerSession[$sessionId] = $coaches;
  5563. }
  5564. $result = [];
  5565. if (!empty($courses)) {
  5566. foreach ($courses as $courseId) {
  5567. $courseInfo = api_get_course_info_by_id($courseId);
  5568. foreach ($coachesPerSession as $sessionId => $coachList) {
  5569. CourseManager::updateTeachers(
  5570. $courseInfo,
  5571. $coachList,
  5572. false,
  5573. false,
  5574. false
  5575. );
  5576. $result[$courseInfo['code']][$sessionId] = $coachList;
  5577. }
  5578. }
  5579. }
  5580. $sessionUrl = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session=';
  5581. $htmlResult = null;
  5582. if (!empty($result)) {
  5583. foreach ($result as $courseCode => $data) {
  5584. $url = api_get_course_url($courseCode);
  5585. $htmlResult .= sprintf(
  5586. get_lang('CoachesSubscribedAsATeacherInCourseX'),
  5587. Display::url($courseCode, $url, ['target' => '_blank'])
  5588. );
  5589. foreach ($data as $sessionId => $coachList) {
  5590. $sessionInfo = self::fetch($sessionId);
  5591. $htmlResult .= '<br />';
  5592. $htmlResult .= Display::url(
  5593. get_lang('Session').': '.$sessionInfo['name'].' <br />',
  5594. $sessionUrl.$sessionId,
  5595. ['target' => '_blank']
  5596. );
  5597. $teacherList = [];
  5598. foreach ($coachList as $coachId) {
  5599. $userInfo = api_get_user_info($coachId);
  5600. $teacherList[] = $userInfo['complete_name'];
  5601. }
  5602. if (!empty($teacherList)) {
  5603. $htmlResult .= implode(', ', $teacherList);
  5604. } else {
  5605. $htmlResult .= get_lang('NothingToAdd');
  5606. }
  5607. }
  5608. $htmlResult .= '<br />';
  5609. }
  5610. $htmlResult = Display::return_message($htmlResult, 'normal', false);
  5611. }
  5612. return $htmlResult;
  5613. }
  5614. /**
  5615. * @param string $keyword
  5616. * @param string $active
  5617. * @param string $lastConnectionDate
  5618. * @param array $sessionIdList
  5619. * @param array $studentIdList
  5620. * @param int $filterUserStatus STUDENT|COURSEMANAGER constants
  5621. *
  5622. * @return array|int
  5623. */
  5624. public static function getCountUserTracking(
  5625. $keyword = null,
  5626. $active = null,
  5627. $lastConnectionDate = null,
  5628. $sessionIdList = [],
  5629. $studentIdList = [],
  5630. $filterUserStatus = null
  5631. ) {
  5632. $userId = api_get_user_id();
  5633. $drhLoaded = false;
  5634. if (api_is_drh()) {
  5635. if (api_drh_can_access_all_session_content()) {
  5636. $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
  5637. 'drh_all',
  5638. $userId,
  5639. true,
  5640. null,
  5641. null,
  5642. null,
  5643. null,
  5644. $keyword,
  5645. $active,
  5646. $lastConnectionDate,
  5647. $sessionIdList,
  5648. $studentIdList,
  5649. $filterUserStatus
  5650. );
  5651. $drhLoaded = true;
  5652. }
  5653. }
  5654. if ($drhLoaded == false) {
  5655. $count = UserManager::getUsersFollowedByUser(
  5656. $userId,
  5657. $filterUserStatus,
  5658. false,
  5659. false,
  5660. true,
  5661. null,
  5662. null,
  5663. null,
  5664. null,
  5665. $active,
  5666. $lastConnectionDate,
  5667. api_is_student_boss() ? STUDENT_BOSS : COURSEMANAGER,
  5668. $keyword
  5669. );
  5670. }
  5671. return $count;
  5672. }
  5673. /**
  5674. * Get teachers followed by a user.
  5675. *
  5676. * @param int $userId
  5677. * @param int $active
  5678. * @param string $lastConnectionDate
  5679. * @param bool $getCount
  5680. * @param array $sessionIdList
  5681. *
  5682. * @return array|int
  5683. */
  5684. public static function getTeacherTracking(
  5685. $userId,
  5686. $active = 1,
  5687. $lastConnectionDate = null,
  5688. $getCount = false,
  5689. $sessionIdList = []
  5690. ) {
  5691. $teacherListId = [];
  5692. if (api_is_drh() || api_is_platform_admin()) {
  5693. // Followed teachers by drh
  5694. if (api_drh_can_access_all_session_content()) {
  5695. if (empty($sessionIdList)) {
  5696. $sessions = self::get_sessions_followed_by_drh($userId);
  5697. $sessionIdList = [];
  5698. foreach ($sessions as $session) {
  5699. $sessionIdList[] = $session['id'];
  5700. }
  5701. }
  5702. $sessionIdList = array_map('intval', $sessionIdList);
  5703. $sessionToString = implode("', '", $sessionIdList);
  5704. $course = Database::get_main_table(TABLE_MAIN_COURSE);
  5705. $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  5706. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5707. // Select the teachers.
  5708. $sql = "SELECT DISTINCT(cu.user_id)
  5709. FROM $course c
  5710. INNER JOIN $sessionCourse src
  5711. ON c.id = src.c_id
  5712. INNER JOIN $courseUser cu
  5713. ON (cu.c_id = c.id)
  5714. WHERE src.session_id IN ('$sessionToString') AND cu.status = 1";
  5715. $result = Database::query($sql);
  5716. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5717. $teacherListId[$row['user_id']] = $row['user_id'];
  5718. }
  5719. } else {
  5720. $teacherResult = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
  5721. foreach ($teacherResult as $userInfo) {
  5722. $teacherListId[] = $userInfo['user_id'];
  5723. }
  5724. }
  5725. }
  5726. if (!empty($teacherListId)) {
  5727. $tableUser = Database::get_main_table(TABLE_MAIN_USER);
  5728. $select = "SELECT DISTINCT u.* ";
  5729. if ($getCount) {
  5730. $select = "SELECT count(DISTINCT(u.user_id)) as count";
  5731. }
  5732. $sql = "$select FROM $tableUser u";
  5733. if (!empty($lastConnectionDate)) {
  5734. $tableLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  5735. //$sql .= " INNER JOIN $tableLogin l ON (l.login_user_id = u.user_id) ";
  5736. }
  5737. $active = intval($active);
  5738. $teacherListId = implode("','", $teacherListId);
  5739. $where = " WHERE u.active = $active AND u.user_id IN ('$teacherListId') ";
  5740. if (!empty($lastConnectionDate)) {
  5741. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  5742. //$where .= " AND l.login_date <= '$lastConnectionDate' ";
  5743. }
  5744. $sql .= $where;
  5745. $result = Database::query($sql);
  5746. if (Database::num_rows($result)) {
  5747. if ($getCount) {
  5748. $row = Database::fetch_array($result);
  5749. return $row['count'];
  5750. } else {
  5751. return Database::store_result($result, 'ASSOC');
  5752. }
  5753. }
  5754. }
  5755. return 0;
  5756. }
  5757. /**
  5758. * Get the list of course tools that have to be dealt with in case of
  5759. * registering any course to a session.
  5760. *
  5761. * @return array The list of tools to be dealt with (literal names)
  5762. */
  5763. public static function getCourseToolToBeManaged()
  5764. {
  5765. return [
  5766. 'courseDescription',
  5767. 'courseIntroduction',
  5768. ];
  5769. }
  5770. /**
  5771. * Calls the methods bound to each tool when a course is registered into a session.
  5772. *
  5773. * @param int $sessionId
  5774. * @param int $courseId
  5775. *
  5776. * @return bool
  5777. */
  5778. public static function installCourse($sessionId, $courseId)
  5779. {
  5780. return true;
  5781. $toolList = self::getCourseToolToBeManaged();
  5782. foreach ($toolList as $tool) {
  5783. $method = 'add'.$tool;
  5784. if (method_exists(get_class(), $method)) {
  5785. self::$method($sessionId, $courseId);
  5786. }
  5787. }
  5788. }
  5789. /**
  5790. * Calls the methods bound to each tool when a course is unregistered from
  5791. * a session.
  5792. *
  5793. * @param int $sessionId
  5794. * @param int $courseId
  5795. */
  5796. public static function unInstallCourse($sessionId, $courseId)
  5797. {
  5798. return true;
  5799. $toolList = self::getCourseToolToBeManaged();
  5800. foreach ($toolList as $tool) {
  5801. $method = 'remove'.$tool;
  5802. if (method_exists(get_class(), $method)) {
  5803. self::$method($sessionId, $courseId);
  5804. }
  5805. }
  5806. }
  5807. /**
  5808. * @param array $userSessionList format see self::importSessionDrhCSV()
  5809. * @param bool $sendEmail
  5810. * @param bool $removeOldRelationShips
  5811. */
  5812. public static function subscribeDrhToSessionList(
  5813. $userSessionList,
  5814. $sendEmail,
  5815. $removeOldRelationShips
  5816. ) {
  5817. if (!empty($userSessionList)) {
  5818. foreach ($userSessionList as $userId => $data) {
  5819. $sessionList = [];
  5820. foreach ($data['session_list'] as $sessionInfo) {
  5821. $sessionList[] = $sessionInfo['session_id'];
  5822. }
  5823. $userInfo = $data['user_info'];
  5824. self::subscribeSessionsToDrh(
  5825. $userInfo,
  5826. $sessionList,
  5827. $sendEmail,
  5828. $removeOldRelationShips
  5829. );
  5830. }
  5831. }
  5832. }
  5833. /**
  5834. * @param array $userSessionList format see self::importSessionDrhCSV()
  5835. *
  5836. * @return string
  5837. */
  5838. public static function checkSubscribeDrhToSessionList($userSessionList)
  5839. {
  5840. $message = null;
  5841. if (!empty($userSessionList)) {
  5842. if (!empty($userSessionList)) {
  5843. foreach ($userSessionList as $userId => $data) {
  5844. $userInfo = $data['user_info'];
  5845. $sessionListSubscribed = self::get_sessions_followed_by_drh($userId);
  5846. if (!empty($sessionListSubscribed)) {
  5847. $sessionListSubscribed = array_keys($sessionListSubscribed);
  5848. }
  5849. $sessionList = [];
  5850. if (!empty($data['session_list'])) {
  5851. foreach ($data['session_list'] as $sessionInfo) {
  5852. if (in_array($sessionInfo['session_id'], $sessionListSubscribed)) {
  5853. $sessionList[] = $sessionInfo['session_info']['name'];
  5854. }
  5855. }
  5856. }
  5857. $message .= '<strong>'.get_lang('User').'</strong>: ';
  5858. $message .= $userInfo['complete_name_with_username'].' <br />';
  5859. if (!in_array($userInfo['status'], [DRH]) && !api_is_platform_admin_by_id($userInfo['user_id'])) {
  5860. $message .= get_lang('UserMustHaveTheDrhRole').'<br />';
  5861. continue;
  5862. }
  5863. if (!empty($sessionList)) {
  5864. $message .= '<strong>'.get_lang('Sessions').':</strong> <br />';
  5865. $message .= implode(', ', $sessionList).'<br /><br />';
  5866. } else {
  5867. $message .= get_lang('NoSessionProvided').' <br /><br />';
  5868. }
  5869. }
  5870. }
  5871. }
  5872. return $message;
  5873. }
  5874. /**
  5875. * @param string $file
  5876. * @param bool $sendEmail
  5877. * @param bool $removeOldRelationShips
  5878. *
  5879. * @return string
  5880. */
  5881. public static function importSessionDrhCSV($file, $sendEmail, $removeOldRelationShips)
  5882. {
  5883. $list = Import::csv_reader($file);
  5884. if (!empty($list)) {
  5885. $userSessionList = [];
  5886. foreach ($list as $data) {
  5887. $userInfo = api_get_user_info_from_username($data['Username']);
  5888. $sessionInfo = self::get_session_by_name($data['SessionName']);
  5889. if (empty($sessionInfo)) {
  5890. Display::addFlash(Display::return_message(get_lang('NoSessionId').' - '.$data['SessionName'], 'warning'));
  5891. }
  5892. if (empty($userInfo)) {
  5893. Display::addFlash(Display::return_message(get_lang('UserDoesNotExist').' - '.$data['Username'], 'warning'));
  5894. }
  5895. if (!empty($userInfo) && !empty($sessionInfo)) {
  5896. $userSessionList[$userInfo['user_id']]['session_list'][] = [
  5897. 'session_id' => $sessionInfo['id'],
  5898. 'session_info' => $sessionInfo,
  5899. ];
  5900. $userSessionList[$userInfo['user_id']]['user_info'] = $userInfo;
  5901. }
  5902. }
  5903. self::subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips);
  5904. return self::checkSubscribeDrhToSessionList($userSessionList);
  5905. }
  5906. }
  5907. /**
  5908. * Courses re-ordering in resume_session.php flag see BT#8316.
  5909. */
  5910. public static function orderCourseIsEnabled()
  5911. {
  5912. $sessionCourseOrder = api_get_setting('session_course_ordering');
  5913. if ($sessionCourseOrder === 'true') {
  5914. return true;
  5915. }
  5916. return false;
  5917. }
  5918. /**
  5919. * @param string $direction (up/down)
  5920. * @param int $sessionId
  5921. * @param int $courseId
  5922. *
  5923. * @return bool
  5924. */
  5925. public static function move($direction, $sessionId, $courseId)
  5926. {
  5927. if (!self::orderCourseIsEnabled()) {
  5928. return false;
  5929. }
  5930. $sessionId = intval($sessionId);
  5931. $courseId = intval($courseId);
  5932. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  5933. $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
  5934. $position = [];
  5935. $count = 0;
  5936. foreach ($courseList as $course) {
  5937. if ($course['position'] == '') {
  5938. $course['position'] = $count;
  5939. }
  5940. $position[$course['code']] = $course['position'];
  5941. // Saving current order.
  5942. $sql = "UPDATE $table SET position = $count
  5943. WHERE session_id = $sessionId AND c_id = '".$course['real_id']."'";
  5944. Database::query($sql);
  5945. $count++;
  5946. }
  5947. // Loading new positions.
  5948. $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
  5949. $found = false;
  5950. switch ($direction) {
  5951. case 'up':
  5952. $courseList = array_reverse($courseList);
  5953. break;
  5954. case 'down':
  5955. break;
  5956. }
  5957. foreach ($courseList as $course) {
  5958. if ($found) {
  5959. $nextId = $course['real_id'];
  5960. $nextOrder = $course['position'];
  5961. break;
  5962. }
  5963. if ($courseId == $course['real_id']) {
  5964. $thisCourseCode = $course['real_id'];
  5965. $thisOrder = $course['position'];
  5966. $found = true;
  5967. }
  5968. }
  5969. $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."'
  5970. WHERE session_id = $sessionId AND c_id = $thisCourseCode";
  5971. Database::query($sql1);
  5972. $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."'
  5973. WHERE session_id = $sessionId AND c_id = $nextId";
  5974. Database::query($sql2);
  5975. return true;
  5976. }
  5977. /**
  5978. * @param int $sessionId
  5979. * @param int $courseId
  5980. *
  5981. * @return bool
  5982. */
  5983. public static function moveUp($sessionId, $courseId)
  5984. {
  5985. return self::move('up', $sessionId, $courseId);
  5986. }
  5987. /**
  5988. * @param int $sessionId
  5989. * @param string $courseCode
  5990. *
  5991. * @return bool
  5992. */
  5993. public static function moveDown($sessionId, $courseCode)
  5994. {
  5995. return self::move('down', $sessionId, $courseCode);
  5996. }
  5997. /**
  5998. * Use the session duration to allow/block user access see BT#8317
  5999. * Needs these DB changes
  6000. * ALTER TABLE session ADD COLUMN duration int;
  6001. * ALTER TABLE session_rel_user ADD COLUMN duration int;.
  6002. */
  6003. public static function durationPerUserIsEnabled()
  6004. {
  6005. return api_get_configuration_value('session_duration_feature');
  6006. }
  6007. /**
  6008. * Returns the number of days the student has left in a session when using
  6009. * sessions durations.
  6010. *
  6011. * @param array $sessionInfo
  6012. * @param int $userId
  6013. *
  6014. * @return int
  6015. */
  6016. public static function getDayLeftInSession(array $sessionInfo, $userId)
  6017. {
  6018. $sessionId = $sessionInfo['id'];
  6019. $subscription = self::getUserSession($userId, $sessionId);
  6020. $duration = empty($subscription['duration'])
  6021. ? $sessionInfo['duration']
  6022. : $sessionInfo['duration'] + $subscription['duration'];
  6023. // Get an array with the details of the first access of the student to
  6024. // this session
  6025. $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
  6026. $sessionId,
  6027. $userId
  6028. );
  6029. $currentTime = time();
  6030. // If no previous access, return false
  6031. if (count($courseAccess) == 0) {
  6032. return $duration;
  6033. }
  6034. $firstAccess = api_strtotime($courseAccess['login_course_date'], 'UTC');
  6035. $endDateInSeconds = $firstAccess + $duration * 24 * 60 * 60;
  6036. $leftDays = round(($endDateInSeconds - $currentTime) / 60 / 60 / 24);
  6037. return $leftDays;
  6038. }
  6039. /**
  6040. * @param int $duration
  6041. * @param int $userId
  6042. * @param int $sessionId
  6043. *
  6044. * @return bool
  6045. */
  6046. public static function editUserSessionDuration($duration, $userId, $sessionId)
  6047. {
  6048. $duration = (int) $duration;
  6049. $userId = (int) $userId;
  6050. $sessionId = (int) $sessionId;
  6051. if (empty($userId) || empty($sessionId)) {
  6052. return false;
  6053. }
  6054. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  6055. $parameters = ['duration' => $duration];
  6056. $where = ['session_id = ? AND user_id = ? ' => [$sessionId, $userId]];
  6057. Database::update($table, $parameters, $where);
  6058. return true;
  6059. }
  6060. /**
  6061. * Gets one row from the session_rel_user table.
  6062. *
  6063. * @param int $userId
  6064. * @param int $sessionId
  6065. *
  6066. * @return array
  6067. */
  6068. public static function getUserSession($userId, $sessionId)
  6069. {
  6070. $userId = (int) $userId;
  6071. $sessionId = (int) $sessionId;
  6072. if (empty($userId) || empty($sessionId)) {
  6073. return false;
  6074. }
  6075. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  6076. $sql = "SELECT * FROM $table
  6077. WHERE session_id = $sessionId AND user_id = $userId";
  6078. $result = Database::query($sql);
  6079. $values = [];
  6080. if (Database::num_rows($result)) {
  6081. $values = Database::fetch_array($result, 'ASSOC');
  6082. }
  6083. return $values;
  6084. }
  6085. /**
  6086. * Check if user is subscribed inside a session as student.
  6087. *
  6088. * @param int $sessionId The session id
  6089. * @param int $userId The user id
  6090. *
  6091. * @return bool Whether is subscribed
  6092. */
  6093. public static function isUserSubscribedAsStudent($sessionId, $userId)
  6094. {
  6095. $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  6096. $sessionId = (int) $sessionId;
  6097. $userId = (int) $userId;
  6098. // COUNT(1) actually returns the number of rows from the table (as if
  6099. // counting the results from the first column)
  6100. $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
  6101. WHERE
  6102. session_id = $sessionId AND
  6103. user_id = $userId AND
  6104. relation_type = 0";
  6105. $result = Database::fetch_assoc(Database::query($sql));
  6106. if (!empty($result) && $result['qty'] > 0) {
  6107. return true;
  6108. }
  6109. return false;
  6110. }
  6111. /**
  6112. * Check if user is subscribed inside a session as a HRM.
  6113. *
  6114. * @param int $sessionId The session id
  6115. * @param int $userId The user id
  6116. *
  6117. * @return bool Whether is subscribed
  6118. */
  6119. public static function isUserSubscribedAsHRM($sessionId, $userId)
  6120. {
  6121. $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  6122. $sessionId = (int) $sessionId;
  6123. $userId = (int) $userId;
  6124. // COUNT(1) actually returns the number of rows from the table (as if
  6125. // counting the results from the first column)
  6126. $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
  6127. WHERE
  6128. session_id = $sessionId AND
  6129. user_id = $userId AND
  6130. relation_type = ".SESSION_RELATION_TYPE_RRHH;
  6131. $result = Database::fetch_assoc(Database::query($sql));
  6132. if (!empty($result) && $result['qty'] > 0) {
  6133. return true;
  6134. }
  6135. return false;
  6136. }
  6137. /**
  6138. * Get the session coached by a user (general coach and course-session coach).
  6139. *
  6140. * @param int $coachId The coach id
  6141. * @param bool $checkSessionRelUserVisibility Check the session visibility
  6142. * @param bool $asPlatformAdmin The user is a platform admin and we want all sessions
  6143. *
  6144. * @return array The session list
  6145. */
  6146. public static function getSessionsCoachedByUser(
  6147. $coachId,
  6148. $checkSessionRelUserVisibility = false,
  6149. $asPlatformAdmin = false
  6150. ) {
  6151. // Get all sessions where $coachId is the general coach
  6152. $sessions = self::get_sessions_by_general_coach($coachId, $asPlatformAdmin);
  6153. // Get all sessions where $coachId is the course - session coach
  6154. $courseSessionList = self::getCoursesListByCourseCoach($coachId);
  6155. $sessionsByCoach = [];
  6156. if (!empty($courseSessionList)) {
  6157. foreach ($courseSessionList as $userCourseSubscription) {
  6158. $session = $userCourseSubscription->getSession();
  6159. $sessionsByCoach[$session->getId()] = api_get_session_info(
  6160. $session->getId()
  6161. );
  6162. }
  6163. }
  6164. if (!empty($sessionsByCoach)) {
  6165. $sessions = array_merge($sessions, $sessionsByCoach);
  6166. }
  6167. // Remove repeated sessions
  6168. if (!empty($sessions)) {
  6169. $cleanSessions = [];
  6170. foreach ($sessions as $session) {
  6171. $cleanSessions[$session['id']] = $session;
  6172. }
  6173. $sessions = $cleanSessions;
  6174. }
  6175. if ($checkSessionRelUserVisibility) {
  6176. if (!empty($sessions)) {
  6177. $newSessions = [];
  6178. foreach ($sessions as $session) {
  6179. $visibility = api_get_session_visibility($session['id']);
  6180. if ($visibility == SESSION_INVISIBLE) {
  6181. continue;
  6182. }
  6183. $newSessions[] = $session;
  6184. }
  6185. $sessions = $newSessions;
  6186. }
  6187. }
  6188. return $sessions;
  6189. }
  6190. /**
  6191. * Check if the course belongs to the session.
  6192. *
  6193. * @param int $sessionId The session id
  6194. * @param string $courseCode The course code
  6195. *
  6196. * @return bool
  6197. */
  6198. public static function sessionHasCourse($sessionId, $courseCode)
  6199. {
  6200. $sessionId = (int) $sessionId;
  6201. $courseCode = Database::escape_string($courseCode);
  6202. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  6203. $sessionRelCourseTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  6204. $sql = "SELECT COUNT(1) AS qty
  6205. FROM $courseTable c
  6206. INNER JOIN $sessionRelCourseTable src
  6207. ON c.id = src.c_id
  6208. WHERE src.session_id = $sessionId
  6209. AND c.code = '$courseCode' ";
  6210. $result = Database::query($sql);
  6211. if ($result !== false) {
  6212. $data = Database::fetch_assoc($result);
  6213. if ($data['qty'] > 0) {
  6214. return true;
  6215. }
  6216. }
  6217. return false;
  6218. }
  6219. /**
  6220. * Calculate the total user time in the platform.
  6221. *
  6222. * @param int $userId The user id
  6223. * @param string $from Optional. From date
  6224. * @param string $until Optional. Until date
  6225. *
  6226. * @return string The time (hh:mm:ss)
  6227. */
  6228. public static function getTotalUserTimeInPlatform($userId, $from = '', $until = '')
  6229. {
  6230. $userId = (int) $userId;
  6231. $trackLoginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  6232. $whereConditions = [
  6233. 'login_user_id = ? ' => $userId,
  6234. ];
  6235. if (!empty($from) && !empty($until)) {
  6236. $whereConditions["AND (login_date >= '?' "] = $from;
  6237. $whereConditions["AND logout_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
  6238. }
  6239. $trackResult = Database::select(
  6240. 'SEC_TO_TIME(SUM(UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date))) as total_time',
  6241. $trackLoginTable,
  6242. [
  6243. 'where' => $whereConditions,
  6244. ],
  6245. 'first'
  6246. );
  6247. if ($trackResult != false) {
  6248. return $trackResult['total_time'] ? $trackResult['total_time'] : '00:00:00';
  6249. }
  6250. return '00:00:00';
  6251. }
  6252. /**
  6253. * Get the courses list by a course coach.
  6254. *
  6255. * @param int $coachId The coach id
  6256. *
  6257. * @return array (id, user_id, session_id, c_id, visibility, status, legal_agreement)
  6258. */
  6259. public static function getCoursesListByCourseCoach($coachId)
  6260. {
  6261. $entityManager = Database::getManager();
  6262. $scuRepo = $entityManager->getRepository(
  6263. 'ChamiloCoreBundle:SessionRelCourseRelUser'
  6264. );
  6265. return $scuRepo->findBy([
  6266. 'user' => $coachId,
  6267. 'status' => SessionRelCourseRelUser::STATUS_COURSE_COACH,
  6268. ]);
  6269. }
  6270. /**
  6271. * Get the count of user courses in session.
  6272. *
  6273. * @param int $sessionId
  6274. * @param int $courseId
  6275. *
  6276. * @return array
  6277. */
  6278. public static function getTotalUserCoursesInSession($sessionId, $courseId = 0)
  6279. {
  6280. $tableUser = Database::get_main_table(TABLE_MAIN_USER);
  6281. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  6282. $sessionId = (int) $sessionId;
  6283. if (empty($sessionId)) {
  6284. return [];
  6285. }
  6286. $courseCondition = '';
  6287. if (!empty($courseId)) {
  6288. $courseId = (int) $courseId;
  6289. $courseCondition = " c_id = $courseId AND ";
  6290. }
  6291. $sql = "SELECT
  6292. COUNT(u.id) as count,
  6293. u.id,
  6294. scu.status status_in_session,
  6295. u.status user_status
  6296. FROM $table scu
  6297. INNER JOIN $tableUser u
  6298. ON scu.user_id = u.id
  6299. WHERE
  6300. $courseCondition
  6301. scu.session_id = ".$sessionId."
  6302. GROUP BY u.id";
  6303. $result = Database::query($sql);
  6304. $list = [];
  6305. while ($data = Database::fetch_assoc($result)) {
  6306. $list[] = $data;
  6307. }
  6308. return $list;
  6309. }
  6310. /**
  6311. * Returns list of a few data from session (name, short description, start
  6312. * date, end date) and the given extra fields if defined based on a
  6313. * session category Id.
  6314. *
  6315. * @param int $categoryId The internal ID of the session category
  6316. * @param string $target Value to search for in the session field values
  6317. * @param array $extraFields A list of fields to be scanned and returned
  6318. *
  6319. * @return mixed
  6320. */
  6321. public static function getShortSessionListAndExtraByCategory(
  6322. $categoryId,
  6323. $target,
  6324. $extraFields = null,
  6325. $publicationDate = null
  6326. ) {
  6327. $categoryId = (int) $categoryId;
  6328. $sessionList = [];
  6329. // Check if categoryId is valid
  6330. if ($categoryId > 0) {
  6331. $target = Database::escape_string($target);
  6332. $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
  6333. $sfTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  6334. $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  6335. // Join session field and session field values tables
  6336. $joinTable = $sfTable.' sf INNER JOIN '.$sfvTable.' sfv ON sf.id = sfv.field_id';
  6337. $fieldsArray = [];
  6338. foreach ($extraFields as $field) {
  6339. $fieldsArray[] = Database::escape_string($field);
  6340. }
  6341. $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
  6342. if (isset($publicationDate)) {
  6343. $publicationDateString = $publicationDate->format('Y-m-d H:i:s');
  6344. $wherePublication = " AND id NOT IN (
  6345. SELECT sfv.item_id FROM $joinTable
  6346. WHERE
  6347. sf.extra_field_type = $extraFieldType AND
  6348. ((sf.variable = 'publication_start_date' AND sfv.value > '$publicationDateString' and sfv.value != '') OR
  6349. (sf.variable = 'publication_end_date' AND sfv.value < '$publicationDateString' and sfv.value != ''))
  6350. )";
  6351. }
  6352. // Get the session list from session category and target
  6353. $sessionList = Database::select(
  6354. 'id, name, access_start_date, access_end_date',
  6355. $sTable,
  6356. [
  6357. 'where' => [
  6358. "session_category_id = ? AND id IN (
  6359. SELECT sfv.item_id FROM $joinTable
  6360. WHERE
  6361. sf.extra_field_type = $extraFieldType AND
  6362. sfv.item_id = session.id AND
  6363. sf.variable = 'target' AND
  6364. sfv.value = ?
  6365. ) $wherePublication" => [$categoryId, $target],
  6366. ],
  6367. ]
  6368. );
  6369. $whereFieldVariables = [];
  6370. $whereFieldIds = [];
  6371. if (
  6372. is_array($fieldsArray) &&
  6373. count($fieldsArray) > 0
  6374. ) {
  6375. $whereParams = '?';
  6376. for ($i = 1; $i < count($fieldsArray); $i++) {
  6377. $whereParams .= ', ?';
  6378. }
  6379. $whereFieldVariables = ' variable IN ( '.$whereParams.' )';
  6380. $whereFieldIds = 'field_id IN ( '.$whereParams.' )';
  6381. }
  6382. // Get session fields
  6383. $extraField = new ExtraFieldModel('session');
  6384. $questionMarks = substr(str_repeat('?, ', count($fieldsArray)), 0, -2);
  6385. $fieldsList = $extraField->get_all([
  6386. ' variable IN ( '.$questionMarks.' )' => $fieldsArray,
  6387. ]);
  6388. // Index session fields
  6389. foreach ($fieldsList as $field) {
  6390. $fields[$field['id']] = $field['variable'];
  6391. }
  6392. // Get session field values
  6393. $extra = new ExtraFieldValue('session');
  6394. $questionMarksFields = substr(str_repeat('?, ', count($fields)), 0, -2);
  6395. $sessionFieldValueList = $extra->get_all(['where' => ['field_id IN ( '.$questionMarksFields.' )' => array_keys($fields)]]);
  6396. // Add session fields values to session list
  6397. foreach ($sessionList as $id => &$session) {
  6398. foreach ($sessionFieldValueList as $sessionFieldValue) {
  6399. // Match session field values to session
  6400. if ($sessionFieldValue['item_id'] == $id) {
  6401. // Check if session field value is set in session field list
  6402. if (isset($fields[$sessionFieldValue['field_id']])) {
  6403. // Avoid overwriting the session's ID field
  6404. if ($fields[$sessionFieldValue['field_id']] != 'id') {
  6405. $var = $fields[$sessionFieldValue['field_id']];
  6406. $val = $sessionFieldValue['value'];
  6407. // Assign session field value to session
  6408. $session[$var] = $val;
  6409. }
  6410. }
  6411. }
  6412. }
  6413. }
  6414. }
  6415. return $sessionList;
  6416. }
  6417. /**
  6418. * Return the Session Category id searched by name.
  6419. *
  6420. * @param string $categoryName Name attribute of session category used for search query
  6421. * @param bool $force boolean used to get even if something is wrong (e.g not unique name)
  6422. *
  6423. * @return int|array If success, return category id (int), else it will return an array
  6424. * with the next structure:
  6425. * array('error' => true, 'errorMessage' => ERROR_MESSAGE)
  6426. */
  6427. public static function getSessionCategoryIdByName($categoryName, $force = false)
  6428. {
  6429. // Start error result
  6430. $errorResult = ['error' => true, 'errorMessage' => get_lang('ThereWasAnError')];
  6431. $categoryName = Database::escape_string($categoryName);
  6432. // Check if is not empty category name
  6433. if (!empty($categoryName)) {
  6434. $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  6435. // Get all session category with same name
  6436. $result = Database::select(
  6437. 'id',
  6438. $sessionCategoryTable,
  6439. [
  6440. 'where' => [
  6441. 'name = ?' => $categoryName,
  6442. ],
  6443. ]
  6444. );
  6445. // Check the result
  6446. if ($result < 1) {
  6447. // If not found any result, update error message
  6448. $errorResult['errorMessage'] = 'Not found any session category name '.$categoryName;
  6449. } elseif (count($result) > 1 && !$force) {
  6450. // If found more than one result and force is disabled, update error message
  6451. $errorResult['errorMessage'] = 'Found many session categories';
  6452. } elseif (count($result) == 1 || $force) {
  6453. // If found just one session category or force option is enabled
  6454. return key($result);
  6455. }
  6456. } else {
  6457. // category name is empty, update error message
  6458. $errorResult['errorMessage'] = 'Not valid category name';
  6459. }
  6460. return $errorResult;
  6461. }
  6462. /**
  6463. * Return all data from sessions (plus extra field, course and coach data) by category id.
  6464. *
  6465. * @param int $sessionCategoryId session category id used to search sessions
  6466. *
  6467. * @return array If success, return session list and more session related data, else it will return an array
  6468. * with the next structure:
  6469. * array('error' => true, 'errorMessage' => ERROR_MESSAGE)
  6470. */
  6471. public static function getSessionListAndExtraByCategoryId($sessionCategoryId)
  6472. {
  6473. // Start error result
  6474. $errorResult = [
  6475. 'error' => true,
  6476. 'errorMessage' => get_lang('ThereWasAnError'),
  6477. ];
  6478. $sessionCategoryId = intval($sessionCategoryId);
  6479. // Check if session category id is valid
  6480. if ($sessionCategoryId > 0) {
  6481. // Get table names
  6482. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  6483. $sessionFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  6484. $sessionFieldValueTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  6485. $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  6486. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  6487. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  6488. // Get all data from all sessions whit the session category specified
  6489. $sessionList = Database::select(
  6490. '*',
  6491. $sessionTable,
  6492. [
  6493. 'where' => [
  6494. 'session_category_id = ?' => $sessionCategoryId,
  6495. ],
  6496. ]
  6497. );
  6498. $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
  6499. // Check if session list query had result
  6500. if (!empty($sessionList)) {
  6501. // implode all session id
  6502. $sessionIdsString = '('.implode(', ', array_keys($sessionList)).')';
  6503. // Get all field variables
  6504. $sessionFieldList = Database::select(
  6505. 'id, variable',
  6506. $sessionFieldTable,
  6507. ['extra_field_type = ? ' => [$extraFieldType]]
  6508. );
  6509. // Get all field values
  6510. $sql = "SELECT item_id, field_id, value FROM
  6511. $sessionFieldValueTable v INNER JOIN $sessionFieldTable f
  6512. ON (f.id = v.field_id)
  6513. WHERE
  6514. item_id IN $sessionIdsString AND
  6515. extra_field_type = $extraFieldType
  6516. ";
  6517. $result = Database::query($sql);
  6518. $sessionFieldValueList = Database::store_result($result, 'ASSOC');
  6519. // Check if session field values had result
  6520. if (!empty($sessionFieldValueList)) {
  6521. $sessionFieldValueListBySession = [];
  6522. foreach ($sessionFieldValueList as $key => $sessionFieldValue) {
  6523. // Create an array to index ids to session id
  6524. $sessionFieldValueListBySession[$sessionFieldValue['item_id']][] = $key;
  6525. }
  6526. }
  6527. // Query used to find course-coaches from sessions
  6528. $sql = "SELECT
  6529. scu.session_id,
  6530. c.id AS course_id,
  6531. c.code AS course_code,
  6532. c.title AS course_title,
  6533. u.username AS coach_username,
  6534. u.firstname AS coach_firstname,
  6535. u.lastname AS coach_lastname
  6536. FROM $courseTable c
  6537. INNER JOIN $sessionCourseUserTable scu ON c.id = scu.c_id
  6538. INNER JOIN $userTable u ON scu.user_id = u.user_id
  6539. WHERE scu.status = 2 AND scu.session_id IN $sessionIdsString
  6540. ORDER BY scu.session_id ASC ";
  6541. $res = Database::query($sql);
  6542. $sessionCourseList = Database::store_result($res, 'ASSOC');
  6543. // Check if course list had result
  6544. if (!empty($sessionCourseList)) {
  6545. foreach ($sessionCourseList as $key => $sessionCourse) {
  6546. // Create an array to index ids to session_id
  6547. $sessionCourseListBySession[$sessionCourse['session_id']][] = $key;
  6548. }
  6549. }
  6550. // Join lists
  6551. if (is_array($sessionList)) {
  6552. foreach ($sessionList as $id => &$row) {
  6553. if (
  6554. !empty($sessionFieldValueListBySession) &&
  6555. is_array($sessionFieldValueListBySession[$id])
  6556. ) {
  6557. // If have an index array for session extra fields, use it to join arrays
  6558. foreach ($sessionFieldValueListBySession[$id] as $key) {
  6559. $row['extra'][$key] = [
  6560. 'field_name' => $sessionFieldList[$sessionFieldValueList[$key]['field_id']]['variable'],
  6561. 'value' => $sessionFieldValueList[$key]['value'],
  6562. ];
  6563. }
  6564. }
  6565. if (
  6566. !empty($sessionCourseListBySession) &&
  6567. is_array($sessionCourseListBySession[$id])
  6568. ) {
  6569. // If have an index array for session course coach, use it to join arrays
  6570. foreach ($sessionCourseListBySession[$id] as $key) {
  6571. $row['course'][$key] = [
  6572. 'course_id' => $sessionCourseList[$key]['course_id'],
  6573. 'course_code' => $sessionCourseList[$key]['course_code'],
  6574. 'course_title' => $sessionCourseList[$key]['course_title'],
  6575. 'coach_username' => $sessionCourseList[$key]['coach_username'],
  6576. 'coach_firstname' => $sessionCourseList[$key]['coach_firstname'],
  6577. 'coach_lastname' => $sessionCourseList[$key]['coach_lastname'],
  6578. ];
  6579. }
  6580. }
  6581. }
  6582. }
  6583. return $sessionList;
  6584. } else {
  6585. // Not found result, update error message
  6586. $errorResult['errorMessage'] = 'Not found any session for session category id '.$sessionCategoryId;
  6587. }
  6588. }
  6589. return $errorResult;
  6590. }
  6591. /**
  6592. * Return session description from session id.
  6593. *
  6594. * @param int $sessionId
  6595. *
  6596. * @return string
  6597. */
  6598. public static function getDescriptionFromSessionId($sessionId)
  6599. {
  6600. // Init variables
  6601. $sessionId = (int) $sessionId;
  6602. $description = '';
  6603. // Check if session id is valid
  6604. if ($sessionId > 0) {
  6605. // Select query from session id
  6606. $rows = Database::select(
  6607. 'description',
  6608. Database::get_main_table(TABLE_MAIN_SESSION),
  6609. [
  6610. 'where' => [
  6611. 'id = ?' => $sessionId,
  6612. ],
  6613. ]
  6614. );
  6615. // Check if select query result is not empty
  6616. if (!empty($rows)) {
  6617. // Get session description
  6618. $description = $rows[0]['description'];
  6619. }
  6620. }
  6621. return $description;
  6622. }
  6623. /**
  6624. * Get a session list filtered by name, description or any of the given extra fields.
  6625. *
  6626. * @param string $term The term to search
  6627. * @param array $extraFieldsToInclude Extra fields to include in the session data
  6628. *
  6629. * @return array The list
  6630. */
  6631. public static function searchSession($term, $extraFieldsToInclude = [])
  6632. {
  6633. $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
  6634. $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  6635. $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  6636. $term = Database::escape_string($term);
  6637. $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
  6638. if (is_array($extraFieldsToInclude) && count($extraFieldsToInclude) > 0) {
  6639. $resultData = Database::select('*', $sTable, [
  6640. 'where' => [
  6641. "name LIKE %?% " => $term,
  6642. " OR description LIKE %?% " => $term,
  6643. " OR id IN (
  6644. SELECT item_id
  6645. FROM $sfvTable v INNER JOIN $extraFieldTable e
  6646. ON (v.field_id = e.id)
  6647. WHERE value LIKE %?% AND extra_field_type = $extraFieldType
  6648. ) " => $term,
  6649. ],
  6650. ]);
  6651. } else {
  6652. $resultData = Database::select('*', $sTable, [
  6653. 'where' => [
  6654. "name LIKE %?% " => $term,
  6655. "OR description LIKE %?% " => $term,
  6656. ],
  6657. ]);
  6658. return $resultData;
  6659. }
  6660. foreach ($resultData as $id => &$session) {
  6661. $session['extra'] = self::getFilteredExtraFields($id, $extraFieldsToInclude);
  6662. }
  6663. return $resultData;
  6664. }
  6665. /**
  6666. * @param int $sessionId
  6667. * @param array $extraFieldsToInclude
  6668. *
  6669. * @return array
  6670. */
  6671. public static function getFilteredExtraFields($sessionId, $extraFieldsToInclude = [])
  6672. {
  6673. $extraData = [];
  6674. $variables = [];
  6675. $variablePlaceHolders = [];
  6676. foreach ($extraFieldsToInclude as $sessionExtraField) {
  6677. $variablePlaceHolders[] = "?";
  6678. $variables[] = Database::escape_string($sessionExtraField);
  6679. }
  6680. $sessionExtraField = new ExtraFieldModel('session');
  6681. $fieldList = $sessionExtraField->get_all([
  6682. "variable IN ( ".implode(", ", $variablePlaceHolders)." ) " => $variables,
  6683. ]);
  6684. $fields = [];
  6685. // Index session fields
  6686. foreach ($fieldList as $field) {
  6687. $fields[$field['id']] = $field['variable'];
  6688. }
  6689. // Get session field values
  6690. $extra = new ExtraFieldValue('session');
  6691. $sessionFieldValueList = $extra->get_all(
  6692. [
  6693. "field_id IN ( ".implode(", ", $variablePlaceHolders)." )" => array_keys($fields),
  6694. ]
  6695. );
  6696. foreach ($sessionFieldValueList as $sessionFieldValue) {
  6697. // Match session field values to session
  6698. if ($sessionFieldValue['item_id'] != $sessionId) {
  6699. continue;
  6700. }
  6701. // Check if session field value is set in session field list
  6702. if (!isset($fields[$sessionFieldValue['field_id']])) {
  6703. continue;
  6704. }
  6705. $extrafieldVariable = $fields[$sessionFieldValue['field_id']];
  6706. $extrafieldValue = $sessionFieldValue['value'];
  6707. $extraData[] = [
  6708. 'variable' => $extrafieldVariable,
  6709. 'value' => $extrafieldValue,
  6710. ];
  6711. }
  6712. return $extraData;
  6713. }
  6714. /**
  6715. * @param int $sessionId
  6716. *
  6717. * @return bool
  6718. */
  6719. public static function isValidId($sessionId)
  6720. {
  6721. $sessionId = intval($sessionId);
  6722. if ($sessionId > 0) {
  6723. $rows = Database::select(
  6724. 'id',
  6725. Database::get_main_table(TABLE_MAIN_SESSION),
  6726. ['where' => ['id = ?' => $sessionId]]
  6727. );
  6728. if (!empty($rows)) {
  6729. return true;
  6730. }
  6731. }
  6732. return false;
  6733. }
  6734. /**
  6735. * Get list of sessions based on users of a group for a group admin.
  6736. *
  6737. * @param int $userId The user id
  6738. *
  6739. * @return array
  6740. */
  6741. public static function getSessionsFollowedForGroupAdmin($userId)
  6742. {
  6743. $sessionList = [];
  6744. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  6745. $sessionUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  6746. $userGroup = new UserGroup();
  6747. $userIdList = $userGroup->getGroupUsersByUser($userId);
  6748. if (empty($userIdList)) {
  6749. return [];
  6750. }
  6751. $sql = "SELECT DISTINCT s.*
  6752. FROM $sessionTable s
  6753. INNER JOIN $sessionUserTable sru
  6754. ON s.id = sru.id_session
  6755. WHERE
  6756. (sru.id_user IN (".implode(', ', $userIdList).")
  6757. AND sru.relation_type = 0
  6758. )";
  6759. if (api_is_multiple_url_enabled()) {
  6760. $sessionAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  6761. $accessUrlId = api_get_current_access_url_id();
  6762. if ($accessUrlId != -1) {
  6763. $sql = "SELECT DISTINCT s.*
  6764. FROM $sessionTable s
  6765. INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
  6766. INNER JOIN $sessionAccessUrlTable srau ON s.id = srau.session_id
  6767. WHERE
  6768. srau.access_url_id = $accessUrlId
  6769. AND (
  6770. sru.id_user IN (".implode(', ', $userIdList).")
  6771. AND sru.relation_type = 0
  6772. )";
  6773. }
  6774. }
  6775. $result = Database::query($sql);
  6776. while ($row = Database::fetch_assoc($result)) {
  6777. $sessionList[] = $row;
  6778. }
  6779. return $sessionList;
  6780. }
  6781. /**
  6782. * @param array $sessionInfo
  6783. *
  6784. * @return string
  6785. */
  6786. public static function getSessionVisibility($sessionInfo)
  6787. {
  6788. switch ($sessionInfo['visibility']) {
  6789. case 1:
  6790. return get_lang('ReadOnly');
  6791. case 2:
  6792. return get_lang('Visible');
  6793. case 3:
  6794. return api_ucfirst(get_lang('Invisible'));
  6795. }
  6796. }
  6797. /**
  6798. * Returns a human readable string.
  6799. *
  6800. * @param array $sessionInfo An array with all the session dates
  6801. * @param bool $showTime
  6802. *
  6803. * @return array
  6804. */
  6805. public static function parseSessionDates($sessionInfo, $showTime = false)
  6806. {
  6807. $displayDates = self::convertSessionDateToString(
  6808. $sessionInfo['display_start_date'],
  6809. $sessionInfo['display_end_date'],
  6810. $showTime,
  6811. true
  6812. );
  6813. $accessDates = self::convertSessionDateToString(
  6814. $sessionInfo['access_start_date'],
  6815. $sessionInfo['access_end_date'],
  6816. $showTime,
  6817. true
  6818. );
  6819. $coachDates = self::convertSessionDateToString(
  6820. $sessionInfo['coach_access_start_date'],
  6821. $sessionInfo['coach_access_end_date'],
  6822. $showTime,
  6823. true
  6824. );
  6825. $result = [
  6826. 'access' => $accessDates,
  6827. 'display' => $displayDates,
  6828. 'coach' => $coachDates,
  6829. ];
  6830. return $result;
  6831. }
  6832. /**
  6833. * @param FormValidator $form
  6834. * @param array $sessionInfo Optional
  6835. *
  6836. * @return array
  6837. */
  6838. public static function setForm(FormValidator $form, array $sessionInfo = [])
  6839. {
  6840. $sessionId = 0;
  6841. $coachInfo = [];
  6842. if (!empty($sessionInfo)) {
  6843. $sessionId = (int) $sessionInfo['id'];
  6844. $coachInfo = api_get_user_info($sessionInfo['id_coach']);
  6845. }
  6846. $categoriesList = self::get_all_session_category();
  6847. $userInfo = api_get_user_info();
  6848. $categoriesOptions = [
  6849. '0' => get_lang('None'),
  6850. ];
  6851. if ($categoriesList != false) {
  6852. foreach ($categoriesList as $categoryItem) {
  6853. $categoriesOptions[$categoryItem['id']] = $categoryItem['name'];
  6854. }
  6855. }
  6856. // Database Table Definitions
  6857. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  6858. $form->addText(
  6859. 'name',
  6860. get_lang('SessionName'),
  6861. true,
  6862. ['maxlength' => 150, 'aria-label' => get_lang('SessionName')]
  6863. );
  6864. $form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
  6865. if (!api_is_platform_admin() && api_is_teacher()) {
  6866. $form->addElement(
  6867. 'select',
  6868. 'coach_username',
  6869. get_lang('CoachName'),
  6870. [api_get_user_id() => $userInfo['complete_name']],
  6871. [
  6872. 'id' => 'coach_username',
  6873. 'style' => 'width:370px;',
  6874. ]
  6875. );
  6876. } else {
  6877. $sql = "SELECT COUNT(1) FROM $tbl_user WHERE status = 1";
  6878. $rs = Database::query($sql);
  6879. $countUsers = (int) Database::result($rs, 0, 0);
  6880. if ($countUsers < 50) {
  6881. $orderClause = 'ORDER BY ';
  6882. $orderClause .= api_sort_by_first_name() ? 'firstname, lastname, username' : 'lastname, firstname, username';
  6883. $sql = "SELECT user_id, lastname, firstname, username
  6884. FROM $tbl_user
  6885. WHERE status = '1' ".
  6886. $orderClause;
  6887. if (api_is_multiple_url_enabled()) {
  6888. $userRelAccessUrlTable = Database::get_main_table(
  6889. TABLE_MAIN_ACCESS_URL_REL_USER
  6890. );
  6891. $accessUrlId = api_get_current_access_url_id();
  6892. if ($accessUrlId != -1) {
  6893. $sql = "SELECT user.user_id, username, lastname, firstname
  6894. FROM $tbl_user user
  6895. INNER JOIN $userRelAccessUrlTable url_user
  6896. ON (url_user.user_id = user.user_id)
  6897. WHERE
  6898. access_url_id = $accessUrlId AND
  6899. status = 1 "
  6900. .$orderClause;
  6901. }
  6902. }
  6903. $result = Database::query($sql);
  6904. $coachesList = Database::store_result($result);
  6905. $coachesOptions = [];
  6906. foreach ($coachesList as $coachItem) {
  6907. $coachesOptions[$coachItem['user_id']] =
  6908. api_get_person_name($coachItem['firstname'], $coachItem['lastname']).' ('.$coachItem['username'].')';
  6909. }
  6910. $form->addElement(
  6911. 'select',
  6912. 'coach_username',
  6913. get_lang('CoachName'),
  6914. $coachesOptions,
  6915. [
  6916. 'id' => 'coach_username',
  6917. 'style' => 'width:370px;',
  6918. ]
  6919. );
  6920. } else {
  6921. $form->addElement(
  6922. 'select_ajax',
  6923. 'coach_username',
  6924. get_lang('CoachName'),
  6925. $coachInfo ? [$coachInfo['id'] => $coachInfo['complete_name_with_username']] : [],
  6926. [
  6927. 'url' => api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=search_general_coach',
  6928. 'width' => '100%',
  6929. 'id' => 'coach_username',
  6930. ]
  6931. );
  6932. }
  6933. }
  6934. $form->addRule('coach_username', get_lang('ThisFieldIsRequired'), 'required');
  6935. $form->addHtml('<div id="ajax_list_coachs"></div>');
  6936. $form->addButtonAdvancedSettings('advanced_params');
  6937. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  6938. if (empty($sessionId)) {
  6939. $sessions = self::formatSessionsAdminForGrid();
  6940. $sessionList = [];
  6941. $sessionList[] = '';
  6942. foreach ($sessions as $session) {
  6943. $sessionList[$session['id']] = strip_tags($session['name']);
  6944. }
  6945. $form->addSelect(
  6946. 'session_template',
  6947. get_lang('SessionTemplate'),
  6948. $sessionList,
  6949. ['id' => 'system_template']
  6950. );
  6951. }
  6952. $form->addSelect(
  6953. 'session_category',
  6954. get_lang('SessionCategory'),
  6955. $categoriesOptions,
  6956. [
  6957. 'id' => 'session_category',
  6958. ]
  6959. );
  6960. $form->addHtmlEditor(
  6961. 'description',
  6962. get_lang('Description'),
  6963. false,
  6964. false,
  6965. [
  6966. 'ToolbarSet' => 'Minimal',
  6967. ]
  6968. );
  6969. $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'));
  6970. $visibilityGroup = [];
  6971. $visibilityGroup[] = $form->createElement(
  6972. 'select',
  6973. 'session_visibility',
  6974. null,
  6975. [
  6976. SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
  6977. SESSION_VISIBLE => get_lang('SessionAccessible'),
  6978. SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible')),
  6979. ]
  6980. );
  6981. $form->addGroup(
  6982. $visibilityGroup,
  6983. 'visibility_group',
  6984. get_lang('SessionVisibility'),
  6985. null,
  6986. false
  6987. );
  6988. $options = [
  6989. 0 => get_lang('ByDuration'),
  6990. 1 => get_lang('ByDates'),
  6991. ];
  6992. $form->addSelect('access', get_lang('Access'), $options, [
  6993. 'onchange' => 'accessSwitcher()',
  6994. 'id' => 'access',
  6995. ]);
  6996. $form->addHtml('<div id="duration_div" style="display:none">');
  6997. $form->addElement(
  6998. 'number',
  6999. 'duration',
  7000. [
  7001. get_lang('SessionDurationTitle'),
  7002. get_lang('SessionDurationDescription'),
  7003. ],
  7004. [
  7005. 'maxlength' => 50,
  7006. ]
  7007. );
  7008. $form->addHtml('</div>');
  7009. $form->addHtml('<div id="date_fields" style="display:none">');
  7010. // Dates
  7011. $form->addDateTimePicker(
  7012. 'access_start_date',
  7013. [get_lang('SessionStartDate'), get_lang('SessionStartDateComment')],
  7014. ['id' => 'access_start_date']
  7015. );
  7016. $form->addDateTimePicker(
  7017. 'access_end_date',
  7018. [get_lang('SessionEndDate'), get_lang('SessionEndDateComment')],
  7019. ['id' => 'access_end_date']
  7020. );
  7021. $form->addRule(
  7022. ['access_start_date', 'access_end_date'],
  7023. get_lang('StartDateMustBeBeforeTheEndDate'),
  7024. 'compare_datetime_text',
  7025. '< allow_empty'
  7026. );
  7027. $form->addDateTimePicker(
  7028. 'display_start_date',
  7029. [
  7030. get_lang('SessionDisplayStartDate'),
  7031. get_lang('SessionDisplayStartDateComment'),
  7032. ],
  7033. ['id' => 'display_start_date']
  7034. );
  7035. $form->addDateTimePicker(
  7036. 'display_end_date',
  7037. [
  7038. get_lang('SessionDisplayEndDate'),
  7039. get_lang('SessionDisplayEndDateComment'),
  7040. ],
  7041. ['id' => 'display_end_date']
  7042. );
  7043. $form->addRule(
  7044. ['display_start_date', 'display_end_date'],
  7045. get_lang('StartDateMustBeBeforeTheEndDate'),
  7046. 'compare_datetime_text',
  7047. '< allow_empty'
  7048. );
  7049. $form->addDateTimePicker(
  7050. 'coach_access_start_date',
  7051. [
  7052. get_lang('SessionCoachStartDate'),
  7053. get_lang('SessionCoachStartDateComment'),
  7054. ],
  7055. ['id' => 'coach_access_start_date']
  7056. );
  7057. $form->addDateTimePicker(
  7058. 'coach_access_end_date',
  7059. [
  7060. get_lang('SessionCoachEndDate'),
  7061. get_lang('SessionCoachEndDateComment'),
  7062. ],
  7063. ['id' => 'coach_access_end_date']
  7064. );
  7065. $form->addRule(
  7066. ['coach_access_start_date', 'coach_access_end_date'],
  7067. get_lang('StartDateMustBeBeforeTheEndDate'),
  7068. 'compare_datetime_text',
  7069. '< allow_empty'
  7070. );
  7071. $form->addElement('html', '</div>');
  7072. $form->addCheckBox(
  7073. 'send_subscription_notification',
  7074. [
  7075. get_lang('SendSubscriptionNotification'),
  7076. get_lang('SendAnEmailWhenAUserBeingSubscribed'),
  7077. ]
  7078. );
  7079. // Extra fields
  7080. $extra_field = new ExtraFieldModel('session');
  7081. $extra = $extra_field->addElements($form, $sessionId);
  7082. $form->addElement('html', '</div>');
  7083. $js = $extra['jquery_ready_content'];
  7084. return ['js' => $js];
  7085. }
  7086. /**
  7087. * Gets the number of rows in the session table filtered through the given
  7088. * array of parameters.
  7089. *
  7090. * @param array Array of options/filters/keys
  7091. *
  7092. * @return int The number of rows, or false on wrong param
  7093. * @assert ('a') === false
  7094. */
  7095. public static function get_count_admin_complete($options = [])
  7096. {
  7097. if (!is_array($options)) {
  7098. return false;
  7099. }
  7100. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  7101. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  7102. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  7103. $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  7104. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  7105. $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  7106. $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  7107. $where = 'WHERE 1 = 1 ';
  7108. $user_id = api_get_user_id();
  7109. if (api_is_session_admin() &&
  7110. api_get_setting('allow_session_admins_to_see_all_sessions') == 'false'
  7111. ) {
  7112. $where .= " WHERE s.session_admin_id = $user_id ";
  7113. }
  7114. $extraFieldTables = '';
  7115. if (!empty($options['where'])) {
  7116. $options['where'] = str_replace('course_title', 'c.title', $options['where']);
  7117. $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
  7118. $options['where'] = str_replace(
  7119. ["AND session_active = '1' )", " AND ( session_active = '1' )"],
  7120. [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
  7121. $options['where']
  7122. );
  7123. $options['where'] = str_replace(
  7124. ["AND session_active = '0' )", " AND ( session_active = '0' )"],
  7125. [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
  7126. $options['where']
  7127. );
  7128. if (!empty($options['extra'])) {
  7129. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  7130. $options['where'] = str_replace('AND', 'OR', $options['where']);
  7131. foreach ($options['extra'] as $extra) {
  7132. $options['where'] = str_replace(
  7133. $extra['field'],
  7134. 'fv.field_id = '.$extra['id'].' AND fvo.option_value',
  7135. $options['where']
  7136. );
  7137. $extraFieldTables = "$tbl_session_field_values fv, $tbl_session_field_options fvo, ";
  7138. }
  7139. }
  7140. $where .= ' AND '.$options['where'];
  7141. }
  7142. $today = api_get_utc_datetime();
  7143. $query_rows = "SELECT count(*) as total_rows, c.title as course_title, s.name,
  7144. IF (
  7145. (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
  7146. (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
  7147. (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
  7148. (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
  7149. ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
  7150. , 1, 0) as session_active
  7151. FROM $extraFieldTables $tbl_session s
  7152. LEFT JOIN $tbl_session_category sc
  7153. ON s.session_category_id = sc.id
  7154. INNER JOIN $tbl_user u
  7155. ON s.id_coach = u.user_id
  7156. INNER JOIN $sessionCourseUserTable scu
  7157. ON s.id = scu.session_id
  7158. INNER JOIN $courseTable c
  7159. ON c.id = scu.c_id
  7160. $where ";
  7161. if (api_is_multiple_url_enabled()) {
  7162. $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  7163. $access_url_id = api_get_current_access_url_id();
  7164. if ($access_url_id != -1) {
  7165. $where .= " AND ar.access_url_id = $access_url_id ";
  7166. $query_rows = "SELECT count(*) as total_rows
  7167. FROM $tbl_session s
  7168. LEFT JOIN $tbl_session_category sc
  7169. ON s.session_category_id = sc.id
  7170. INNER JOIN $tbl_user u
  7171. ON s.id_coach = u.user_id
  7172. INNER JOIN $table_access_url_rel_session ar
  7173. ON ar.session_id = s.id $where ";
  7174. }
  7175. }
  7176. $result = Database::query($query_rows);
  7177. $num = 0;
  7178. if (Database::num_rows($result)) {
  7179. $rows = Database::fetch_array($result);
  7180. $num = $rows['total_rows'];
  7181. }
  7182. return $num;
  7183. }
  7184. /**
  7185. * @param string $listType
  7186. * @param array $extraFields
  7187. *
  7188. * @return array
  7189. */
  7190. public static function getGridColumns(
  7191. $listType = 'simple',
  7192. $extraFields = []
  7193. ) {
  7194. $showCount = api_get_configuration_value('session_list_show_count_users');
  7195. // Column config
  7196. $operators = ['cn', 'nc'];
  7197. $date_operators = ['gt', 'ge', 'lt', 'le'];
  7198. switch ($listType) {
  7199. case 'my_space':
  7200. $columns = [
  7201. get_lang('Title'),
  7202. get_lang('Date'),
  7203. get_lang('NbCoursesPerSession'),
  7204. get_lang('NbStudentPerSession'),
  7205. get_lang('Details'),
  7206. ];
  7207. $columnModel = [
  7208. ['name' => 'name', 'index' => 'name', 'width' => '255', 'align' => 'left'],
  7209. ['name' => 'date', 'index' => 'access_start_date', 'width' => '150', 'align' => 'left'],
  7210. [
  7211. 'name' => 'course_per_session',
  7212. 'index' => 'course_per_session',
  7213. 'width' => '150',
  7214. 'sortable' => 'false',
  7215. 'search' => 'false',
  7216. ],
  7217. [
  7218. 'name' => 'student_per_session',
  7219. 'index' => 'student_per_session',
  7220. 'width' => '100',
  7221. 'sortable' => 'false',
  7222. 'search' => 'false',
  7223. ],
  7224. ['name' => 'actions', 'index' => 'actions', 'width' => '100', 'sortable' => 'false', 'search' => 'false'],
  7225. ];
  7226. break;
  7227. case 'simple':
  7228. $columns = [
  7229. '#',
  7230. get_lang('Name'),
  7231. get_lang('Category'),
  7232. get_lang('SessionDisplayStartDate'),
  7233. get_lang('SessionDisplayEndDate'),
  7234. get_lang('Visibility'),
  7235. ];
  7236. $columnModel = [
  7237. [
  7238. 'name' => 'id',
  7239. 'index' => 's.id',
  7240. 'width' => '160',
  7241. 'hidden' => 'true',
  7242. ],
  7243. [
  7244. 'name' => 'name',
  7245. 'index' => 's.name',
  7246. 'width' => '160',
  7247. 'align' => 'left',
  7248. 'search' => 'true',
  7249. 'searchoptions' => ['sopt' => $operators],
  7250. ],
  7251. [
  7252. 'name' => 'category_name',
  7253. 'index' => 'category_name',
  7254. 'width' => '40',
  7255. 'align' => 'left',
  7256. 'search' => 'true',
  7257. 'searchoptions' => ['sopt' => $operators],
  7258. ],
  7259. [
  7260. 'name' => 'display_start_date',
  7261. 'index' => 'display_start_date',
  7262. 'width' => '50',
  7263. 'align' => 'left',
  7264. 'search' => 'true',
  7265. 'searchoptions' => [
  7266. 'dataInit' => 'date_pick_today',
  7267. 'sopt' => $date_operators,
  7268. ],
  7269. ],
  7270. [
  7271. 'name' => 'display_end_date',
  7272. 'index' => 'display_end_date',
  7273. 'width' => '50',
  7274. 'align' => 'left',
  7275. 'search' => 'true',
  7276. 'searchoptions' => [
  7277. 'dataInit' => 'date_pick_one_month',
  7278. 'sopt' => $date_operators,
  7279. ],
  7280. ],
  7281. [
  7282. 'name' => 'visibility',
  7283. 'index' => 'visibility',
  7284. 'width' => '40',
  7285. 'align' => 'left',
  7286. 'search' => 'false',
  7287. ],
  7288. ];
  7289. if ($showCount) {
  7290. $columns[] = get_lang('Users');
  7291. $columnModel[] = [
  7292. 'name' => 'users',
  7293. 'index' => 'users',
  7294. 'width' => '20',
  7295. 'align' => 'left',
  7296. 'search' => 'false',
  7297. ];
  7298. }
  7299. break;
  7300. case 'complete':
  7301. $columns = [
  7302. get_lang('Name'),
  7303. get_lang('SessionDisplayStartDate'),
  7304. get_lang('SessionDisplayEndDate'),
  7305. get_lang('Coach'),
  7306. get_lang('Status'),
  7307. get_lang('Visibility'),
  7308. get_lang('CourseTitle'),
  7309. ];
  7310. $columnModel = [
  7311. ['name' => 'name', 'index' => 's.name', 'width' => '200', 'align' => 'left', 'search' => 'true', 'searchoptions' => ['sopt' => $operators]],
  7312. ['name' => 'display_start_date', 'index' => 'display_start_date', 'width' => '70', 'align' => 'left', 'search' => 'true', 'searchoptions' => ['dataInit' => 'date_pick_today', 'sopt' => $date_operators]],
  7313. ['name' => 'display_end_date', 'index' => 'display_end_date', 'width' => '70', 'align' => 'left', 'search' => 'true', 'searchoptions' => ['dataInit' => 'date_pick_one_month', 'sopt' => $date_operators]],
  7314. ['name' => 'coach_name', 'index' => 'coach_name', 'width' => '70', 'align' => 'left', 'search' => 'false', 'searchoptions' => ['sopt' => $operators]],
  7315. ['name' => 'session_active', 'index' => 'session_active', 'width' => '25', 'align' => 'left', 'search' => 'true', 'stype' => 'select',
  7316. // for the bottom bar
  7317. 'searchoptions' => [
  7318. 'defaultValue' => '1',
  7319. 'value' => '1:'.get_lang('Active').';0:'.get_lang('Inactive'), ],
  7320. // for the top bar
  7321. 'editoptions' => ['value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive')],
  7322. ],
  7323. ['name' => 'visibility', 'index' => 'visibility', 'width' => '40', 'align' => 'left', 'search' => 'false'],
  7324. ['name' => 'course_title', 'index' => 'course_title', 'width' => '50', 'hidden' => 'true', 'search' => 'true', 'searchoptions' => ['searchhidden' => 'true', 'sopt' => $operators]],
  7325. ];
  7326. break;
  7327. }
  7328. if (!empty($extraFields)) {
  7329. foreach ($extraFields as $field) {
  7330. $columns[] = $field['display_text'];
  7331. $columnModel[] = [
  7332. 'name' => $field['variable'],
  7333. 'index' => $field['variable'],
  7334. 'width' => '80',
  7335. 'align' => 'center',
  7336. 'search' => 'false',
  7337. ];
  7338. }
  7339. }
  7340. // Inject extra session fields
  7341. $sessionField = new ExtraFieldModel('session');
  7342. $rules = $sessionField->getRules($columns, $columnModel);
  7343. if (!in_array('actions', array_column($columnModel, 'name'))) {
  7344. $columnModel[] = [
  7345. 'name' => 'actions',
  7346. 'index' => 'actions',
  7347. 'width' => '80',
  7348. 'align' => 'left',
  7349. 'formatter' => 'action_formatter',
  7350. 'sortable' => 'false',
  7351. 'search' => 'false',
  7352. ];
  7353. $columns[] = get_lang('Actions');
  7354. }
  7355. $columnName = [];
  7356. foreach ($columnModel as $col) {
  7357. $columnName[] = $col['name'];
  7358. }
  7359. $return = [
  7360. 'columns' => $columns,
  7361. 'column_model' => $columnModel,
  7362. 'rules' => $rules,
  7363. 'simple_column_name' => $columnName,
  7364. ];
  7365. return $return;
  7366. }
  7367. /**
  7368. * Converts all dates sent through the param array (given form) to correct dates with timezones.
  7369. *
  7370. * @param array The dates The same array, with times converted
  7371. * @param bool $applyFormat Whether apply the DATE_TIME_FORMAT_SHORT format for sessions
  7372. *
  7373. * @return array The same array, with times converted
  7374. */
  7375. public static function convert_dates_to_local($params, $applyFormat = false)
  7376. {
  7377. if (!is_array($params)) {
  7378. return false;
  7379. }
  7380. $params['display_start_date'] = api_get_local_time($params['display_start_date'], null, null, true);
  7381. $params['display_end_date'] = api_get_local_time($params['display_end_date'], null, null, true);
  7382. $params['access_start_date'] = api_get_local_time($params['access_start_date'], null, null, true);
  7383. $params['access_end_date'] = api_get_local_time($params['access_end_date'], null, null, true);
  7384. $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_local_time($params['coach_access_start_date'], null, null, true) : null;
  7385. $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_local_time($params['coach_access_end_date'], null, null, true) : null;
  7386. if ($applyFormat) {
  7387. if (isset($params['display_start_date'])) {
  7388. $params['display_start_date'] = api_format_date($params['display_start_date'], DATE_TIME_FORMAT_SHORT);
  7389. }
  7390. if (isset($params['display_end_date'])) {
  7391. $params['display_end_date'] = api_format_date($params['display_end_date'], DATE_TIME_FORMAT_SHORT);
  7392. }
  7393. if (isset($params['access_start_date'])) {
  7394. $params[''] = api_format_date($params['access_start_date'], DATE_TIME_FORMAT_SHORT);
  7395. }
  7396. if (isset($params['access_end_date'])) {
  7397. $params['access_end_date'] = api_format_date($params['access_end_date'], DATE_TIME_FORMAT_SHORT);
  7398. }
  7399. if (isset($params['coach_access_start_date'])) {
  7400. $params['coach_access_start_date'] = api_format_date($params['coach_access_start_date'], DATE_TIME_FORMAT_SHORT);
  7401. }
  7402. if (isset($params['coach_access_end_date'])) {
  7403. $params['coach_access_end_date'] = api_format_date($params['coach_access_end_date'], DATE_TIME_FORMAT_SHORT);
  7404. }
  7405. }
  7406. return $params;
  7407. }
  7408. /**
  7409. * Gets the admin session list callback of the session/session_list.php
  7410. * page with all user/details in the right fomat.
  7411. *
  7412. * @param array $options
  7413. *
  7414. * @return array Array of rows results
  7415. * @asset ('a') === false
  7416. */
  7417. public static function get_sessions_admin_complete($options = [])
  7418. {
  7419. if (!is_array($options)) {
  7420. return false;
  7421. }
  7422. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  7423. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  7424. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  7425. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  7426. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  7427. $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  7428. $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  7429. $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  7430. $where = 'WHERE 1 = 1 ';
  7431. $user_id = api_get_user_id();
  7432. if (!api_is_platform_admin()) {
  7433. if (api_is_session_admin() &&
  7434. api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
  7435. ) {
  7436. $where .= " AND s.session_admin_id = $user_id ";
  7437. }
  7438. }
  7439. $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
  7440. if (api_is_western_name_order()) {
  7441. $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
  7442. }
  7443. $today = api_get_utc_datetime();
  7444. $inject_extra_fields = null;
  7445. $extra_fields_info = [];
  7446. //for now only sessions
  7447. $extra_field = new ExtraFieldModel('session');
  7448. $double_fields = [];
  7449. $extra_field_option = new ExtraFieldOption('session');
  7450. if (isset($options['extra'])) {
  7451. $extra_fields = $options['extra'];
  7452. if (!empty($extra_fields)) {
  7453. foreach ($extra_fields as $extra) {
  7454. $inject_extra_fields .= " IF (fv.field_id = {$extra['id']}, fvo.option_display_text, NULL ) as {$extra['field']} , ";
  7455. if (isset($extra_fields_info[$extra['id']])) {
  7456. $info = $extra_fields_info[$extra['id']];
  7457. } else {
  7458. $info = $extra_field->get($extra['id']);
  7459. $extra_fields_info[$extra['id']] = $info;
  7460. }
  7461. if ($info['field_type'] == ExtraFieldModel::FIELD_TYPE_DOUBLE_SELECT) {
  7462. $double_fields[$info['id']] = $info;
  7463. }
  7464. }
  7465. }
  7466. }
  7467. $options_by_double = [];
  7468. foreach ($double_fields as $double) {
  7469. $my_options = $extra_field_option->get_field_options_by_field(
  7470. $double['id'],
  7471. true
  7472. );
  7473. $options_by_double['extra_'.$double['field_variable']] = $my_options;
  7474. }
  7475. //sc.name as category_name,
  7476. $select = "
  7477. SELECT * FROM (
  7478. SELECT DISTINCT
  7479. IF (
  7480. (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
  7481. (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
  7482. (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
  7483. (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
  7484. ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
  7485. , 1, 0) as session_active,
  7486. s.name,
  7487. s.nbr_courses,
  7488. s.nbr_users,
  7489. s.display_start_date,
  7490. s.display_end_date,
  7491. $coach_name,
  7492. access_start_date,
  7493. access_end_date,
  7494. s.visibility,
  7495. u.user_id,
  7496. $inject_extra_fields
  7497. c.title as course_title,
  7498. s.id ";
  7499. if (!empty($options['where'])) {
  7500. if (!empty($options['extra'])) {
  7501. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  7502. $options['where'] = str_replace('AND', 'OR', $options['where']);
  7503. foreach ($options['extra'] as $extra) {
  7504. $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
  7505. }
  7506. }
  7507. $options['where'] = str_replace('course_title', 'c.title', $options['where']);
  7508. $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
  7509. $options['where'] = str_replace(
  7510. ["AND session_active = '1' )", " AND ( session_active = '1' )"],
  7511. [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
  7512. $options['where']
  7513. );
  7514. $options['where'] = str_replace(
  7515. ["AND session_active = '0' )", " AND ( session_active = '0' )"],
  7516. [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
  7517. $options['where']
  7518. );
  7519. $where .= ' AND '.$options['where'];
  7520. }
  7521. $limit = '';
  7522. if (!empty($options['limit'])) {
  7523. $limit = " LIMIT ".$options['limit'];
  7524. }
  7525. $query = "$select FROM $tbl_session s
  7526. LEFT JOIN $tbl_session_field_values fv
  7527. ON (fv.item_id = s.id)
  7528. LEFT JOIN $extraFieldTable f
  7529. ON f.id = fv.field_id
  7530. LEFT JOIN $tbl_session_field_options fvo
  7531. ON (fv.field_id = fvo.field_id)
  7532. LEFT JOIN $tbl_session_rel_course src
  7533. ON (src.session_id = s.id)
  7534. LEFT JOIN $tbl_course c
  7535. ON (src.c_id = c.id)
  7536. LEFT JOIN $tbl_session_category sc
  7537. ON (s.session_category_id = sc.id)
  7538. INNER JOIN $tbl_user u
  7539. ON (s.id_coach = u.user_id)
  7540. $where
  7541. $limit
  7542. ";
  7543. if (api_is_multiple_url_enabled()) {
  7544. $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  7545. $access_url_id = api_get_current_access_url_id();
  7546. if ($access_url_id != -1) {
  7547. $query = "$select
  7548. FROM $tbl_session s
  7549. LEFT JOIN $tbl_session_field_values fv
  7550. ON (fv.item_id = s.id)
  7551. LEFT JOIN $tbl_session_field_options fvo
  7552. ON (fv.field_id = fvo.field_id)
  7553. LEFT JOIN $tbl_session_rel_course src
  7554. ON (src.session_id = s.id)
  7555. LEFT JOIN $tbl_course c
  7556. ON (src.c_id = c.id)
  7557. LEFT JOIN $tbl_session_category sc
  7558. ON (s.session_category_id = sc.id)
  7559. INNER JOIN $tbl_user u
  7560. ON (s.id_coach = u.user_id)
  7561. INNER JOIN $table_access_url_rel_session ar
  7562. ON (ar.session_id = s.id AND ar.access_url_id = $access_url_id)
  7563. $where
  7564. $limit
  7565. ";
  7566. }
  7567. }
  7568. $query .= ") AS session_table";
  7569. if (!empty($options['order'])) {
  7570. $query .= " ORDER BY ".$options['order'];
  7571. }
  7572. $result = Database::query($query);
  7573. $acceptIcon = Display::return_icon(
  7574. 'accept.png',
  7575. get_lang('Active'),
  7576. [],
  7577. ICON_SIZE_SMALL
  7578. );
  7579. $errorIcon = Display::return_icon(
  7580. 'error.png',
  7581. get_lang('Inactive'),
  7582. [],
  7583. ICON_SIZE_SMALL
  7584. );
  7585. $formatted_sessions = [];
  7586. if (Database::num_rows($result)) {
  7587. $sessions = Database::store_result($result, 'ASSOC');
  7588. foreach ($sessions as $session) {
  7589. $session_id = $session['id'];
  7590. $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
  7591. $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
  7592. if ($session['session_active'] == 1) {
  7593. $session['session_active'] = $acceptIcon;
  7594. } else {
  7595. $session['session_active'] = $errorIcon;
  7596. }
  7597. $session = self::convert_dates_to_local($session);
  7598. switch ($session['visibility']) {
  7599. case SESSION_VISIBLE_READ_ONLY: //1
  7600. $session['visibility'] = get_lang('ReadOnly');
  7601. break;
  7602. case SESSION_VISIBLE: //2
  7603. case SESSION_AVAILABLE: //4
  7604. $session['visibility'] = get_lang('Visible');
  7605. break;
  7606. case SESSION_INVISIBLE: //3
  7607. $session['visibility'] = api_ucfirst(get_lang('Invisible'));
  7608. break;
  7609. }
  7610. // Cleaning double selects
  7611. foreach ($session as $key => &$value) {
  7612. if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
  7613. $options = explode('::', $value);
  7614. }
  7615. $original_key = $key;
  7616. if (strpos($key, '_second') === false) {
  7617. } else {
  7618. $key = str_replace('_second', '', $key);
  7619. }
  7620. if (isset($options_by_double[$key])) {
  7621. if (isset($options[0])) {
  7622. if (isset($options_by_double[$key][$options[0]])) {
  7623. if (strpos($original_key, '_second') === false) {
  7624. $value = $options_by_double[$key][$options[0]]['option_display_text'];
  7625. } else {
  7626. $value = $options_by_double[$key][$options[1]]['option_display_text'];
  7627. }
  7628. }
  7629. }
  7630. }
  7631. }
  7632. // Magic filter
  7633. if (isset($formatted_sessions[$session_id])) {
  7634. $formatted_sessions[$session_id] = self::compareArraysToMerge(
  7635. $formatted_sessions[$session_id],
  7636. $session
  7637. );
  7638. } else {
  7639. $formatted_sessions[$session_id] = $session;
  7640. }
  7641. }
  7642. }
  7643. return $formatted_sessions;
  7644. }
  7645. /**
  7646. * Compare two arrays.
  7647. *
  7648. * @param array $array1
  7649. * @param array $array2
  7650. *
  7651. * @return array
  7652. */
  7653. public static function compareArraysToMerge($array1, $array2)
  7654. {
  7655. if (empty($array2)) {
  7656. return $array1;
  7657. }
  7658. foreach ($array1 as $key => $item) {
  7659. if (!isset($array1[$key])) {
  7660. //My string is empty try the other one
  7661. if (isset($array2[$key]) && !empty($array2[$key])) {
  7662. $array1[$key] = $array2[$key];
  7663. }
  7664. }
  7665. }
  7666. return $array1;
  7667. }
  7668. /**
  7669. * Get link to the admin page for this session.
  7670. *
  7671. * @param int $id Session ID
  7672. *
  7673. * @return mixed URL to the admin page to manage the session, or false on error
  7674. */
  7675. public static function getAdminPath($id)
  7676. {
  7677. $id = (int) $id;
  7678. $session = self::fetch($id);
  7679. if (empty($session)) {
  7680. return false;
  7681. }
  7682. return api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$id;
  7683. }
  7684. /**
  7685. * Get link to the user page for this session.
  7686. * If a course is provided, build the link to the course.
  7687. *
  7688. * @param int $id Session ID
  7689. * @param int $courseId Course ID (optional) in case the link has to send straight to the course
  7690. *
  7691. * @return mixed URL to the page to use the session, or false on error
  7692. */
  7693. public static function getPath($id, $courseId = 0)
  7694. {
  7695. $id = (int) $id;
  7696. $session = self::fetch($id);
  7697. if (empty($session)) {
  7698. return false;
  7699. }
  7700. if (empty($courseId)) {
  7701. return api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$id;
  7702. } else {
  7703. $courseInfo = api_get_course_info_by_id($courseId);
  7704. if ($courseInfo) {
  7705. return $courseInfo['course_public_url'].'?id_session='.$id;
  7706. }
  7707. }
  7708. return false;
  7709. }
  7710. /**
  7711. * Return an associative array 'id_course' => [id_session1, id_session2...]
  7712. * where course id_course is in sessions id_session1, id_session2
  7713. * for course where user is coach
  7714. * i.e. coach for the course or
  7715. * main coach for a session the course is in
  7716. * for a session category (or woth no session category if empty).
  7717. *
  7718. * @param int $userId
  7719. *
  7720. * @return array
  7721. */
  7722. public static function getSessionCourseForUser($userId)
  7723. {
  7724. // list of COURSES where user is COURSE session coach
  7725. $listCourseCourseCoachSession = self::getCoursesForCourseSessionCoach($userId);
  7726. // list of courses where user is MAIN session coach
  7727. $listCourseMainCoachSession = self::getCoursesForMainSessionCoach($userId);
  7728. // merge these 2 array
  7729. $listResCourseSession = $listCourseCourseCoachSession;
  7730. foreach ($listCourseMainCoachSession as $courseId2 => $listSessionId2) {
  7731. if (isset($listResCourseSession[$courseId2])) {
  7732. // if sessionId array exists for this course
  7733. // same courseId, merge the list of session
  7734. foreach ($listCourseMainCoachSession[$courseId2] as $i => $sessionId2) {
  7735. if (!in_array($sessionId2, $listResCourseSession[$courseId2])) {
  7736. $listResCourseSession[$courseId2][] = $sessionId2;
  7737. }
  7738. }
  7739. } else {
  7740. $listResCourseSession[$courseId2] = $listSessionId2;
  7741. }
  7742. }
  7743. return $listResCourseSession;
  7744. }
  7745. /**
  7746. * Return an associative array 'id_course' => [id_session1, id_session2...]
  7747. * where course id_course is in sessions id_session1, id_session2.
  7748. *
  7749. * @param int $userId
  7750. *
  7751. * @return array
  7752. */
  7753. public static function getCoursesForCourseSessionCoach($userId)
  7754. {
  7755. $userId = (int) $userId;
  7756. $listResCourseSession = [];
  7757. $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  7758. $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  7759. $sql = "SELECT session_id, c_id, c.id
  7760. FROM $tblSessionRelCourseRelUser srcru
  7761. LEFT JOIN $tblCourse c
  7762. ON c.id = srcru.c_id
  7763. WHERE
  7764. srcru.user_id = $userId AND
  7765. srcru.status = 2";
  7766. $res = Database::query($sql);
  7767. while ($data = Database::fetch_assoc($res)) {
  7768. if (api_get_session_visibility($data['session_id'])) {
  7769. if (!isset($listResCourseSession[$data['id']])) {
  7770. $listResCourseSession[$data['id']] = [];
  7771. }
  7772. $listResCourseSession[$data['id']][] = $data['session_id'];
  7773. }
  7774. }
  7775. return $listResCourseSession;
  7776. }
  7777. /**
  7778. * Return an associative array 'id_course' => [id_session1, id_session2...]
  7779. * where course id_course is in sessions id_session1, id_session2.
  7780. *
  7781. * @param $userId
  7782. *
  7783. * @return array
  7784. */
  7785. public static function getCoursesForMainSessionCoach($userId)
  7786. {
  7787. $userId = (int) $userId;
  7788. $listResCourseSession = [];
  7789. $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
  7790. // list of SESSION where user is session coach
  7791. $sql = "SELECT id FROM $tblSession
  7792. WHERE id_coach = ".$userId;
  7793. $res = Database::query($sql);
  7794. while ($data = Database::fetch_assoc($res)) {
  7795. $sessionId = $data['id'];
  7796. $listCoursesInSession = self::getCoursesInSession($sessionId);
  7797. foreach ($listCoursesInSession as $i => $courseId) {
  7798. if (api_get_session_visibility($sessionId)) {
  7799. if (!isset($listResCourseSession[$courseId])) {
  7800. $listResCourseSession[$courseId] = [];
  7801. }
  7802. $listResCourseSession[$courseId][] = $sessionId;
  7803. }
  7804. }
  7805. }
  7806. return $listResCourseSession;
  7807. }
  7808. /**
  7809. * Return an array of course_id used in session $sessionId.
  7810. *
  7811. * @param $sessionId
  7812. *
  7813. * @return array
  7814. */
  7815. public static function getCoursesInSession($sessionId)
  7816. {
  7817. if (empty($sessionId)) {
  7818. return [];
  7819. }
  7820. $tblSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  7821. $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  7822. // list of course in this session
  7823. $sql = "SELECT session_id, c.id
  7824. FROM $tblSessionRelCourse src
  7825. LEFT JOIN $tblCourse c
  7826. ON c.id = src.c_id
  7827. WHERE session_id = ".intval($sessionId);
  7828. $res = Database::query($sql);
  7829. $listResultsCourseId = [];
  7830. while ($data = Database::fetch_assoc($res)) {
  7831. $listResultsCourseId[] = $data['id'];
  7832. }
  7833. return $listResultsCourseId;
  7834. }
  7835. /**
  7836. * Return an array of courses in session for user
  7837. * and for each courses the list of session that use this course for user.
  7838. *
  7839. * [0] => array
  7840. * userCatId
  7841. * userCatTitle
  7842. * courseInUserCatList
  7843. * [0] => array
  7844. * courseId
  7845. * title
  7846. * courseCode
  7847. * sessionCatList
  7848. * [0] => array
  7849. * catSessionId
  7850. * catSessionName
  7851. * sessionList
  7852. * [0] => array
  7853. * sessionId
  7854. * sessionName
  7855. *
  7856. * @param int $userId
  7857. *
  7858. * @return array
  7859. */
  7860. public static function getNamedSessionCourseForCoach($userId)
  7861. {
  7862. $listResults = [];
  7863. $listCourseSession = self::getSessionCourseForUser($userId);
  7864. foreach ($listCourseSession as $courseId => $listSessionId) {
  7865. // Course info
  7866. $courseInfo = api_get_course_info_by_id($courseId);
  7867. $listOneCourse = [];
  7868. $listOneCourse['courseId'] = $courseId;
  7869. $listOneCourse['title'] = $courseInfo['title'];
  7870. //$listOneCourse['courseCode'] = $courseInfo['code'];
  7871. $listOneCourse['course'] = $courseInfo;
  7872. $listOneCourse['sessionCatList'] = [];
  7873. $listCat = [];
  7874. foreach ($listSessionId as $i => $sessionId) {
  7875. // here we got all session for this course
  7876. // lets check there session categories
  7877. $sessionInfo = self::fetch($sessionId);
  7878. $catId = $sessionInfo['session_category_id'];
  7879. if (!isset($listCat[$catId])) {
  7880. $listCatInfo = self::get_session_category($catId);
  7881. $listCat[$catId] = [];
  7882. $listCat[$catId]['catSessionId'] = $catId;
  7883. $listCat[$catId]['catSessionName'] = $listCatInfo['name'];
  7884. $listCat[$catId]['sessionList'] = [];
  7885. }
  7886. $listSessionInfo = self::fetch($sessionId);
  7887. $listSessionIdName = [
  7888. 'sessionId' => $sessionId,
  7889. 'sessionName' => $listSessionInfo['name'],
  7890. ];
  7891. $listCat[$catId]['sessionList'][] = $listSessionIdName;
  7892. }
  7893. // sort $listCat by catSessionName
  7894. usort($listCat, 'self::compareBySessionName');
  7895. // in each catSession sort sessionList by sessionName
  7896. foreach ($listCat as $i => $listCatSessionInfo) {
  7897. $listSessionList = $listCatSessionInfo['sessionList'];
  7898. usort($listSessionList, 'self::compareCatSessionInfo');
  7899. $listCat[$i]['sessionList'] = $listSessionList;
  7900. }
  7901. $listOneCourse['sessionCatList'] = $listCat;
  7902. // user course category
  7903. $courseCategory = CourseManager::getUserCourseCategoryForCourse(
  7904. $userId,
  7905. $courseId
  7906. );
  7907. $userCatTitle = '';
  7908. $userCatId = 0;
  7909. if ($courseCategory) {
  7910. $userCatId = $courseCategory['user_course_cat'];
  7911. $userCatTitle = $courseCategory['title'];
  7912. }
  7913. $listResults[$userCatId]['courseInUserCategoryId'] = $userCatId;
  7914. $listResults[$userCatId]['courseInUserCategoryTitle'] = $userCatTitle;
  7915. $listResults[$userCatId]['courseInUserCatList'][] = $listOneCourse;
  7916. }
  7917. // sort by user course cat
  7918. uasort($listResults, 'self::compareByUserCourseCat');
  7919. // sort by course title
  7920. foreach ($listResults as $userCourseCatId => $tabCoursesInCat) {
  7921. $courseInUserCatList = $tabCoursesInCat['courseInUserCatList'];
  7922. uasort($courseInUserCatList, 'self::compareByCourse');
  7923. $listResults[$userCourseCatId]['courseInUserCatList'] = $courseInUserCatList;
  7924. }
  7925. return $listResults;
  7926. }
  7927. /**
  7928. * @param int $userId
  7929. * @param int $courseId
  7930. *
  7931. * @return array
  7932. */
  7933. public static function searchCourseInSessionsFromUser($userId, $courseId)
  7934. {
  7935. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  7936. $userId = (int) $userId;
  7937. $courseId = (int) $courseId;
  7938. if (empty($userId) || empty($courseId)) {
  7939. return [];
  7940. }
  7941. $sql = "SELECT * FROM $table
  7942. WHERE c_id = $courseId AND user_id = $userId";
  7943. $result = Database::query($sql);
  7944. return Database::store_result($result, 'ASSOC');
  7945. }
  7946. /**
  7947. * Subscribe and redirect to session after inscription.
  7948. */
  7949. public static function redirectToSession()
  7950. {
  7951. $sessionId = (int) ChamiloSession::read('session_redirect');
  7952. $onlyOneCourseSessionToRedirect = ChamiloSession::read('only_one_course_session_redirect');
  7953. if ($sessionId) {
  7954. $sessionInfo = api_get_session_info($sessionId);
  7955. if (!empty($sessionInfo)) {
  7956. $userId = api_get_user_id();
  7957. $response = self::isUserSubscribedAsStudent($sessionId, $userId);
  7958. if ($response) {
  7959. $urlToRedirect = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
  7960. if (!empty($onlyOneCourseSessionToRedirect)) {
  7961. $urlToRedirect = api_get_path(WEB_PATH).
  7962. 'courses/'.$onlyOneCourseSessionToRedirect.'/index.php?id_session='.$sessionId;
  7963. }
  7964. header('Location: '.$urlToRedirect);
  7965. exit;
  7966. }
  7967. }
  7968. }
  7969. }
  7970. /**
  7971. * @param Course $course
  7972. * @param Session $session
  7973. *
  7974. * @return int
  7975. */
  7976. public static function getCountUsersInCourseSession(
  7977. Course $course,
  7978. Session $session
  7979. ) {
  7980. return Database::getManager()
  7981. ->createQuery("
  7982. SELECT COUNT(scu)
  7983. FROM ChamiloCoreBundle:SessionRelCourseRelUser scu
  7984. INNER JOIN ChamiloCoreBundle:SessionRelUser su
  7985. WITH scu.user = su.user
  7986. AND scu.session = su.session
  7987. WHERE
  7988. scu.course = :course AND
  7989. su.relationType <> :relationType AND
  7990. scu.session = :session
  7991. ")
  7992. ->setParameters([
  7993. 'course' => $course->getId(),
  7994. 'relationType' => SESSION_RELATION_TYPE_RRHH,
  7995. 'session' => $session->getId(),
  7996. ])
  7997. ->getSingleScalarResult();
  7998. }
  7999. /**
  8000. * Get course IDs where user in not subscribed in session.
  8001. *
  8002. * @param User $user
  8003. * @param Session $session
  8004. *
  8005. * @return array
  8006. */
  8007. public static function getAvoidedCoursesInSession(User $user, Session $session)
  8008. {
  8009. $courseIds = [];
  8010. /** @var SessionRelCourse $sessionCourse */
  8011. foreach ($session->getCourses() as $sessionCourse) {
  8012. /** @var Course $course */
  8013. $course = $sessionCourse->getCourse();
  8014. if ($session->getUserInCourse($user, $course)->count()) {
  8015. continue;
  8016. }
  8017. $courseIds[] = $course->getId();
  8018. }
  8019. return $courseIds;
  8020. }
  8021. /**
  8022. * @param int $userId
  8023. * @param int $sessionId
  8024. * @param ExtraFieldValue $extraFieldValue
  8025. * @param string $collapsableLink
  8026. *
  8027. * @return array
  8028. */
  8029. public static function getCollapsableData($userId, $sessionId, $extraFieldValue, $collapsableLink)
  8030. {
  8031. $collapsed = 0;
  8032. // Get default collapsed value in extra field
  8033. $value = $extraFieldValue->get_values_by_handler_and_field_variable($sessionId, 'collapsed');
  8034. if (!empty($value) && isset($value['value'])) {
  8035. $collapsed = $value['value'];
  8036. }
  8037. $userRelSession = self::getUserSession($userId, $sessionId);
  8038. if ($userRelSession) {
  8039. if (isset($userRelSession['collapsed']) && $userRelSession['collapsed'] != '') {
  8040. $collapsed = $userRelSession['collapsed'];
  8041. }
  8042. } else {
  8043. return ['collapsed' => $collapsed, 'collapsable_link' => '&nbsp;'];
  8044. }
  8045. $link = $collapsableLink.'&session_id='.$sessionId.'&value=1';
  8046. $image = '<i class="fa fa-folder-open"></i>';
  8047. if ($collapsed == 1) {
  8048. $link = $collapsableLink.'&session_id='.$sessionId.'&value=0';
  8049. $image = '<i class="fa fa-folder"></i>';
  8050. }
  8051. $link = Display::url(
  8052. $image,
  8053. $link
  8054. );
  8055. return ['collapsed' => $collapsed, 'collapsable_link' => $link];
  8056. }
  8057. /**
  8058. * Converts "start date" and "end date" to "From start date to end date" string.
  8059. *
  8060. * @param string $startDate
  8061. * @param string $endDate
  8062. * @param bool $showTime
  8063. * @param bool $dateHuman
  8064. *
  8065. * @return string
  8066. */
  8067. public static function convertSessionDateToString($startDate, $endDate, $showTime, $dateHuman)
  8068. {
  8069. // api_get_local_time returns empty if date is invalid like 0000-00-00 00:00:00
  8070. $startDateToLocal = api_get_local_time(
  8071. $startDate,
  8072. null,
  8073. null,
  8074. true,
  8075. $showTime,
  8076. $dateHuman
  8077. );
  8078. $endDateToLocal = api_get_local_time(
  8079. $endDate,
  8080. null,
  8081. null,
  8082. true,
  8083. $showTime,
  8084. $dateHuman
  8085. );
  8086. $format = $showTime ? DATE_TIME_FORMAT_LONG_24H : DATE_FORMAT_LONG_NO_DAY;
  8087. $result = '';
  8088. if (!empty($startDateToLocal) && !empty($endDateToLocal)) {
  8089. $result = sprintf(
  8090. get_lang('FromDateXToDateY'),
  8091. api_format_date($startDateToLocal, $format),
  8092. api_format_date($endDateToLocal, $format)
  8093. );
  8094. } else {
  8095. if (!empty($startDateToLocal)) {
  8096. $result = get_lang('From').' '.api_format_date($startDateToLocal, $format);
  8097. }
  8098. if (!empty($endDateToLocal)) {
  8099. $result = get_lang('Until').' '.api_format_date($endDateToLocal, $format);
  8100. }
  8101. }
  8102. if (empty($result)) {
  8103. $result = get_lang('NoTimeLimits');
  8104. }
  8105. return $result;
  8106. }
  8107. /**
  8108. * @param int $id
  8109. *
  8110. * @return bool
  8111. */
  8112. private static function allowed($id)
  8113. {
  8114. $sessionInfo = self::fetch($id);
  8115. if (empty($sessionInfo)) {
  8116. return false;
  8117. }
  8118. if (api_is_platform_admin()) {
  8119. return true;
  8120. }
  8121. $userId = api_get_user_id();
  8122. if (api_is_session_admin() &&
  8123. api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true'
  8124. ) {
  8125. if ($sessionInfo['session_admin_id'] != $userId) {
  8126. return false;
  8127. }
  8128. }
  8129. if (api_is_teacher() &&
  8130. api_get_setting('allow_teachers_to_create_sessions') == 'true'
  8131. ) {
  8132. if ($sessionInfo['id_coach'] != $userId) {
  8133. return false;
  8134. }
  8135. }
  8136. return true;
  8137. }
  8138. /**
  8139. * Add classes (by their names) to a session.
  8140. *
  8141. * @param int $sessionId
  8142. * @param array $classesNames
  8143. * @param bool $deleteClassSessions Optional. Empty the session list for the usergroup (class)
  8144. */
  8145. private static function addClassesByName($sessionId, $classesNames, $deleteClassSessions = true)
  8146. {
  8147. if (!$classesNames) {
  8148. return;
  8149. }
  8150. $usergroup = new UserGroup();
  8151. foreach ($classesNames as $className) {
  8152. if (empty($className)) {
  8153. continue;
  8154. }
  8155. $usergroup->subscribe_sessions_to_usergroup(
  8156. $usergroup->getIdByName($className),
  8157. [$sessionId],
  8158. $deleteClassSessions
  8159. );
  8160. }
  8161. }
  8162. /**
  8163. * @param array $listA
  8164. * @param array $listB
  8165. *
  8166. * @return int
  8167. */
  8168. private static function compareCatSessionInfo($listA, $listB)
  8169. {
  8170. if ($listA['sessionName'] == $listB['sessionName']) {
  8171. return 0;
  8172. } elseif ($listA['sessionName'] > $listB['sessionName']) {
  8173. return 1;
  8174. } else {
  8175. return -1;
  8176. }
  8177. }
  8178. /**
  8179. * @param array $listA
  8180. * @param array $listB
  8181. *
  8182. * @return int
  8183. */
  8184. private static function compareBySessionName($listA, $listB)
  8185. {
  8186. if ($listB['catSessionName'] == '') {
  8187. return -1;
  8188. } elseif ($listA['catSessionName'] == '') {
  8189. return 1;
  8190. } elseif ($listA['catSessionName'] == $listB['catSessionName']) {
  8191. return 0;
  8192. } elseif ($listA['catSessionName'] > $listB['catSessionName']) {
  8193. return 1;
  8194. } else {
  8195. return -1;
  8196. }
  8197. }
  8198. /**
  8199. * @param array $listA
  8200. * @param array $listB
  8201. *
  8202. * @return int
  8203. */
  8204. private static function compareByUserCourseCat($listA, $listB)
  8205. {
  8206. if ($listA['courseInUserCategoryTitle'] == $listB['courseInUserCategoryTitle']) {
  8207. return 0;
  8208. } elseif ($listA['courseInUserCategoryTitle'] > $listB['courseInUserCategoryTitle']) {
  8209. return 1;
  8210. } else {
  8211. return -1;
  8212. }
  8213. }
  8214. /**
  8215. * @param array $listA
  8216. * @param array $listB
  8217. *
  8218. * @return int
  8219. */
  8220. private static function compareByCourse($listA, $listB)
  8221. {
  8222. if ($listA['title'] == $listB['title']) {
  8223. return 0;
  8224. } elseif ($listA['title'] > $listB['title']) {
  8225. return 1;
  8226. } else {
  8227. return -1;
  8228. }
  8229. }
  8230. }