sessionmanager.lib.php 346 KB

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