sessionmanager.lib.php 350 KB

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