sessionmanager.lib.php 315 KB

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