sessionmanager.lib.php 344 KB

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