sessionmanager.lib.php 342 KB

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