sessionmanager.lib.php 331 KB

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