sessionmanager.lib.php 335 KB

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