sessionmanager.lib.php 346 KB

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