sessionmanager.lib.php 343 KB

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