sessionmanager.lib.php 327 KB

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