sessionmanager.lib.php 243 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class SessionManager
  5. *
  6. * This is the session library for Chamilo.
  7. * All main sessions functions should be placed here.
  8. * This class provides methods for sessions management.
  9. * Include/require it in your code to use its features.
  10. *
  11. * @package chamilo.library
  12. *
  13. */
  14. class SessionManager
  15. {
  16. public static $_debug = false;
  17. /**
  18. * Constructor
  19. */
  20. public function __construct()
  21. {
  22. }
  23. /**
  24. * Fetches a session from the database
  25. * @param int $id Session Id
  26. *
  27. * @return array Session details
  28. */
  29. public static function fetch($id)
  30. {
  31. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  32. if ($id != strval(intval($id))) {
  33. return array();
  34. }
  35. $s = "SELECT * FROM $t WHERE id = $id";
  36. $r = Database::query($s);
  37. if (Database::num_rows($r) != 1) {
  38. return array();
  39. }
  40. return Database::fetch_array($r, 'ASSOC');
  41. }
  42. /**
  43. * Create a session
  44. * @author Carlos Vargas <carlos.vargas@beeznest.com>, from existing code
  45. * @param string name
  46. * @param integer Start year (yyyy)
  47. * @param integer Start month (mm)
  48. * @param integer Start day (dd)
  49. * @param integer End year (yyyy)
  50. * @param integer End month (mm)
  51. * @param integer End day (dd)
  52. * @param integer Number of days that the coach can access the session before the start date
  53. * @param integer Number of days that the coach can access the session after the end date
  54. * @param integer If 1, means there are no date limits
  55. * @param mixed If integer, this is the session coach id, if string, the coach ID will be looked for from the user table
  56. * @param integer ID of the session category in which this session is registered
  57. * @param integer Visibility after end date (0 = read-only, 1 = invisible, 2 = accessible)
  58. * @param string Start limit = true if the start date has to be considered
  59. * @param string End limit = true if the end date has to be considered
  60. * @param string $fix_name
  61. * @todo use an array to replace all this parameters or use the model.lib.php ...
  62. * @return mixed Session ID on success, error message otherwise
  63. * */
  64. public static function create_session(
  65. $sname,
  66. $syear_start,
  67. $smonth_start,
  68. $sday_start,
  69. $syear_end,
  70. $smonth_end,
  71. $sday_end,
  72. $snb_days_acess_before,
  73. $snb_days_acess_after,
  74. $nolimit,
  75. $coach_username,
  76. $id_session_category,
  77. $id_visibility,
  78. $start_limit = true,
  79. $end_limit = true,
  80. $fix_name = false,
  81. $duration = null,
  82. $showDescription = null
  83. ) {
  84. global $_configuration;
  85. //Check portal limits
  86. $access_url_id = 1;
  87. if (api_get_multiple_access_url()) {
  88. $access_url_id = api_get_current_access_url_id();
  89. }
  90. if (is_array($_configuration[$access_url_id]) &&
  91. isset($_configuration[$access_url_id]['hosting_limit_sessions']) &&
  92. $_configuration[$access_url_id]['hosting_limit_sessions'] > 0
  93. ) {
  94. $num = self::count_sessions();
  95. if ($num >= $_configuration[$access_url_id]['hosting_limit_sessions']) {
  96. api_warn_hosting_contact('hosting_limit_sessions');
  97. return get_lang('PortalSessionsLimitReached');
  98. }
  99. }
  100. $name = Database::escape_string(trim($sname));
  101. $year_start = intval($syear_start);
  102. $month_start = intval($smonth_start);
  103. $day_start = intval($sday_start);
  104. $year_end = intval($syear_end);
  105. $month_end = intval($smonth_end);
  106. $day_end = intval($sday_end);
  107. $nb_days_acess_before = intval($snb_days_acess_before);
  108. $nb_days_acess_after = intval($snb_days_acess_after);
  109. $id_session_category = intval($id_session_category);
  110. $id_visibility = intval($id_visibility);
  111. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  112. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  113. if (is_int($coach_username)) {
  114. $id_coach = $coach_username;
  115. } else {
  116. $sql = 'SELECT user_id FROM ' . $tbl_user . ' WHERE username="' . Database::escape_string($coach_username) . '"';
  117. $rs = Database::query($sql);
  118. $id_coach = Database::result($rs, 0, 'user_id');
  119. }
  120. if (empty($nolimit)) {
  121. $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
  122. $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
  123. } else {
  124. $id_visibility = 1; // by default session visibility is read only
  125. $date_start = "0000-00-00";
  126. $date_end = "0000-00-00";
  127. }
  128. if (empty($end_limit)) {
  129. $date_end = "0000-00-00";
  130. $id_visibility = 1; // by default session visibility is read only
  131. }
  132. if (empty($start_limit)) {
  133. $date_start = "0000-00-00";
  134. }
  135. if (empty($name)) {
  136. $msg = get_lang('SessionNameIsRequired');
  137. return $msg;
  138. } elseif (empty($coach_username)) {
  139. $msg = get_lang('CoachIsRequired');
  140. return $msg;
  141. } elseif (!empty($start_limit) && empty($nolimit) && (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start))) {
  142. $msg = get_lang('InvalidStartDate');
  143. return $msg;
  144. } elseif (!empty($end_limit) && empty($nolimit) && (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end))) {
  145. $msg = get_lang('InvalidEndDate');
  146. return $msg;
  147. } elseif (!empty($start_limit) && !empty($end_limit) && empty($nolimit) && $date_start >= $date_end) {
  148. $msg = get_lang('StartDateShouldBeBeforeEndDate');
  149. return $msg;
  150. } else {
  151. $ready_to_create = false;
  152. if ($fix_name) {
  153. $name = self::generate_nice_next_session_name($name);
  154. if ($name) {
  155. $ready_to_create = true;
  156. } else {
  157. $msg = get_lang('SessionNameAlreadyExists');
  158. return $msg;
  159. }
  160. } else {
  161. $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='" . $name . "'");
  162. if (Database::num_rows($rs)) {
  163. $msg = get_lang('SessionNameAlreadyExists');
  164. return $msg;
  165. }
  166. $ready_to_create = true;
  167. }
  168. if ($ready_to_create) {
  169. $sql = "INSERT INTO $tbl_session(name,date_start,date_end,id_coach,session_admin_id, nb_days_access_before_beginning, nb_days_access_after_end, session_category_id,visibility)
  170. VALUES('" . $name . "','$date_start','$date_end','$id_coach'," . api_get_user_id() . "," . $nb_days_acess_before . ", " . $nb_days_acess_after . ", " . $id_session_category . ", " . $id_visibility . ")";
  171. Database::query($sql);
  172. $session_id = Database::insert_id();
  173. if (self::durationPerUserIsEnabled()) {
  174. $duration = intval($duration);
  175. if (empty($duration)) {
  176. $duration = null;
  177. } else {
  178. $sql = "UPDATE $tbl_session SET
  179. date_start = '0000-00-00',
  180. date_end = '0000-00-00'
  181. WHERE id = $session_id";
  182. Database::query($sql);
  183. }
  184. $sql = "UPDATE $tbl_session
  185. SET duration = '$duration'
  186. WHERE id = $session_id";
  187. Database::query($sql);
  188. }
  189. if (!is_null($showDescription)) {
  190. $showDescription = intval($showDescription);
  191. $sql = "UPDATE $tbl_session
  192. SET show_description = '$showDescription'
  193. WHERE id = $session_id";
  194. Database::query($sql);
  195. }
  196. if (!empty($session_id)) {
  197. /*
  198. Sends a message to the user_id = 1
  199. $user_info = api_get_user_info(1);
  200. $complete_name = $user_info['firstname'].' '.$user_info['lastname'];
  201. $subject = api_get_setting('siteName').' - '.get_lang('ANewSessionWasCreated');
  202. $message = get_lang('ANewSessionWasCreated')." <br /> ".get_lang('NameOfTheSession').' : '.$name;
  203. api_mail_html($complete_name, $user_info['email'], $subject, $message);
  204. *
  205. */
  206. //Adding to the correct URL
  207. $access_url_id = api_get_current_access_url_id();
  208. UrlManager::add_session_to_url($session_id, $access_url_id);
  209. // add event to system log
  210. $user_id = api_get_user_id();
  211. event_system(
  212. LOG_SESSION_CREATE,
  213. LOG_SESSION_ID,
  214. $session_id,
  215. api_get_utc_datetime(),
  216. $user_id
  217. );
  218. }
  219. return $session_id;
  220. }
  221. }
  222. }
  223. /**
  224. * @param string $name
  225. * @return bool
  226. */
  227. public static function session_name_exists($name)
  228. {
  229. $name = Database::escape_string($name);
  230. $sql = "SELECT COUNT(*) as count FROM " . Database::get_main_table(TABLE_MAIN_SESSION) . "
  231. WHERE name = '$name'";
  232. $result = Database::fetch_array(Database::query($sql));
  233. return $result['count'] > 0;
  234. }
  235. /**
  236. * @param string $where_condition
  237. * @return mixed
  238. */
  239. public static function get_count_admin($where_condition = null)
  240. {
  241. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  242. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  243. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  244. $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  245. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  246. $where = 'WHERE 1=1 ';
  247. $user_id = api_get_user_id();
  248. $extraJoin = null;
  249. if (api_is_session_admin() &&
  250. api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
  251. ) {
  252. $where .= " AND (
  253. s.session_admin_id = $user_id OR
  254. sru.id_user = '$user_id' AND
  255. sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "'
  256. )
  257. ";
  258. $extraJoin = " INNER JOIN $tbl_session_rel_user sru
  259. ON sru.id_session = s.id ";
  260. }
  261. $today = api_get_utc_datetime();
  262. $today = api_strtotime($today, 'UTC');
  263. $today = date('Y-m-d', $today);
  264. if (!empty($where_condition)) {
  265. $where_condition = str_replace("( session_active = ':' )", '1=1', $where_condition);
  266. $where_condition = str_replace('category_name', 'sc.name', $where_condition);
  267. $where_condition = str_replace(
  268. array("AND session_active = '1' )", " AND ( session_active = '1' )"),
  269. array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
  270. , $where_condition
  271. );
  272. $where_condition = str_replace(
  273. array("AND session_active = '0' )", " AND ( session_active = '0' )"),
  274. array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
  275. $where_condition
  276. );
  277. } else {
  278. $where_condition = " AND 1 = 1";
  279. }
  280. $courseCondition = null;
  281. if (strpos($where_condition, 'c.id')) {
  282. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  283. $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  284. $courseCondition = " INNER JOIN $table course_rel_session ON (s.id = course_rel_session.id_session)
  285. INNER JOIN $tableCourse c ON (course_rel_session.course_code = c.code)
  286. ";
  287. }
  288. $sql = "SELECT COUNT(id) as total_rows FROM (
  289. SELECT DISTINCT
  290. IF (
  291. (s.date_start <= '$today' AND '$today' <= s.date_end) OR
  292. (s.nb_days_access_before_beginning > 0 AND DATEDIFF(s.date_start, '$today') <= s.nb_days_access_before_beginning) OR
  293. (s.nb_days_access_after_end > 0 AND DATEDIFF('$today',s.date_end) <= s.nb_days_access_after_end) OR
  294. (s.date_start = '0000-00-00' AND s.date_end = '0000-00-00' ) OR
  295. (s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
  296. ('$today' <= s.date_end AND '0000-00-00' = s.date_start)
  297. , 1, 0) as session_active,
  298. s.id
  299. FROM $tbl_session s
  300. LEFT JOIN $tbl_session_category sc ON s.session_category_id = sc.id
  301. INNER JOIN $tbl_user u ON s.id_coach = u.user_id
  302. $courseCondition
  303. $extraJoin
  304. $where $where_condition ) as session_table";
  305. if (api_is_multiple_url_enabled()) {
  306. $access_url_id = api_get_current_access_url_id();
  307. if ($access_url_id != -1) {
  308. $where.= " AND ar.access_url_id = $access_url_id ";
  309. $sql = "SELECT count(id) as total_rows FROM (
  310. SELECT DISTINCT
  311. IF (
  312. (s.date_start <= '$today' AND '$today' <= s.date_end) OR
  313. (s.nb_days_access_before_beginning > 0 AND DATEDIFF(s.date_start, '$today') <= s.nb_days_access_before_beginning) OR
  314. (s.nb_days_access_after_end > 0 AND DATEDIFF('$today',s.date_end) <= s.nb_days_access_after_end) OR
  315. (s.date_start = '0000-00-00' AND s.date_end = '0000-00-00' ) OR
  316. (s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
  317. ('$today' <= s.date_end AND '0000-00-00' = s.date_start)
  318. , 1, 0)
  319. as session_active,
  320. s.id
  321. FROM $tbl_session s
  322. LEFT JOIN $tbl_session_category sc ON s.session_category_id = sc.id
  323. INNER JOIN $tbl_user u ON s.id_coach = u.user_id
  324. INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
  325. $courseCondition
  326. $extraJoin
  327. $where $where_condition) as session_table";
  328. }
  329. }
  330. $result_rows = Database::query($sql);
  331. $row = Database::fetch_array($result_rows);
  332. $num = $row['total_rows'];
  333. return $num;
  334. }
  335. /**
  336. * Gets the admin session list callback of the admin/session_list.php page
  337. * @param array $options order and limit keys
  338. * @return array
  339. */
  340. public static function get_sessions_admin($options)
  341. {
  342. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  343. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  344. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  345. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  346. $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  347. $where = ' WHERE 1=1 ';
  348. $user_id = api_get_user_id();
  349. $extraJoin = null;
  350. if (api_is_session_admin() &&
  351. api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
  352. ) {
  353. $where .= " AND (
  354. s.session_admin_id = $user_id OR
  355. sru.id_user = '$user_id' AND
  356. sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "'
  357. )
  358. ";
  359. $extraJoin = " INNER JOIN $tbl_session_rel_user sru
  360. ON sru.id_session = s.id ";
  361. }
  362. if (api_is_allowed_to_edit() && !api_is_platform_admin()) {
  363. $where.=" AND s.id_coach = $user_id ";
  364. }
  365. $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
  366. if (api_is_western_name_order()) {
  367. $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
  368. }
  369. $options['where'] = str_replace(
  370. array("AND session_active = '1' )", " AND ( session_active = '1' )"),
  371. array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 ")
  372. , $options['where']
  373. );
  374. $options['where'] = str_replace("( session_active = ':' )", '1=1', $options['where']);
  375. $options['where'] = str_replace(
  376. array("AND session_active = '0' )", " AND ( session_active = '0' )"),
  377. array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
  378. $options['where']
  379. );
  380. $today = api_get_utc_datetime();
  381. $today = api_strtotime($today, 'UTC');
  382. $today = date('Y-m-d', $today);
  383. $courseCondition = null;
  384. if (strpos($options['where'], 'c.id')) {
  385. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  386. $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  387. $courseCondition = " INNER JOIN $table course_rel_session ON (s.id = course_rel_session.id_session)
  388. INNER JOIN $tableCourse c ON (course_rel_session.course_code = c.code)
  389. ";
  390. }
  391. $select = "SELECT DISTINCT * FROM (SELECT
  392. IF (
  393. (s.date_start <= '$today' AND '$today' <= s.date_end) OR
  394. (s.nb_days_access_before_beginning > 0 AND DATEDIFF(s.date_start,'" . $today . "' " . ") <= s.nb_days_access_before_beginning) OR
  395. (s.nb_days_access_after_end > 0 AND DATEDIFF('" . $today . "',s.date_end) <= s.nb_days_access_after_end) OR
  396. (s.date_start = '0000-00-00' AND s.date_end = '0000-00-00' ) OR
  397. (s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
  398. ('$today' <= s.date_end AND '0000-00-00' = s.date_start)
  399. , 1, 0)
  400. as session_active,
  401. s.name,
  402. nbr_courses,
  403. s.nbr_users,
  404. s.date_start,
  405. s.date_end,
  406. $coach_name,
  407. sc.name as category_name,
  408. s.visibility,
  409. u.user_id,
  410. s.id";
  411. $limit = null;
  412. if (!empty($options['limit'])) {
  413. $limit = " LIMIT " . $options['limit'];
  414. }
  415. if (!empty($options['where'])) {
  416. $where .= ' '.$options['where'];
  417. }
  418. $order = null;
  419. if (!empty($options['order'])) {
  420. $order = " ORDER BY " . $options['order'];
  421. }
  422. $query = "$select FROM $tbl_session s
  423. LEFT JOIN $tbl_session_category sc ON s.session_category_id = sc.id
  424. LEFT JOIN $tbl_user u ON s.id_coach = u.user_id
  425. $courseCondition
  426. $extraJoin
  427. $where $order $limit";
  428. if (api_is_multiple_url_enabled()) {
  429. $access_url_id = api_get_current_access_url_id();
  430. if ($access_url_id != -1) {
  431. $query = " $select
  432. FROM $tbl_session s
  433. LEFT JOIN $tbl_session_category sc ON s.session_category_id = sc.id
  434. LEFT JOIN $tbl_user u ON s.id_coach = u.user_id
  435. INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id AND ar.access_url_id = $access_url_id
  436. $courseCondition
  437. $extraJoin
  438. $where $order $limit";
  439. }
  440. }
  441. $query .= ") AS session_table";
  442. $result = Database::query($query);
  443. $formatted_sessions = array();
  444. if (Database::num_rows($result)) {
  445. $sessions = Database::store_result($result);
  446. foreach ($sessions as $session) {
  447. $session['name'] = Display::url($session['name'], "resume_session.php?id_session=" . $session['id']);
  448. $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=" . $session['user_id']);
  449. if ($session['date_start'] == '0000-00-00' && $session['date_end'] == '0000-00-00') {
  450. // $session['session_active'] = 1;
  451. }
  452. if ($session['session_active'] == 1) {
  453. $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
  454. } else {
  455. $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
  456. }
  457. if ($session['date_start'] == '0000-00-00') {
  458. $session['date_start'] = '';
  459. }
  460. if ($session['date_end'] == '0000-00-00') {
  461. $session['date_end'] = '';
  462. }
  463. switch ($session['visibility']) {
  464. case SESSION_VISIBLE_READ_ONLY: //1
  465. $session['visibility'] = get_lang('SessionReadOnly');
  466. break;
  467. case SESSION_VISIBLE: //2
  468. $session['visibility'] = get_lang('SessionAccessible');
  469. break;
  470. case SESSION_INVISIBLE: //3
  471. $session['visibility'] = api_ucfirst(get_lang('SessionNotAccessible'));
  472. break;
  473. }
  474. $formatted_sessions[] = $session;
  475. }
  476. }
  477. return $formatted_sessions;
  478. }
  479. /**
  480. * Get total of records for progress of learning paths in the given session
  481. * @param int session id
  482. * @return int
  483. */
  484. public static function get_count_session_lp_progress($sessionId = 0)
  485. {
  486. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  487. $tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
  488. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  489. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  490. $sessionId = intval($sessionId);
  491. $sql = "SELECT count(*) as total_rows
  492. FROM $tbl_lp_view v
  493. INNER JOIN $tbl_lp l ON l.id = v.lp_id
  494. INNER JOIN $tbl_user u ON u.user_id = v.user_id
  495. INNER JOIN $tbl_course c
  496. WHERE v.session_id = " . $sessionId;
  497. $result_rows = Database::query($sql);
  498. $row = Database::fetch_array($result_rows);
  499. $num = $row['total_rows'];
  500. return $num;
  501. }
  502. /**
  503. * Gets the progress of learning paths in the given session
  504. * @param int session id
  505. * @param array options order and limit keys
  506. * @return array table with user name, lp name, progress
  507. */
  508. public static function get_session_lp_progress($sessionId = 0, $courseId = 0, $date_from, $date_to, $options)
  509. {
  510. //escaping vars
  511. $sessionId = $sessionId == 'T' ? 'T' : intval($sessionId);
  512. $courseId = intval($courseId);
  513. $date_from = Database :: escape_string($date_from);
  514. $date_to = Database :: escape_string($date_to);
  515. //tables
  516. $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  517. $user = Database::get_main_table(TABLE_MAIN_USER);
  518. $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
  519. $course = api_get_course_info_by_id($courseId);
  520. //getting all the students of the course
  521. //we are not using this because it only returns user ids
  522. /* if (empty($sessionId)
  523. {
  524. // Registered students in a course outside session.
  525. $users = CourseManager :: get_student_list_from_course_code($course_code);
  526. } else {
  527. // Registered students in session.
  528. $users = CourseManager :: get_student_list_from_course_code($course_code, true, $sessionId);
  529. } */
  530. $sessionCond = 'and id_session = %s';
  531. if ($sessionId == 'T') {
  532. $sessionCond = "";
  533. }
  534. $where = " WHERE course_code = '%s'
  535. AND s.status <> 2 $sessionCond";
  536. $limit = null;
  537. if (!empty($options['limit'])) {
  538. $limit = " LIMIT " . $options['limit'];
  539. }
  540. if (!empty($options['where'])) {
  541. $where .= ' '.$options['where'];
  542. }
  543. $order = null;
  544. if (!empty($options['order'])) {
  545. $order = " ORDER BY " . $options['order'];
  546. }
  547. $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.course_code
  548. FROM $session_course_user s
  549. INNER JOIN $user u ON u.user_id = s.id_user
  550. $where $order $limit";
  551. $sql_query = sprintf($sql, Database::escape_string($course['code']), $sessionId);
  552. $rs = Database::query($sql_query);
  553. while ($user = Database::fetch_array($rs)) {
  554. $users[$user['user_id']] = $user;
  555. }
  556. //Get lessons
  557. require_once api_get_path(SYS_CODE_PATH) . 'newscorm/learnpathList.class.php';
  558. $lessons = LearnpathList::get_course_lessons($course['code'], $sessionId);
  559. $table = array();
  560. foreach ($users as $user) {
  561. $data = array(
  562. 'lastname' => $user[1],
  563. 'firstname' => $user[2],
  564. 'username' => $user[3],
  565. );
  566. $sessionCond = 'AND v.session_id = %d';
  567. if ($sessionId == 'T') {
  568. $sessionCond = "";
  569. }
  570. //Get lessons progress by user
  571. $sql = "SELECT v.lp_id as id, v.progress
  572. FROM $tbl_course_lp_view v
  573. WHERE v.c_id = %d
  574. AND v.user_id = %d
  575. $sessionCond";
  576. $sql_query = sprintf($sql,
  577. intval($courseId),
  578. intval($user['user_id']),
  579. $sessionId
  580. );
  581. $result = Database::query($sql_query);
  582. $user_lessons = array();
  583. while ($row = Database::fetch_array($result)) {
  584. $user_lessons[$row['id']] = $row;
  585. }
  586. //Match course lessons with user progress
  587. $progress = 0;
  588. $count = 0;
  589. foreach ($lessons as $lesson) {
  590. $data[$lesson['id']] = (!empty($user_lessons[$lesson['id']]['progress'])) ? $user_lessons[$lesson['id']]['progress'] : 0;
  591. $progress += $data[$lesson['id']];
  592. $data[$lesson['id']] = $data[$lesson['id']] . '%';
  593. $count++;
  594. }
  595. if ($count == 0) {
  596. $data['total'] = 0;
  597. } else {
  598. $data['total'] = round($progress / $count, 2) . '%';
  599. }
  600. $table[] = $data;
  601. }
  602. return $table;
  603. }
  604. /**
  605. * Gets the survey answers
  606. * @param int session id
  607. * @param int course id
  608. * @param int survey id
  609. * @param array options order and limit keys
  610. * @todo fix the query
  611. * @return array table with user name, lp name, progress
  612. */
  613. public static function get_survey_overview($sessionId = 0, $courseId = 0, $surveyId = 0, $date_from, $date_to, $options)
  614. {
  615. //escaping vars
  616. $sessionId = intval($sessionId);
  617. $courseId = intval($courseId);
  618. $surveyId = intval($surveyId);
  619. $date_from = Database::escape_string($date_from);
  620. $date_to = Database::escape_string($date_to);
  621. //tables
  622. $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  623. $user = Database::get_main_table(TABLE_MAIN_USER);
  624. $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
  625. $c_survey = Database::get_course_table(TABLE_SURVEY);
  626. $c_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  627. $c_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  628. $c_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  629. $course = api_get_course_info_by_id($courseId);
  630. $where = " WHERE course_code = '%s' AND s.status <> 2 AND id_session = %s";
  631. $limit = null;
  632. if (!empty($options['limit'])) {
  633. $limit = " LIMIT " . $options['limit'];
  634. }
  635. if (!empty($options['where'])) {
  636. $where .= ' '.$options['where'];
  637. }
  638. $order = null;
  639. if (!empty($options['order'])) {
  640. $order = " ORDER BY " . $options['order'];
  641. }
  642. /* $where_survey = '';
  643. if (!empty($date_to) && !empty($date_from)) {
  644. $where_survey = sprintf(" AND s.avail_from >= '%s'
  645. AND s.avail_till <= '%s'", $date_from, $date_to);
  646. } */
  647. $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.course_code
  648. FROM $session_course_user s
  649. INNER JOIN $user u ON u.user_id = s.id_user
  650. $where $order $limit";
  651. $sql_query = sprintf($sql, Database::escape_string($course['code']), $sessionId);
  652. $rs = Database::query($sql_query);
  653. while ($user = Database::fetch_array($rs)) {
  654. $users[$user['user_id']] = $user;
  655. }
  656. //Get survey questions
  657. $questions = survey_manager::get_questions($surveyId, $courseId);
  658. //Survey is anonymous?
  659. $result = Database::query(sprintf("SELECT anonymous FROM $c_survey WHERE survey_id = %d", $surveyId));
  660. $row = Database::fetch_array($result);
  661. $anonymous = ($row['anonymous'] == 1) ? true : false;
  662. $table = array();
  663. foreach ($users as $user) {
  664. $data = array(
  665. 'lastname' => ($anonymous ? '***' : $user[1]),
  666. 'firstname' => ($anonymous ? '***' : $user[2]),
  667. 'username' => ($anonymous ? '***' : $user[3]),
  668. );
  669. //Get questions by user
  670. $sql = "SELECT sa.question_id, sa.option_id, sqo.option_text, sq.type
  671. FROM $c_survey_answer sa
  672. INNER JOIN $c_survey_question sq
  673. ON sq.question_id = sa.question_id
  674. LEFT JOIN $c_survey_question_option sqo
  675. ON
  676. sqo.c_id = sa.c_id AND
  677. sqo.question_id = sq.question_id AND
  678. sqo.question_option_id = sa.option_id AND
  679. sqo.survey_id = sq.survey_id
  680. WHERE
  681. sa.survey_id = %d AND
  682. sa.c_id = %d AND
  683. sa.user = %d
  684. "; //. $where_survey;
  685. $sql_query = sprintf($sql, $surveyId, $courseId, $user['user_id']);
  686. $result = Database::query($sql_query);
  687. $user_questions = array();
  688. while ($row = Database::fetch_array($result)) {
  689. $user_questions[$row['question_id']] = $row;
  690. }
  691. //Match course lessons with user progress
  692. foreach ($questions as $question_id => $question) {
  693. $option_text = 'option_text';
  694. if ($user_questions[$question_id]['type'] == 'open') {
  695. $option_text = 'option_id';
  696. }
  697. $data[$question_id] = $user_questions[$question_id][$option_text];
  698. }
  699. $table[] = $data;
  700. }
  701. return $table;
  702. }
  703. /**
  704. * Gets the progress of the given session
  705. * @param int session id
  706. * @param array options order and limit keys
  707. * @return array table with user name, lp name, progress
  708. */
  709. public static function get_session_progress($sessionId, $courseId, $date_from, $date_to, $options)
  710. {
  711. $sessionId = intval($sessionId);
  712. $getAllSessions = false;
  713. if (empty($sessionId)) {
  714. $sessionId = 0;
  715. $getAllSessions = true;
  716. }
  717. //tables
  718. $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  719. $user = Database::get_main_table(TABLE_MAIN_USER);
  720. $course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  721. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  722. $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  723. $forum = Database::get_course_table(TABLE_FORUM);
  724. $forum_post = Database::get_course_table(TABLE_FORUM_POST);
  725. $tbl_course_lp = Database::get_course_table(TABLE_LP_MAIN);
  726. $wiki = Database::get_course_table(TABLE_WIKI);
  727. $table_stats_default = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
  728. $table_stats_access = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  729. $course = api_get_course_info_by_id($courseId);
  730. //getting all the students of the course
  731. //we are not using this because it only returns user ids
  732. /* if (empty($sessionId)
  733. {
  734. // Registered students in a course outside session.
  735. $users = CourseManager :: get_student_list_from_course_code($course_code);
  736. } else {
  737. // Registered students in session.
  738. $users = CourseManager :: get_student_list_from_course_code($course_code, true, $sessionId);
  739. } */
  740. $where = " WHERE course_code = '%s' AND s.status <> 2 ";
  741. $limit = null;
  742. if (!empty($options['limit'])) {
  743. $limit = " LIMIT " . $options['limit'];
  744. }
  745. if (!empty($options['where'])) {
  746. $where .= ' '.$options['where'];
  747. }
  748. $order = null;
  749. if (!empty($options['order'])) {
  750. $order = " ORDER BY " . $options['order'];
  751. }
  752. //TODO, fix create report without session
  753. $queryVariables = array($course['code']);
  754. if (!empty($sessionId)) {
  755. $where .= ' AND id_session = %s';
  756. $queryVariables[] = $sessionId;
  757. $sql = "SELECT
  758. u.user_id, u.lastname, u.firstname, u.username,
  759. u.email, s.course_code, s.id_session
  760. FROM $session_course_user s
  761. INNER JOIN $user u
  762. ON u.user_id = s.id_user
  763. $where $order $limit";
  764. } else {
  765. $sql = "SELECT
  766. u.user_id, u.lastname, u.firstname, u.username,
  767. u.email, s.course_code, s.id_session
  768. FROM $session_course_user s
  769. INNER JOIN $user u ON u.user_id = s.id_user
  770. $where $order $limit";
  771. }
  772. $sql_query = vsprintf($sql, $queryVariables);
  773. $rs = Database::query($sql_query);
  774. while ($user = Database::fetch_array($rs)) {
  775. $users[$user['user_id']] = $user;
  776. }
  777. /**
  778. * Lessons
  779. */
  780. $sql = "SELECT * FROM $tbl_course_lp WHERE c_id = %s "; //AND session_id = %s
  781. $sql_query = sprintf($sql, $course['real_id']);
  782. $result = Database::query($sql_query);
  783. $arrLesson = array(array());
  784. while ($row = Database::fetch_array($result)) {
  785. // if (api_get_item_visibility(api_get_course_info($course['code']), 'learnpath', $row['id'], $row['session_id']))
  786. // {
  787. if (empty($arrLesson[$row['session_id']]['lessons_total'])) {
  788. $arrLesson[$row['session_id']]['lessons_total'] = 1;
  789. } else {
  790. $arrLesson[$row['session_id']]['lessons_total'] ++;
  791. }
  792. // }
  793. }
  794. /**
  795. * Exercises
  796. */
  797. require_once api_get_path(SYS_CODE_PATH) . 'exercice/exercise.lib.php';
  798. $exercises = get_all_exercises($course, $sessionId, false, '', $getAllSessions);
  799. $exercises_total = count($exercises);
  800. /**
  801. * Assignments
  802. */
  803. //total
  804. if ($getAllSessions) {
  805. $sql = "SELECT count(w.id) as count
  806. FROM $workTable w
  807. LEFT JOIN $workTableAssignment a
  808. ON (a.publication_id = w.id AND a.c_id = w.c_id)
  809. WHERE w.c_id = %s
  810. AND parent_id = 0
  811. AND active IN (1, 0)";
  812. } else {
  813. $sql = "SELECT count(w.id) as count
  814. FROM $workTable w
  815. LEFT JOIN $workTableAssignment a
  816. ON (a.publication_id = w.id AND a.c_id = w.c_id)
  817. WHERE w.c_id = %s
  818. AND parent_id = 0
  819. AND active IN (1, 0)
  820. AND session_id = %s";
  821. }
  822. $sql_query = sprintf($sql, $course['real_id'], $sessionId);
  823. $result = Database::query($sql_query);
  824. $row = Database::fetch_array($result);
  825. $assignments_total = $row['count'];
  826. /**
  827. * Wiki
  828. */
  829. if ($getAllSessions) {
  830. $sql = "SELECT count(distinct page_id) as count FROM $wiki
  831. WHERE c_id = %s";
  832. } else {
  833. $sql = "SELECT count(distinct page_id) as count FROM $wiki
  834. WHERE c_id = %s and session_id = %s";
  835. }
  836. $sql_query = sprintf($sql, $course['real_id'], $sessionId);
  837. $result = Database::query($sql_query);
  838. $row = Database::fetch_array($result);
  839. $wiki_total = $row['count'];
  840. /**
  841. * Surveys
  842. */
  843. $survey_user_list = array();
  844. $survey_list = survey_manager::get_surveys($course['code'], $sessionId);
  845. $surveys_total = count($survey_list);
  846. foreach ($survey_list as $survey) {
  847. $user_list = survey_manager::get_people_who_filled_survey(
  848. $survey['survey_id'],
  849. false,
  850. $course['real_id']
  851. );
  852. foreach ($user_list as $user_id) {
  853. isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id] ++ : $survey_user_list[$user_id] = 1;
  854. }
  855. }
  856. /**
  857. * Forums
  858. */
  859. $forums_total = CourseManager::getCountForum(
  860. $course['real_id'],
  861. $sessionId,
  862. $getAllSessions
  863. );
  864. //process table info
  865. foreach ($users as $user) {
  866. //Course description
  867. $sql = "SELECT count(*) as count
  868. FROM $table_stats_access
  869. WHERE access_tool = 'course_description'
  870. AND access_cours_code = '%s'
  871. AND access_session_id = %s
  872. AND access_user_id = %s ";
  873. $sql_query = sprintf($sql, $course['code'], $user['id_session'], $user['user_id']);
  874. $result = Database::query($sql_query);
  875. $row = Database::fetch_array($result);
  876. $course_description_progress = ($row['count'] > 0) ? 100 : 0;
  877. if (!empty($arrLesson[$user['id_session']]['lessons_total'])) {
  878. $lessons_total = $arrLesson[$user['id_session']]['lessons_total'];
  879. } else {
  880. $lessons_total = !empty($arrLesson[0]['lessons_total']) ? $arrLesson[0]['lessons_total'] : 0;
  881. }
  882. //Lessons
  883. //TODO: Lessons done and left is calculated by progress per item in lesson, maybe we should calculate it only per completed lesson?
  884. $lessons_progress = Tracking::get_avg_student_progress($user['user_id'], $course['code'], array(), $user['id_session']);
  885. $lessons_done = ($lessons_progress * $lessons_total) / 100;
  886. $lessons_left = $lessons_total - $lessons_done;
  887. //Exercises
  888. $exercises_progress = str_replace('%', '', Tracking::get_exercise_student_progress($exercises, $user['user_id'], $course['code'], $user['id_session']));
  889. $exercises_done = round(($exercises_progress * $exercises_total) / 100);
  890. $exercises_left = $exercises_total - $exercises_done;
  891. //Assignments
  892. $assignments_done = Tracking::count_student_assignments($user['user_id'], $course['code'], $user['id_session']);
  893. $assignments_left = $assignments_total - $assignments_done;
  894. if (!empty($assignments_total)) {
  895. $assignments_progress = round((( $assignments_done * 100 ) / $assignments_total), 2);
  896. } else {
  897. $assignments_progress = 0;
  898. }
  899. //Wiki
  900. //total revisions per user
  901. $sql = "SELECT count(*) as count
  902. FROM $wiki
  903. where c_id = %s and session_id = %s and user_id = %s";
  904. $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
  905. $result = Database::query($sql_query);
  906. $row = Database::fetch_array($result);
  907. $wiki_revisions = $row['count'];
  908. //count visited wiki pages
  909. $sql = "SELECT count(distinct default_value) as count
  910. FROM $table_stats_default
  911. WHERE default_user_id = %s
  912. AND default_cours_code = '%s'
  913. AND default_event_type = 'wiki_page_view'
  914. AND default_value_type = 'wiki_page_id'
  915. AND c_id = %s";
  916. $sql_query = sprintf($sql, $user['user_id'], $course['code'], $course['real_id']);
  917. $result = Database::query($sql_query);
  918. $row = Database::fetch_array($result);
  919. $wiki_read = $row['count'];
  920. $wiki_unread = $wiki_total - $wiki_read;
  921. if (!empty($wiki_total)) {
  922. $wiki_progress = round((( $wiki_read * 100 ) / $wiki_total), 2);
  923. } else {
  924. $wiki_progress = 0;
  925. }
  926. //Surveys
  927. $surveys_done = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0);
  928. $surveys_left = $surveys_total - $surveys_done;
  929. if (!empty($surveys_total)) {
  930. $surveys_progress = round((( $surveys_done * 100 ) / $surveys_total), 2);
  931. } else {
  932. $surveys_progress = 0;
  933. }
  934. //Forums
  935. $forums_done = CourseManager::getCountForumPerUser(
  936. $user['user_id'],
  937. $course['real_id'],
  938. $user['id_session']
  939. );
  940. $forums_left = $forums_total - $forums_done;
  941. if (!empty($forums_total)) {
  942. $forums_progress = round((( $forums_done * 100 ) / $forums_total), 2);
  943. } else {
  944. $forums_progress = 0;
  945. }
  946. //Overall Total
  947. $overall_total = ($course_description_progress + $exercises_progress + $forums_progress + $assignments_progress + $wiki_progress + $surveys_progress) / 6;
  948. $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>';
  949. $linkForum = '<a href="' . api_get_path(WEB_CODE_PATH) . 'forum/index.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
  950. $linkWork = '<a href="' . api_get_path(WEB_CODE_PATH) . 'work/work.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
  951. $linkWiki = '<a href="' . api_get_path(WEB_CODE_PATH) . 'wiki/index.php?cidReq=' . $course['code'] . '&session_id=' . $user['id_session'] . '&action=statistics"> %s </a>';
  952. $linkSurvey = '<a href="' . api_get_path(WEB_CODE_PATH) . 'survey/survey_list.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
  953. $table[] = array(
  954. 'lastname' => $user[1],
  955. 'firstname' => $user[2],
  956. 'username' => $user[3],
  957. #'profile' => '',
  958. 'total' => round($overall_total, 2) . '%',
  959. 'courses' => sprintf($link, $course_description_progress . '%'),
  960. 'lessons' => sprintf($link, $lessons_progress . '%'),
  961. 'exercises' => sprintf($link, $exercises_progress . '%'),
  962. 'forums' => sprintf($link, $forums_progress . '%'),
  963. 'homeworks' => sprintf($link, $assignments_progress . '%'),
  964. 'wikis' => sprintf($link, $wiki_progress . '%'),
  965. 'surveys' => sprintf($link, $surveys_progress . '%'),
  966. //course description
  967. 'course_description_progress' => $course_description_progress . '%',
  968. //lessons
  969. 'lessons_total' => sprintf($link, $lessons_total),
  970. 'lessons_done' => sprintf($link, $lessons_done),
  971. 'lessons_left' => sprintf($link, $lessons_left),
  972. 'lessons_progress' => sprintf($link, $lessons_progress . '%'),
  973. //exercises
  974. 'exercises_total' => sprintf($link, $exercises_total),
  975. 'exercises_done' => sprintf($link, $exercises_done),
  976. 'exercises_left' => sprintf($link, $exercises_left),
  977. 'exercises_progress' => sprintf($link, $exercises_progress . '%'),
  978. //forums
  979. 'forums_total' => sprintf($linkForum, $forums_total),
  980. 'forums_done' => sprintf($linkForum, $forums_done),
  981. 'forums_left' => sprintf($linkForum, $forums_left),
  982. 'forums_progress' => sprintf($linkForum, $forums_progress . '%'),
  983. //assignments
  984. 'assignments_total' => sprintf($linkWork, $assignments_total),
  985. 'assignments_done' => sprintf($linkWork, $assignments_done),
  986. 'assignments_left' => sprintf($linkWork, $assignments_left),
  987. 'assignments_progress' => sprintf($linkWork, $assignments_progress . '%'),
  988. //wiki
  989. 'wiki_total' => sprintf($linkWiki, $wiki_total),
  990. 'wiki_revisions' => sprintf($linkWiki, $wiki_revisions),
  991. 'wiki_read' => sprintf($linkWiki, $wiki_read),
  992. 'wiki_unread' => sprintf($linkWiki, $wiki_unread),
  993. 'wiki_progress' => sprintf($linkWiki, $wiki_progress . '%'),
  994. //survey
  995. 'surveys_total' => sprintf($linkSurvey, $surveys_total),
  996. 'surveys_done' => sprintf($linkSurvey, $surveys_done),
  997. 'surveys_left' => sprintf($linkSurvey, $surveys_left),
  998. 'surveys_progress' => sprintf($linkSurvey, $surveys_progress . '%'),
  999. );
  1000. }
  1001. return $table;
  1002. }
  1003. public static function get_number_of_tracking_access_overview()
  1004. {
  1005. // database table definition
  1006. $track_e_course_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1007. return Database::count_rows($track_e_course_access);
  1008. }
  1009. /**
  1010. * Get the ip, total of clicks, login date and time logged in for all user, in one session
  1011. * @todo track_e_course_access table should have ip so we dont have to look for it in track_e_login
  1012. *
  1013. * @author César Perales <cesar.perales@beeznest.com>, Beeznest Team
  1014. * @version Chamilo 1.9.6
  1015. */
  1016. public static function get_user_data_access_tracking_overview(
  1017. $sessionId,
  1018. $courseId,
  1019. $studentId = 0,
  1020. $profile = '',
  1021. $date_from = '',
  1022. $date_to = '',
  1023. $options
  1024. ) {
  1025. global $_configuration;
  1026. //escaping variables
  1027. $sessionId = intval($sessionId);
  1028. $courseId = intval($courseId);
  1029. $studentId = intval($studentId);
  1030. $profile = intval($profile);
  1031. $date_from = Database::escape_string($date_from);
  1032. $date_to = Database::escape_string($date_to);
  1033. // database table definition
  1034. $user = Database :: get_main_table(TABLE_MAIN_USER);
  1035. $course = Database :: get_main_table(TABLE_MAIN_COURSE);
  1036. $track_e_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1037. $track_e_course_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1038. $sessionTable = Database :: get_main_table(TABLE_MAIN_SESSION);
  1039. global $export_csv;
  1040. if ($export_csv) {
  1041. $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
  1042. } else {
  1043. $is_western_name_order = api_is_western_name_order();
  1044. }
  1045. $where = null;
  1046. if (isset($sessionId) && !empty($sessionId)) {
  1047. $where = sprintf(" WHERE a.session_id = %d", $sessionId);
  1048. }
  1049. if (isset($courseId) && !empty($courseId)) {
  1050. $where .= sprintf(" AND c.id = %d", $courseId);
  1051. }
  1052. if (isset($studentId) && !empty($studentId)) {
  1053. $where .= sprintf(" AND u.user_id = %d", $studentId);
  1054. }
  1055. if (isset($profile) && !empty($profile)) {
  1056. $where .= sprintf(" AND u.status = %d", $profile);
  1057. }
  1058. if (!empty($date_to) && !empty($date_from)) {
  1059. $where .= sprintf(
  1060. " AND a.login_course_date >= '%s 00:00:00'
  1061. AND a.login_course_date <= '%s 23:59:59'",
  1062. $date_from,
  1063. $date_to
  1064. );
  1065. }
  1066. $limit = null;
  1067. if (!empty($options['limit'])) {
  1068. $limit = " LIMIT " . $options['limit'];
  1069. }
  1070. if (!empty($options['where'])) {
  1071. $where .= ' '.$options['where'];
  1072. }
  1073. $order = null;
  1074. if (!empty($options['order'])) {
  1075. $order = " ORDER BY " . $options['order'];
  1076. }
  1077. //TODO add course name
  1078. $sql = "SELECT
  1079. a.login_course_date ,
  1080. u.username ,
  1081. " . ($is_western_name_order ? "
  1082. u.firstname,
  1083. u.lastname,
  1084. " : "
  1085. u.lastname,
  1086. u.firstname,
  1087. ") . "
  1088. a.logout_course_date,
  1089. a.counter,
  1090. c.title,
  1091. c.code,
  1092. u.user_id,
  1093. a.session_id
  1094. FROM $track_e_course_access a
  1095. INNER JOIN $user u ON a.user_id = u.user_id
  1096. INNER JOIN $course c ON a.course_code = c.code
  1097. $where $order $limit";
  1098. $result = Database::query(sprintf($sql, $sessionId, $courseId));
  1099. $data = array();
  1100. while ($user = Database::fetch_assoc($result)) {
  1101. $data[] = $user;
  1102. }
  1103. //foreach
  1104. foreach ($data as $key => $info) {
  1105. $sql = "SELECT
  1106. name
  1107. FROM $sessionTable
  1108. WHERE
  1109. id = {$info['session_id']}";
  1110. $result = Database::query($sql);
  1111. $session = Database::fetch_assoc($result);
  1112. //We are not using this becaouse the range its to small and no other date match the condition of this function
  1113. //$clicks = Tracking::get_total_clicks($info['user_id'], $courseId, $sessionId, $info['login_course_date'], $info['logout_course_date']);
  1114. #building array to display
  1115. $return[] = array(
  1116. 'user_id' => $info['user_id'],
  1117. 'logindate' => $info['login_course_date'],
  1118. 'username' => $info['username'],
  1119. 'firstname' => $info['firstname'],
  1120. 'lastname' => $info['lastname'],
  1121. 'clicks' => $info['counter'], //+ $clicks[$info['user_id']],
  1122. 'ip' => '',
  1123. 'timeLoggedIn' => gmdate("H:i:s", strtotime($info['logout_course_date']) - strtotime($info['login_course_date'])),
  1124. 'session' => $session['name']);
  1125. }
  1126. foreach ($return as $key => $info) {
  1127. //Search for ip, we do less querys if we iterate the final array
  1128. $sql = sprintf("SELECT login_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
  1129. $result = Database::query($sql);
  1130. $ip = Database::fetch_assoc($result);
  1131. //if no ip founded, we search the closest higher ip
  1132. if (empty($ip['login_ip'])) {
  1133. $sql = sprintf("SELECT login_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
  1134. $result = Database::query($sql);
  1135. $ip = Database::fetch_assoc($result);
  1136. }
  1137. #add ip to final array
  1138. $return[$key]['ip'] = $ip['login_ip'];
  1139. }
  1140. return $return;
  1141. }
  1142. /**
  1143. * Creates a new course code based in given code
  1144. *
  1145. * @param string wanted code
  1146. * <code>
  1147. * $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3
  1148. * if the course code doest not exist in the DB the same course code will be returned
  1149. * </code>
  1150. * @return string wanted unused code
  1151. */
  1152. public static function generate_nice_next_session_name($session_name)
  1153. {
  1154. $session_name_ok = !self::session_name_exists($session_name);
  1155. if (!$session_name_ok) {
  1156. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  1157. $session_name = Database::escape_string($session_name);
  1158. $sql = "SELECT count(*) as count FROM $table
  1159. WHERE name LIKE '$session_name%'";
  1160. $result = Database::query($sql);
  1161. if (Database::num_rows($result) > 0) {
  1162. $row = Database::fetch_array($result);
  1163. $count = $row['count'] + 1;
  1164. $session_name = $session_name . '_' . $count;
  1165. $result = self::session_name_exists($session_name);
  1166. if (!$result) {
  1167. return $session_name;
  1168. }
  1169. }
  1170. return false;
  1171. }
  1172. return $session_name;
  1173. }
  1174. /**
  1175. * Edit a session
  1176. * @author Carlos Vargas from existing code
  1177. * @param integer id
  1178. * @param string name
  1179. * @param integer year_start
  1180. * @param integer month_start
  1181. * @param integer day_start
  1182. * @param integer year_end
  1183. * @param integer month_end
  1184. * @param integer day_end
  1185. * @param integer nb_days_acess_before
  1186. * @param integer nb_days_acess_after
  1187. * @param integer nolimit
  1188. * @param integer id_coach
  1189. * @param integer id_session_category
  1190. * @param int $id_visibility
  1191. * @param bool
  1192. * @param bool
  1193. * @param string $description
  1194. * @param int $showDescription
  1195. * @return $id;
  1196. * The parameter id is a primary key
  1197. * */
  1198. public static function edit_session(
  1199. $id,
  1200. $name,
  1201. $year_start,
  1202. $month_start,
  1203. $day_start,
  1204. $year_end,
  1205. $month_end,
  1206. $day_end,
  1207. $nb_days_acess_before,
  1208. $nb_days_acess_after,
  1209. $nolimit,
  1210. $id_coach,
  1211. $id_session_category,
  1212. $id_visibility,
  1213. $start_limit = true,
  1214. $end_limit = true,
  1215. $description = null,
  1216. $showDescription = null,
  1217. $duration = null,
  1218. $calendarStartDate = ''
  1219. ) {
  1220. $name = trim(stripslashes($name));
  1221. $year_start = intval($year_start);
  1222. $month_start = intval($month_start);
  1223. $day_start = intval($day_start);
  1224. $year_end = intval($year_end);
  1225. $month_end = intval($month_end);
  1226. $day_end = intval($day_end);
  1227. $id_coach = intval($id_coach);
  1228. $nb_days_acess_before = intval($nb_days_acess_before);
  1229. $nb_days_acess_after = intval($nb_days_acess_after);
  1230. $id_session_category = intval($id_session_category);
  1231. $id_visibility = intval($id_visibility);
  1232. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1233. if (empty($nolimit)) {
  1234. $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
  1235. $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
  1236. } else {
  1237. $date_start = "0000-00-00";
  1238. $date_end = "0000-00-00";
  1239. $id_visibility = 1; //force read only
  1240. }
  1241. if (!empty($no_end_limit)) {
  1242. $date_end = "0000-00-00";
  1243. }
  1244. if (empty($end_limit)) {
  1245. $date_end = "0000-00-00";
  1246. $id_visibility = 1; //force read only
  1247. }
  1248. if (empty($start_limit)) {
  1249. $date_start = "0000-00-00";
  1250. }
  1251. if (empty($name)) {
  1252. $msg = get_lang('SessionNameIsRequired');
  1253. return $msg;
  1254. } elseif (empty($id_coach)) {
  1255. $msg = get_lang('CoachIsRequired');
  1256. return $msg;
  1257. } elseif (!empty($start_limit) && empty($nolimit) && (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start))) {
  1258. $msg = get_lang('InvalidStartDate');
  1259. return $msg;
  1260. } elseif (!empty($end_limit) && empty($nolimit) && (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end))) {
  1261. $msg = get_lang('InvalidEndDate');
  1262. return $msg;
  1263. } elseif (!empty($start_limit) && !empty($end_limit) && empty($nolimit) && $date_start >= $date_end) {
  1264. $msg = get_lang('StartDateShouldBeBeforeEndDate');
  1265. return $msg;
  1266. } else {
  1267. $rs = Database::query("SELECT id FROM $tbl_session WHERE name='" . Database::escape_string($name) . "'");
  1268. $exists = false;
  1269. while ($row = Database::fetch_array($rs)) {
  1270. if ($row['id'] != $id) {
  1271. $exists = true;
  1272. }
  1273. }
  1274. if ($exists) {
  1275. $msg = get_lang('SessionNameAlreadyExists');
  1276. return $msg;
  1277. } else {
  1278. $sessionInfo = SessionManager::fetch($id);
  1279. $descriptionCondition = null;
  1280. if (array_key_exists('description', $sessionInfo)) {
  1281. $descriptionCondition = ' description = "' . Database::escape_string($description) . '" ,';
  1282. }
  1283. $showDescriptionCondition = null;
  1284. if (array_key_exists('show_description', $sessionInfo)) {
  1285. $showDescriptionCondition = ' show_description = "' . Database::escape_string($showDescription) . '" ,';
  1286. }
  1287. $durationCondition = null;
  1288. if (self::durationPerUserIsEnabled()) {
  1289. if (empty($duration)) {
  1290. $duration = null;
  1291. } else {
  1292. $date_start = '0000-00-00';
  1293. $date_end = "0000-00-00";
  1294. $duration = intval($duration);
  1295. }
  1296. $durationCondition = ' duration = "' . $duration . '" ,';
  1297. }
  1298. $calendarStartDateCondition = '';
  1299. if (array_key_exists('calendar_start_date', $sessionInfo)) {
  1300. if (empty($calendarStartDate)) {
  1301. $calendarStartDateCondition = " calendar_start_date = NULL, ";
  1302. } else {
  1303. $calendarStartDateCondition = " calendar_start_date = '".api_get_utc_datetime($calendarStartDate)."', ";
  1304. }
  1305. }
  1306. $sql = "UPDATE $tbl_session SET
  1307. name='" . Database::escape_string($name) . "',
  1308. date_start='" . $date_start . "',
  1309. date_end='" . $date_end . "',
  1310. id_coach='" . $id_coach . "',
  1311. nb_days_access_before_beginning = " . $nb_days_acess_before . ",
  1312. nb_days_access_after_end = " . $nb_days_acess_after . ",
  1313. session_category_id = " . $id_session_category . " ,
  1314. $descriptionCondition
  1315. $showDescriptionCondition
  1316. $durationCondition
  1317. $calendarStartDateCondition
  1318. visibility= " . $id_visibility . "
  1319. WHERE id='$id'";
  1320. Database::query($sql);
  1321. return $id;
  1322. }
  1323. }
  1324. }
  1325. /**
  1326. * Delete session
  1327. * @author Carlos Vargas from existing code
  1328. * @param array id_checked an array to delete sessions
  1329. * @param boolean optional, true if the function is called by a webservice, false otherwise.
  1330. * @return void Nothing, or false on error
  1331. * */
  1332. public static function delete_session($id_checked, $from_ws = false)
  1333. {
  1334. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1335. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1336. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1337. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1338. $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1339. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  1340. $userId = api_get_user_id();
  1341. if (is_array($id_checked)) {
  1342. $id_checked = Database::escape_string(implode(',', $id_checked));
  1343. } else {
  1344. $id_checked = intval($id_checked);
  1345. }
  1346. if (!api_is_platform_admin() && !$from_ws) {
  1347. $sql = 'SELECT session_admin_id FROM ' . Database :: get_main_table(TABLE_MAIN_SESSION) . ' WHERE id IN (' . $id_checked.')';
  1348. $rs = Database::query($sql);
  1349. if (Database::result($rs, 0, 0) != $userId) {
  1350. api_not_allowed(true);
  1351. }
  1352. }
  1353. Database::query("DELETE FROM $tbl_session WHERE id IN($id_checked)");
  1354. Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session IN($id_checked)");
  1355. Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session IN($id_checked)");
  1356. Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session IN($id_checked)");
  1357. Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
  1358. $sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked'";
  1359. Database::query($sql_delete_sfv);
  1360. // Add event to system log
  1361. event_system(
  1362. LOG_SESSION_DELETE,
  1363. LOG_SESSION_ID,
  1364. $id_checked,
  1365. api_get_utc_datetime(),
  1366. $userId
  1367. );
  1368. }
  1369. /**
  1370. * @param int $id_promotion
  1371. * @return bool
  1372. */
  1373. public static function clear_session_ref_promotion($id_promotion)
  1374. {
  1375. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1376. $id_promotion = intval($id_promotion);
  1377. $sql = "UPDATE $tbl_session SET promotion_id=0
  1378. WHERE promotion_id='$id_promotion'";
  1379. if (Database::query($sql)) {
  1380. return true;
  1381. } else {
  1382. return false;
  1383. }
  1384. }
  1385. /**
  1386. * Subscribes students to the given session and optionally (default) unsubscribes previous users
  1387. *
  1388. * @author Carlos Vargas from existing code
  1389. * @author Julio Montoya. Cleaning code.
  1390. * @param int $id_session
  1391. * @param array $user_list
  1392. * @param int $session_visibility
  1393. * @param bool $empty_users
  1394. * @param bool $send_email
  1395. * @return bool
  1396. */
  1397. public static function suscribe_users_to_session(
  1398. $id_session,
  1399. $user_list,
  1400. $session_visibility = SESSION_VISIBLE_READ_ONLY,
  1401. $empty_users = true,
  1402. $send_email = false
  1403. ) {
  1404. if ($id_session != strval(intval($id_session))) {
  1405. return false;
  1406. }
  1407. foreach ($user_list as $intUser) {
  1408. if ($intUser != strval(intval($intUser))) {
  1409. return false;
  1410. }
  1411. }
  1412. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1413. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1414. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1415. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1416. $session_info = api_get_session_info($id_session);
  1417. $session_name = $session_info['name'];
  1418. // from function parameter
  1419. if (empty($session_visibility)) {
  1420. $session_visibility = $session_info['visibility']; //loaded from DB
  1421. //default status loaded if empty
  1422. if (empty($session_visibility))
  1423. $session_visibility = SESSION_VISIBLE_READ_ONLY; // by default readonly 1
  1424. } else {
  1425. if (!in_array($session_visibility, array(SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_INVISIBLE))) {
  1426. $session_visibility = SESSION_VISIBLE_READ_ONLY;
  1427. }
  1428. }
  1429. $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user
  1430. WHERE id_session = '$id_session' AND status = 0";
  1431. $result = Database::query($sql);
  1432. $existingUsers = array();
  1433. while ($row = Database::fetch_array($result)) {
  1434. $existingUsers[] = $row['id_user'];
  1435. }
  1436. $sql = "SELECT course_code FROM $tbl_session_rel_course
  1437. WHERE id_session = '$id_session'";
  1438. $result = Database::query($sql);
  1439. $course_list = array();
  1440. while ($row = Database::fetch_array($result)) {
  1441. $course_list[] = $row['course_code'];
  1442. }
  1443. if ($send_email) {
  1444. // Sending emails only
  1445. if (is_array($user_list) && count($user_list) > 0) {
  1446. foreach ($user_list as $user_id) {
  1447. if (!in_array($user_id, $existingUsers)) {
  1448. $subject = '[' . get_setting('siteName') . '] ' . get_lang('YourReg') . ' ' . get_setting('siteName');
  1449. $user_info = api_get_user_info($user_id);
  1450. $content = get_lang('Dear') . " " . stripslashes($user_info['complete_name']) . ",\n\n" . sprintf(get_lang('YouAreRegisterToSessionX'), $session_name) . " \n\n" . get_lang('Address') . " " . get_setting('siteName') . " " . get_lang('Is') . " : " . api_get_path(WEB_PATH) . "\n\n" . get_lang('Problem') . "\n\n" . get_lang('SignatureFormula') . ",\n\n" . get_setting('administratorName') . " " . get_setting('administratorSurname') . "\n" . get_lang('Manager') . " " . get_setting('siteName') . "\nT. " . get_setting('administratorTelephone') . "\n" . get_lang('Email') . " : " . get_setting('emailAdministrator');
  1451. MessageManager::send_message(
  1452. $user_id,
  1453. $subject,
  1454. $content,
  1455. array(),
  1456. array(),
  1457. null,
  1458. null,
  1459. null,
  1460. null,
  1461. null
  1462. );
  1463. }
  1464. }
  1465. }
  1466. }
  1467. foreach ($course_list as $enreg_course) {
  1468. // for each course in the session
  1469. $nbr_users = 0;
  1470. $enreg_course = Database::escape_string($enreg_course);
  1471. $sql = "SELECT DISTINCT id_user FROM $tbl_session_rel_course_rel_user
  1472. WHERE id_session = '$id_session' AND course_code='$enreg_course' AND status = 0";
  1473. $result = Database::query($sql);
  1474. $existingUsers = array();
  1475. while ($row = Database::fetch_array($result)) {
  1476. $existingUsers[] = $row['id_user'];
  1477. }
  1478. // Delete existing users
  1479. if ($empty_users) {
  1480. foreach ($existingUsers as $existing_user) {
  1481. if (!in_array($existing_user, $user_list)) {
  1482. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  1483. WHERE id_session='$id_session' AND course_code='$enreg_course' AND id_user='$existing_user' AND status = 0";
  1484. Database::query($sql);
  1485. event_system(
  1486. LOG_SESSION_DELETE_USER_COURSE,
  1487. LOG_USER_ID,
  1488. $existing_user,
  1489. api_get_utc_datetime(),
  1490. api_get_user_id(),
  1491. $enreg_course,
  1492. $id_session
  1493. );
  1494. if (Database::affected_rows()) {
  1495. $nbr_users--;
  1496. }
  1497. }
  1498. }
  1499. }
  1500. // Replace with this new function
  1501. // insert new users into session_rel_course_rel_user and ignore if they already exist
  1502. foreach ($user_list as $enreg_user) {
  1503. if (!in_array($enreg_user, $existingUsers)) {
  1504. $enreg_user = Database::escape_string($enreg_user);
  1505. $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session, course_code, id_user, visibility, status)
  1506. VALUES('$id_session','$enreg_course','$enreg_user','$session_visibility', '0')";
  1507. Database::query($sql);
  1508. event_system(
  1509. LOG_SESSION_ADD_USER_COURSE,
  1510. LOG_USER_ID,
  1511. $enreg_user,
  1512. api_get_utc_datetime(),
  1513. api_get_user_id(),
  1514. $enreg_course,
  1515. $id_session
  1516. );
  1517. if (Database::affected_rows()) {
  1518. $nbr_users++;
  1519. }
  1520. }
  1521. }
  1522. // Count users in this session-course relation
  1523. $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user
  1524. WHERE id_session='$id_session' AND course_code='$enreg_course' AND status<>2";
  1525. $rs = Database::query($sql);
  1526. list($nbr_users) = Database::fetch_array($rs);
  1527. // update the session-course relation to add the users total
  1528. $sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users
  1529. WHERE id_session='$id_session' AND course_code = '$enreg_course'";
  1530. Database::query($sql);
  1531. }
  1532. // Delete users from the session
  1533. if ($empty_users === true) {
  1534. $sql = "DELETE FROM $tbl_session_rel_user
  1535. WHERE id_session = $id_session AND relation_type<>" . SESSION_RELATION_TYPE_RRHH . "";
  1536. Database::query($sql);
  1537. }
  1538. // Insert missing users into session
  1539. $nbr_users = 0;
  1540. foreach ($user_list as $enreg_user) {
  1541. $enreg_user = Database::escape_string($enreg_user);
  1542. $nbr_users++;
  1543. $sql = "INSERT IGNORE INTO $tbl_session_rel_user (id_session, id_user)
  1544. VALUES ('$id_session', '$enreg_user')";
  1545. Database::query($sql);
  1546. }
  1547. // update number of users in the session
  1548. $nbr_users = count($user_list);
  1549. if ($empty_users) {
  1550. // update number of users in the session
  1551. $sql = "UPDATE $tbl_session SET nbr_users= $nbr_users
  1552. WHERE id='$id_session' ";
  1553. Database::query($sql);
  1554. } else {
  1555. $sql = "UPDATE $tbl_session SET nbr_users= nbr_users + $nbr_users
  1556. WHERE id='$id_session'";
  1557. Database::query($sql);
  1558. }
  1559. }
  1560. /**
  1561. * Returns user list of the current users subscribed in the course-session
  1562. * @param int $sessionId
  1563. * @param array $courseInfo
  1564. * @param int $status
  1565. *
  1566. * @return array
  1567. */
  1568. public static function getUsersByCourseSession(
  1569. $sessionId,
  1570. $courseInfo,
  1571. $status = null
  1572. ) {
  1573. $sessionId = intval($sessionId);
  1574. $courseCode = $courseInfo['code'];
  1575. if (empty($sessionId) || empty($courseCode)) {
  1576. return array();
  1577. }
  1578. $statusCondition = null;
  1579. if (isset($status) && !is_null($status)) {
  1580. $status = intval($status);
  1581. $statusCondition = " AND status = $status";
  1582. }
  1583. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1584. $sql = "SELECT DISTINCT id_user
  1585. FROM $table
  1586. WHERE
  1587. id_session = '$sessionId' AND
  1588. course_code='$courseCode'
  1589. $statusCondition
  1590. ";
  1591. $result = Database::query($sql);
  1592. $existingUsers = array();
  1593. while ($row = Database::fetch_array($result)) {
  1594. $existingUsers[] = $row['id_user'];
  1595. }
  1596. return $existingUsers;
  1597. }
  1598. /**
  1599. * Remove a list of users from a course-session
  1600. * @param array $userList
  1601. * @param int $sessionId
  1602. * @param array $courseInfo
  1603. * @param int $status
  1604. * @param bool $updateTotal
  1605. * @return bool
  1606. */
  1607. public static function removeUsersFromCourseSession(
  1608. $userList,
  1609. $sessionId,
  1610. $courseInfo,
  1611. $status = null,
  1612. $updateTotal = true
  1613. ) {
  1614. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1615. $tableSessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1616. $sessionId = intval($sessionId);
  1617. if (empty($sessionId) || empty($userList) || empty($courseInfo)) {
  1618. return false;
  1619. }
  1620. $courses = SessionManager::getCoursesInSession($sessionId);
  1621. $courseCode = Database::escape_string($courseInfo['code']);
  1622. $statusCondition = null;
  1623. if (isset($status) && !is_null($status)) {
  1624. $status = intval($status);
  1625. $statusCondition = " AND status = $status";
  1626. }
  1627. foreach ($userList as $userId) {
  1628. $userId = intval($userId);
  1629. $sql = "DELETE FROM $table
  1630. WHERE
  1631. id_session='$sessionId' AND
  1632. course_code='$courseCode' AND
  1633. id_user='$userId'
  1634. $statusCondition
  1635. ";
  1636. Database::query($sql);
  1637. if (count($courses) == 1) {
  1638. SessionManager::unsubscribe_user_from_session($sessionId, $userId);
  1639. }
  1640. }
  1641. if ($updateTotal) {
  1642. // Count users in this session-course relation
  1643. $sql = "SELECT COUNT(id_user) as nbUsers
  1644. FROM $table
  1645. WHERE
  1646. id_session='$sessionId' AND
  1647. course_code='$courseCode' AND
  1648. status<>2";
  1649. $result = Database::query($sql);
  1650. list($userCount) = Database::fetch_array($result);
  1651. // update the session-course relation to add the users total
  1652. $sql = "UPDATE $tableSessionCourse SET
  1653. nbr_users = $userCount
  1654. WHERE id_session='$sessionId' AND course_code = '$courseCode'";
  1655. Database::query($sql);
  1656. }
  1657. }
  1658. /**
  1659. * Subscribe a user to an specific course inside a session.
  1660. *
  1661. * @param array $user_list
  1662. * @param int $session_id
  1663. * @param string $course_code
  1664. * @param int $session_visibility
  1665. * @param bool $removeUsersNotInList
  1666. * @return bool
  1667. */
  1668. public static function subscribe_users_to_session_course(
  1669. $user_list,
  1670. $session_id,
  1671. $course_code,
  1672. $session_visibility = SESSION_VISIBLE_READ_ONLY,
  1673. $removeUsersNotInList = false
  1674. ) {
  1675. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1676. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1677. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1678. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1679. if (empty($session_id) || empty($course_code)) {
  1680. return false;
  1681. }
  1682. $session_id = intval($session_id);
  1683. $course_code = Database::escape_string($course_code);
  1684. $session_visibility = intval($session_visibility);
  1685. if ($removeUsersNotInList) {
  1686. $courseInfo = api_get_course_info($course_code);
  1687. $currentUsers = self::getUsersByCourseSession($session_id, $courseInfo, 0);
  1688. if (!empty($user_list)) {
  1689. $userToDelete = array_diff($currentUsers, $user_list);
  1690. } else {
  1691. $userToDelete = $currentUsers;
  1692. }
  1693. if (!empty($userToDelete)) {
  1694. self::removeUsersFromCourseSession(
  1695. $userToDelete,
  1696. $session_id,
  1697. $courseInfo,
  1698. 0,
  1699. true
  1700. );
  1701. }
  1702. }
  1703. $nbr_users = 0;
  1704. foreach ($user_list as $enreg_user) {
  1705. $enreg_user = intval($enreg_user);
  1706. // Checking if user exists in session - course - user table.
  1707. $sql = "SELECT count(id_user) as count
  1708. FROM $tbl_session_rel_course_rel_user
  1709. WHERE
  1710. id_session = $session_id AND
  1711. course_code = '$course_code' and
  1712. id_user = $enreg_user ";
  1713. $result = Database::query($sql);
  1714. $count = 0;
  1715. if (Database::num_rows($result) > 0) {
  1716. $row = Database::fetch_array($result, 'ASSOC');
  1717. $count = $row['count'];
  1718. }
  1719. if ($count == 0) {
  1720. $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (id_session, course_code, id_user, visibility)
  1721. VALUES ('$session_id','$course_code','$enreg_user','$session_visibility')";
  1722. Database::query($sql);
  1723. if (Database::affected_rows()) {
  1724. $nbr_users++;
  1725. }
  1726. }
  1727. // Checking if user exists in session - user table.
  1728. $sql = "SELECT count(id_user) as count
  1729. FROM $tbl_session_rel_user
  1730. WHERE id_session = $session_id AND id_user = $enreg_user ";
  1731. $result = Database::query($sql);
  1732. $count = 0;
  1733. if (Database::num_rows($result) > 0) {
  1734. $row = Database::fetch_array($result, 'ASSOC');
  1735. $count = $row['count'];
  1736. }
  1737. if (empty($count)) {
  1738. // If user is not registered to a session then add it.
  1739. $sql = "INSERT IGNORE INTO $tbl_session_rel_user (id_session, id_user)
  1740. VALUES ('$session_id', '$enreg_user')";
  1741. Database::query($sql);
  1742. $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + 1
  1743. WHERE id='$session_id' ";
  1744. Database::query($sql);
  1745. }
  1746. }
  1747. // count users in this session-course relation
  1748. $sql = "SELECT COUNT(id_user) as nbUsers
  1749. FROM $tbl_session_rel_course_rel_user
  1750. WHERE id_session='$session_id' AND course_code='$course_code' AND status<>2";
  1751. $rs = Database::query($sql);
  1752. list($nbr_users) = Database::fetch_array($rs);
  1753. // update the session-course relation to add the users total
  1754. $sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users
  1755. WHERE id_session='$session_id' AND course_code='$course_code'";
  1756. Database::query($sql);
  1757. }
  1758. /**
  1759. * Unsubscribe user from session
  1760. *
  1761. * @param int Session id
  1762. * @param int User id
  1763. * @return bool True in case of success, false in case of error
  1764. */
  1765. public static function unsubscribe_user_from_session($session_id, $user_id)
  1766. {
  1767. $session_id = (int) $session_id;
  1768. $user_id = (int) $user_id;
  1769. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1770. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1771. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1772. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1773. $delete_sql = "DELETE FROM $tbl_session_rel_user
  1774. WHERE
  1775. id_session = '$session_id' AND
  1776. id_user ='$user_id' AND
  1777. relation_type <> " . SESSION_RELATION_TYPE_RRHH . "";
  1778. Database::query($delete_sql);
  1779. $return = Database::affected_rows();
  1780. // Update number of users
  1781. $sql = "UPDATE $tbl_session
  1782. SET nbr_users = nbr_users - $return
  1783. WHERE id='$session_id' ";
  1784. Database::query($sql);
  1785. // Get the list of courses related to this session
  1786. $course_list = SessionManager::get_course_list_by_session_id($session_id);
  1787. if (!empty($course_list)) {
  1788. foreach ($course_list as $course) {
  1789. $course_code = $course['code'];
  1790. // Delete user from course
  1791. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  1792. WHERE id_session='$session_id' AND course_code='$course_code' AND id_user='$user_id'";
  1793. Database::query($sql);
  1794. event_system(
  1795. LOG_SESSION_DELETE_USER_COURSE,
  1796. LOG_USER_ID,
  1797. $user_id,
  1798. api_get_utc_datetime(),
  1799. api_get_user_id(),
  1800. $course_code,
  1801. $session_id
  1802. );
  1803. if (Database::affected_rows()) {
  1804. // Update number of users in this relation
  1805. $sql = "UPDATE $tbl_session_rel_course SET nbr_users = nbr_users - 1
  1806. WHERE id_session='$session_id' AND course_code='$course_code'";
  1807. Database::query($sql);
  1808. }
  1809. }
  1810. }
  1811. return true;
  1812. }
  1813. /**
  1814. * Subscribes courses to the given session and optionally (default)
  1815. * unsubscribes previous users
  1816. * @author Carlos Vargas from existing code
  1817. * @param int $sessionId
  1818. * @param array $courseList List of courses IDs
  1819. * @param bool $removeExistingCoursesUsers Whether to unsubscribe
  1820. * existing courses and users (true, default) or not (false)
  1821. * @return void Nothing, or false on error
  1822. * */
  1823. public static function add_courses_to_session(
  1824. $sessionId,
  1825. $courseList,
  1826. $removeExistingCoursesWithUsers = true
  1827. ) {
  1828. $sessionId = intval($sessionId);
  1829. if (empty($sessionId) || empty($courseList)) {
  1830. return false;
  1831. }
  1832. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1833. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1834. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1835. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1836. // get list of courses subscribed to this session
  1837. $sql = "SELECT course_code
  1838. FROM $tbl_session_rel_course
  1839. WHERE id_session=$sessionId";
  1840. $rs = Database::query($sql );
  1841. $existingCourses = Database::store_result($rs);
  1842. $nbr_courses = count($existingCourses);
  1843. // get list of users subscribed to this session
  1844. $sql = "SELECT id_user
  1845. FROM $tbl_session_rel_user
  1846. WHERE
  1847. id_session = $sessionId AND
  1848. relation_type<>" . SESSION_RELATION_TYPE_RRHH;
  1849. $result = Database::query($sql);
  1850. $user_list = Database::store_result($result);
  1851. // Remove existing courses from the session.
  1852. if ($removeExistingCoursesWithUsers === true) {
  1853. foreach ($existingCourses as $existingCourse) {
  1854. if (!in_array($existingCourse['course_code'], $courseList)) {
  1855. $courseInfo = api_get_course_info($existingCourse['course_code']);
  1856. $sql = "DELETE FROM $tbl_session_rel_course
  1857. WHERE course_code='" . $existingCourse['course_code'] . "' AND id_session=$sessionId";
  1858. Database::query($sql);
  1859. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  1860. WHERE course_code='" . $existingCourse['course_code'] . "' AND id_session=$sessionId";
  1861. Database::query($sql);
  1862. event_system(
  1863. LOG_SESSION_DELETE_COURSE,
  1864. LOG_COURSE_ID,
  1865. $existingCourse['c_id'],
  1866. api_get_utc_datetime(),
  1867. api_get_user_id(),
  1868. $existingCourse['course_code'],
  1869. $sessionId
  1870. );
  1871. CourseManager::remove_course_ranking(
  1872. $courseInfo['real_id'],
  1873. $sessionId
  1874. );
  1875. $nbr_courses--;
  1876. }
  1877. }
  1878. }
  1879. // Pass through the courses list we want to add to the session
  1880. foreach ($courseList as $enreg_course) {
  1881. $enreg_course = Database::escape_string($enreg_course);
  1882. $exists = false;
  1883. // check if the course we want to add is already subscribed
  1884. foreach ($existingCourses as $existingCourse) {
  1885. if ($enreg_course == $existingCourse['course_code']) {
  1886. $exists = true;
  1887. }
  1888. }
  1889. if (!$exists) {
  1890. //if the course isn't subscribed yet
  1891. $sql = "INSERT INTO $tbl_session_rel_course (id_session, course_code)
  1892. VALUES ('$sessionId','$enreg_course')";
  1893. Database::query($sql);
  1894. event_system(
  1895. LOG_SESSION_ADD_COURSE,
  1896. LOG_COURSE_ID,
  1897. $enreg_course,
  1898. api_get_utc_datetime(),
  1899. api_get_user_id(),
  1900. $enreg_course,
  1901. $sessionId
  1902. );
  1903. //We add the current course in the existing courses array, to avoid adding another time the current course
  1904. $existingCourses[] = array('course_code' => $enreg_course);
  1905. $nbr_courses++;
  1906. // subscribe all the users from the session to this course inside the session
  1907. $nbr_users = 0;
  1908. foreach ($user_list as $enreg_user) {
  1909. $enreg_user_id = intval($enreg_user['id_user']);
  1910. $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (id_session, course_code, id_user)
  1911. VALUES ($sessionId,'$enreg_course',$enreg_user_id)";
  1912. Database::query($sql);
  1913. event_system(
  1914. LOG_SESSION_ADD_USER_COURSE,
  1915. LOG_USER_ID,
  1916. $enreg_user_id,
  1917. api_get_utc_datetime(),
  1918. api_get_user_id(),
  1919. $enreg_course,
  1920. $sessionId
  1921. );
  1922. if (Database::affected_rows()) {
  1923. $nbr_users++;
  1924. }
  1925. }
  1926. $sql = "UPDATE $tbl_session_rel_course
  1927. SET nbr_users=$nbr_users
  1928. WHERE id_session='$sessionId' AND course_code='$enreg_course'";
  1929. Database::query($sql);
  1930. }
  1931. }
  1932. $sql = "UPDATE $tbl_session
  1933. SET nbr_courses = $nbr_courses
  1934. WHERE id = '$sessionId'";
  1935. Database::query($sql);
  1936. }
  1937. /**
  1938. * Unsubscribe course from a session
  1939. *
  1940. * @param int Session id
  1941. * @param int Course id
  1942. * @return bool True in case of success, false otherwise
  1943. */
  1944. public static function unsubscribe_course_from_session($session_id, $course_id)
  1945. {
  1946. $session_id = (int) $session_id;
  1947. $course_id = (int) $course_id;
  1948. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1949. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1950. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1951. // Get course code
  1952. $course_code = CourseManager::get_course_code_from_course_id($course_id);
  1953. if (empty($course_code)) {
  1954. return false;
  1955. }
  1956. // Unsubscribe course
  1957. $sql = "DELETE FROM $tbl_session_rel_course
  1958. WHERE course_code='$course_code' AND id_session='$session_id'";
  1959. Database::query($sql);
  1960. $nb_affected = Database::affected_rows();
  1961. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  1962. WHERE course_code='$course_code' AND id_session='$session_id'";
  1963. Database::query($sql);
  1964. event_system(
  1965. LOG_SESSION_DELETE_COURSE,
  1966. LOG_COURSE_ID,
  1967. $course_id,
  1968. api_get_utc_datetime(),
  1969. api_get_user_id(),
  1970. $course_code,
  1971. $session_id
  1972. );
  1973. if ($nb_affected > 0) {
  1974. // Update number of courses in the session
  1975. $sql = "UPDATE $tbl_session SET nbr_courses= nbr_courses + $nb_affected WHERE id='$session_id' ";
  1976. Database::query($sql);
  1977. return true;
  1978. } else {
  1979. return false;
  1980. }
  1981. }
  1982. /**
  1983. * Creates a new extra field for a given session
  1984. * @param string Field's internal variable name
  1985. * @param int Field's type
  1986. * @param string Field's language var name
  1987. * @return int new extra field id
  1988. */
  1989. public static function create_session_extra_field($fieldvarname, $fieldtype, $fieldtitle)
  1990. {
  1991. // database table definition
  1992. $t_sf = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  1993. $fieldvarname = Database::escape_string($fieldvarname);
  1994. $fieldtitle = Database::escape_string($fieldtitle);
  1995. $fieldtype = (int) $fieldtype;
  1996. $time = time();
  1997. $sql_field = "SELECT id FROM $t_sf WHERE field_variable = '$fieldvarname'";
  1998. $res_field = Database::query($sql_field);
  1999. $r_field = Database::fetch_row($res_field);
  2000. if (Database::num_rows($res_field) > 0) {
  2001. $field_id = $r_field[0];
  2002. } else {
  2003. // save new fieldlabel into course_field table
  2004. $sql = "SELECT MAX(field_order) FROM $t_sf";
  2005. $res = Database::query($sql);
  2006. $order = 0;
  2007. if (Database::num_rows($res) > 0) {
  2008. $row = Database::fetch_row($res);
  2009. $order = $row[0] + 1;
  2010. }
  2011. $sql = "INSERT INTO $t_sf SET
  2012. field_type = '$fieldtype',
  2013. field_variable = '$fieldvarname',
  2014. field_display_text = '$fieldtitle',
  2015. field_order = '$order',
  2016. tms = FROM_UNIXTIME($time)";
  2017. Database::query($sql);
  2018. $field_id = Database::insert_id();
  2019. }
  2020. return $field_id;
  2021. }
  2022. /**
  2023. * Update an extra field value for a given session
  2024. * @param integer Course ID
  2025. * @param string Field variable name
  2026. * @param string Field value
  2027. * @return boolean true if field updated, false otherwise
  2028. */
  2029. public static function update_session_extra_field_value($session_id, $fname, $fvalue = '')
  2030. {
  2031. $t_sf = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  2032. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  2033. $fname = Database::escape_string($fname);
  2034. $session_id = (int) $session_id;
  2035. $fvalues = '';
  2036. if (is_array($fvalue)) {
  2037. foreach ($fvalue as $val) {
  2038. $fvalues .= Database::escape_string($val) . ';';
  2039. }
  2040. if (!empty($fvalues)) {
  2041. $fvalues = substr($fvalues, 0, -1);
  2042. }
  2043. } else {
  2044. $fvalues = Database::escape_string($fvalue);
  2045. }
  2046. $sqlsf = "SELECT * FROM $t_sf WHERE field_variable='$fname'";
  2047. $ressf = Database::query($sqlsf);
  2048. if (Database::num_rows($ressf) == 1) {
  2049. //ok, the field exists
  2050. // Check if enumerated field, if the option is available
  2051. $rowsf = Database::fetch_array($ressf);
  2052. $tms = time();
  2053. $sqlsfv = "SELECT * FROM $t_sfv
  2054. WHERE session_id = '$session_id' AND field_id = '" . $rowsf['id'] . "' ORDER BY id";
  2055. $ressfv = Database::query($sqlsfv);
  2056. $n = Database::num_rows($ressfv);
  2057. if ($n > 1) {
  2058. //problem, we already have to values for this field and user combination - keep last one
  2059. while ($rowsfv = Database::fetch_array($ressfv)) {
  2060. if ($n > 1) {
  2061. $sqld = "DELETE FROM $t_sfv WHERE id = " . $rowsfv['id'];
  2062. $resd = Database::query($sqld);
  2063. $n--;
  2064. }
  2065. $rowsfv = Database::fetch_array($ressfv);
  2066. if ($rowsfv['field_value'] != $fvalues) {
  2067. $sqlu = "UPDATE $t_sfv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms)
  2068. WHERE id = " . $rowsfv['id'];
  2069. $resu = Database::query($sqlu);
  2070. return($resu ? true : false);
  2071. }
  2072. return true;
  2073. }
  2074. } else if ($n == 1) {
  2075. //we need to update the current record
  2076. $rowsfv = Database::fetch_array($ressfv);
  2077. if ($rowsfv['field_value'] != $fvalues) {
  2078. $sqlu = "UPDATE $t_sfv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms)
  2079. WHERE id = " . $rowsfv['id'];
  2080. //error_log('UM::update_extra_field_value: '.$sqlu);
  2081. $resu = Database::query($sqlu);
  2082. return($resu ? true : false);
  2083. }
  2084. return true;
  2085. } else {
  2086. $sqli = "INSERT INTO $t_sfv (session_id,field_id,field_value,tms) " .
  2087. "VALUES ('$session_id'," . $rowsf['id'] . ",'$fvalues',FROM_UNIXTIME($tms))";
  2088. $resi = Database::query($sqli);
  2089. return $resi ? true : false;
  2090. }
  2091. } else {
  2092. return false; //field not found
  2093. }
  2094. }
  2095. /**
  2096. * Checks the relationship between a session and a course.
  2097. * @param int $session_id
  2098. * @param string $course_id (course code)
  2099. * @return bool Returns TRUE if the session and the course are related, FALSE otherwise.
  2100. * */
  2101. public static function relation_session_course_exist($session_id, $course_id)
  2102. {
  2103. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2104. $return_value = false;
  2105. $sql = "SELECT course_code FROM $tbl_session_course
  2106. WHERE
  2107. id_session = " . intval($session_id) . " AND
  2108. course_code = '" . Database::escape_string($course_id) . "'";
  2109. $result = Database::query($sql);
  2110. $num = Database::num_rows($result);
  2111. if ($num > 0) {
  2112. $return_value = true;
  2113. }
  2114. return $return_value;
  2115. }
  2116. /**
  2117. * Get the session information by name
  2118. * @param string session name
  2119. * @return mixed false if the session does not exist, array if the session exist
  2120. * */
  2121. public static function get_session_by_name($session_name)
  2122. {
  2123. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2124. $session_name = trim($session_name);
  2125. if (empty($session_name)) {
  2126. return false;
  2127. }
  2128. $sql = 'SELECT *
  2129. FROM ' . $tbl_session . '
  2130. WHERE name = "' . Database::escape_string($session_name) . '"';
  2131. $result = Database::query($sql);
  2132. $num = Database::num_rows($result);
  2133. if ($num > 0) {
  2134. return Database::fetch_array($result);
  2135. } else {
  2136. return false;
  2137. }
  2138. }
  2139. /**
  2140. * Create a session category
  2141. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
  2142. * @param string name
  2143. * @param integer year_start
  2144. * @param integer month_start
  2145. * @param integer day_start
  2146. * @param integer year_end
  2147. * @param integer month_end
  2148. * @param integer day_end
  2149. * @return $id_session;
  2150. * */
  2151. public static function create_category_session($sname, $syear_start, $smonth_start, $sday_start, $syear_end, $smonth_end, $sday_end)
  2152. {
  2153. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2154. $name = trim($sname);
  2155. $year_start = intval($syear_start);
  2156. $month_start = intval($smonth_start);
  2157. $day_start = intval($sday_start);
  2158. $year_end = intval($syear_end);
  2159. $month_end = intval($smonth_end);
  2160. $day_end = intval($sday_end);
  2161. $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
  2162. $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
  2163. if (empty($name)) {
  2164. $msg = get_lang('SessionCategoryNameIsRequired');
  2165. return $msg;
  2166. } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
  2167. $msg = get_lang('InvalidStartDate');
  2168. return $msg;
  2169. } elseif (!$month_end && !$day_end && !$year_end) {
  2170. $date_end = "null";
  2171. } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
  2172. $msg = get_lang('InvalidEndDate');
  2173. return $msg;
  2174. } elseif ($date_start >= $date_end) {
  2175. $msg = get_lang('StartDateShouldBeBeforeEndDate');
  2176. return $msg;
  2177. }
  2178. $access_url_id = api_get_current_access_url_id();
  2179. $sql = "INSERT INTO $tbl_session_category (name, date_start, date_end, access_url_id)
  2180. VALUES('" . Database::escape_string($name) . "','$date_start','$date_end', '$access_url_id')";
  2181. Database::query($sql);
  2182. $id_session = Database::insert_id();
  2183. // Add event to system log
  2184. $user_id = api_get_user_id();
  2185. event_system(
  2186. LOG_SESSION_CATEGORY_CREATE,
  2187. LOG_SESSION_CATEGORY_ID,
  2188. $id_session,
  2189. api_get_utc_datetime(),
  2190. $user_id
  2191. );
  2192. return $id_session;
  2193. }
  2194. /**
  2195. * Edit a sessions categories
  2196. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,from existing code
  2197. * @param integer id
  2198. * @param string name
  2199. * @param integer year_start
  2200. * @param integer month_start
  2201. * @param integer day_start
  2202. * @param integer year_end
  2203. * @param integer month_end
  2204. * @param integer day_end
  2205. * @return $id;
  2206. * The parameter id is a primary key
  2207. * */
  2208. public static function edit_category_session($id, $sname, $syear_start, $smonth_start, $sday_start, $syear_end, $smonth_end, $sday_end)
  2209. {
  2210. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2211. $name = trim($sname);
  2212. $year_start = intval($syear_start);
  2213. $month_start = intval($smonth_start);
  2214. $day_start = intval($sday_start);
  2215. $year_end = intval($syear_end);
  2216. $month_end = intval($smonth_end);
  2217. $day_end = intval($sday_end);
  2218. $id = intval($id);
  2219. $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
  2220. $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
  2221. if (empty($name)) {
  2222. $msg = get_lang('SessionCategoryNameIsRequired');
  2223. return $msg;
  2224. } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
  2225. $msg = get_lang('InvalidStartDate');
  2226. return $msg;
  2227. } elseif (!$month_end && !$day_end && !$year_end) {
  2228. $date_end = null;
  2229. } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
  2230. $msg = get_lang('InvalidEndDate');
  2231. return $msg;
  2232. } elseif ($date_start >= $date_end) {
  2233. $msg = get_lang('StartDateShouldBeBeforeEndDate');
  2234. return $msg;
  2235. }
  2236. if ($date_end <> null) {
  2237. $sql = "UPDATE $tbl_session_category SET name = '" . Database::escape_string($name) . "', date_start = '$date_start' " .
  2238. ", date_end = '$date_end' WHERE id= '" . $id . "' ";
  2239. } else {
  2240. $sql = "UPDATE $tbl_session_category SET name = '" . Database::escape_string($name) . "', date_start = '$date_start' " .
  2241. ", date_end = NULL WHERE id= '" . $id . "' ";
  2242. }
  2243. $result = Database::query($sql);
  2244. return ($result ? true : false);
  2245. }
  2246. /**
  2247. * Delete sessions categories
  2248. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
  2249. * @param array id_checked
  2250. * @param bool include delete session
  2251. * @param bool optional, true if the function is called by a webservice, false otherwise.
  2252. * @return void Nothing, or false on error
  2253. * The parameters is a array to delete sessions
  2254. * */
  2255. public static function delete_session_category($id_checked, $delete_session = false, $from_ws = false)
  2256. {
  2257. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2258. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2259. if (is_array($id_checked)) {
  2260. $id_checked = Database::escape_string(implode(',', $id_checked));
  2261. } else {
  2262. $id_checked = intval($id_checked);
  2263. }
  2264. //Setting session_category_id to 0
  2265. $sql = "UPDATE $tbl_session SET session_category_id = 0
  2266. WHERE session_category_id IN (" . $id_checked . ")";
  2267. Database::query($sql);
  2268. $sql = "SELECT id FROM $tbl_session WHERE session_category_id IN (" . $id_checked . ")";
  2269. $result = Database::query($sql);
  2270. while ($rows = Database::fetch_array($result)) {
  2271. $session_id = $rows['id'];
  2272. if ($delete_session) {
  2273. if ($from_ws) {
  2274. SessionManager::delete_session($session_id, true);
  2275. } else {
  2276. SessionManager::delete_session($session_id);
  2277. }
  2278. }
  2279. }
  2280. $sql = "DELETE FROM $tbl_session_category WHERE id IN (" . $id_checked . ")";
  2281. Database::query($sql);
  2282. // Add event to system log
  2283. $user_id = api_get_user_id();
  2284. event_system(
  2285. LOG_SESSION_CATEGORY_DELETE,
  2286. LOG_SESSION_CATEGORY_ID,
  2287. $id_checked,
  2288. api_get_utc_datetime(),
  2289. $user_id
  2290. );
  2291. return true;
  2292. }
  2293. /**
  2294. * Get a list of sessions of which the given conditions match with an = 'cond'
  2295. * @param array $conditions a list of condition example :
  2296. * array('status' => STUDENT) or
  2297. * array('s.name' => array('operator' => 'LIKE', value = '%$needle%'))
  2298. * @param array $order_by a list of fields on which sort
  2299. * @return array An array with all sessions of the platform.
  2300. * @todo optional course code parameter, optional sorting parameters...
  2301. */
  2302. public static function get_sessions_list($conditions = array(), $order_by = array(), $from = null, $to = null)
  2303. {
  2304. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  2305. $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2306. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  2307. $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2308. $session_course_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2309. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  2310. $access_url_id = api_get_current_access_url_id();
  2311. $return_array = array();
  2312. $sql_query = " SELECT
  2313. s.id,
  2314. s.name,
  2315. s.nbr_courses,
  2316. s.date_start,
  2317. s.date_end,
  2318. u.firstname,
  2319. u.lastname,
  2320. sc.name as category_name,
  2321. s.promotion_id
  2322. FROM $session_table s
  2323. INNER JOIN $user_table u ON s.id_coach = u.user_id
  2324. INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
  2325. LEFT JOIN $session_category_table sc ON s.session_category_id = sc.id
  2326. LEFT JOIN $session_course_table sco ON (sco.id_session = s.id)
  2327. INNER JOIN $course_table c ON sco.course_code = c.code
  2328. WHERE ar.access_url_id = $access_url_id ";
  2329. $availableFields = array(
  2330. 's.id',
  2331. 's.name'
  2332. );
  2333. $availableOperator = array(
  2334. 'like',
  2335. '>=',
  2336. '<=',
  2337. '='
  2338. );
  2339. if (count($conditions) > 0) {
  2340. foreach ($conditions as $field => $options) {
  2341. $operator = strtolower($options['operator']);
  2342. $value = Database::escape_string($options['value']);
  2343. $sql_query .= ' AND ';
  2344. if (in_array($field, $availableFields) && in_array($operator, $availableOperator)) {
  2345. $sql_query .= $field . " $operator '" . $value . "'";
  2346. }
  2347. }
  2348. }
  2349. $orderAvailableList = array('name');
  2350. if (count($order_by) > 0) {
  2351. $order = null;
  2352. $direction = null;
  2353. if (isset($order_by[0]) && in_array($order_by[0], $orderAvailableList)) {
  2354. $order = $order_by[0];
  2355. }
  2356. if (isset($order_by[1]) && in_array(strtolower($order_by[1]), array('desc', 'asc'))) {
  2357. $direction = $order_by[1];
  2358. }
  2359. if (!empty($order)) {
  2360. $sql_query .= " ORDER BY $order $direction ";
  2361. }
  2362. }
  2363. if (!is_null($from) && !is_null($to)) {
  2364. $to = intval($to);
  2365. $from = intval($from);
  2366. $sql_query .= "LIMIT $from, $to";
  2367. }
  2368. $sql_result = Database::query($sql_query);
  2369. if (Database::num_rows($sql_result) > 0) {
  2370. while ($result = Database::fetch_array($sql_result)) {
  2371. $return_array[$result['id']] = $result;
  2372. }
  2373. }
  2374. return $return_array;
  2375. }
  2376. /**
  2377. * Get the session category information by id
  2378. * @param string session category ID
  2379. * @return mixed false if the session category does not exist, array if the session category exists
  2380. */
  2381. public static function get_session_category($id)
  2382. {
  2383. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2384. $id = intval($id);
  2385. $sql = "SELECT id, name, date_start, date_end FROM $tbl_session_category WHERE id= $id";
  2386. $result = Database::query($sql);
  2387. $num = Database::num_rows($result);
  2388. if ($num > 0) {
  2389. return Database::fetch_array($result);
  2390. } else {
  2391. return false;
  2392. }
  2393. }
  2394. /**
  2395. * Get all session categories (filter by access_url_id)
  2396. * @return mixed false if the session category does not exist, array if the session category exists
  2397. */
  2398. public static function get_all_session_category()
  2399. {
  2400. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2401. $id = api_get_current_access_url_id();
  2402. $sql = 'SELECT * FROM ' . $tbl_session_category . '
  2403. WHERE access_url_id ="' . $id . '"
  2404. ORDER BY name ASC';
  2405. $result = Database::query($sql);
  2406. if (Database::num_rows($result) > 0) {
  2407. $data = Database::store_result($result, 'ASSOC');
  2408. return $data;
  2409. } else {
  2410. return false;
  2411. }
  2412. }
  2413. /**
  2414. * Assign a coach to course in session with status = 2
  2415. * @param int - user id
  2416. * @param int - session id
  2417. * @param string - course code
  2418. * @param bool - optional, if is true the user don't be a coach now, otherwise it'll assign a coach
  2419. * @return bool true if there are affected rows, otherwise false
  2420. */
  2421. public static function set_coach_to_course_session(
  2422. $user_id,
  2423. $session_id = 0,
  2424. $course_code = '',
  2425. $nocoach = false
  2426. ) {
  2427. // Definition of variables
  2428. $user_id = intval($user_id);
  2429. if (!empty($session_id)) {
  2430. $session_id = intval($session_id);
  2431. } else {
  2432. $session_id = api_get_session_id();
  2433. }
  2434. if (!empty($course_code)) {
  2435. $course_code = Database::escape_string($course_code);
  2436. } else {
  2437. $course_code = api_get_course_id();
  2438. }
  2439. // Table definition
  2440. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2441. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2442. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2443. // check if user is a teacher
  2444. $sql = "SELECT * FROM $tbl_user WHERE status='1' AND user_id = '$user_id'";
  2445. $rs_check_user = Database::query($sql);
  2446. if (Database::num_rows($rs_check_user) > 0) {
  2447. if ($nocoach) {
  2448. // check if user_id exits int session_rel_user
  2449. $sql = "SELECT id_user FROM $tbl_session_rel_user
  2450. WHERE id_session = '$session_id' AND id_user = '$user_id'";
  2451. $res = Database::query($sql);
  2452. if (Database::num_rows($res) > 0) {
  2453. // The user don't be a coach now
  2454. $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 0
  2455. WHERE id_session = '$session_id' AND course_code = '$course_code' AND id_user = '$user_id' ";
  2456. Database::query($sql);
  2457. if (Database::affected_rows() > 0)
  2458. return true;
  2459. else
  2460. return false;
  2461. } else {
  2462. // The user don't be a coach now
  2463. $sql = "DELETE FROM $tbl_session_rel_course_rel_user
  2464. WHERE id_session = '$session_id' AND course_code = '$course_code' AND id_user = '$user_id' ";
  2465. Database::query($sql);
  2466. if (Database::affected_rows() > 0)
  2467. return true;
  2468. else
  2469. return false;
  2470. }
  2471. } else {
  2472. // Assign user like a coach to course
  2473. // First check if the user is registered in the course
  2474. $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user
  2475. WHERE id_session = '$session_id' AND course_code = '$course_code' AND id_user = '$user_id'";
  2476. $rs_check = Database::query($sql);
  2477. // Then update or insert.
  2478. if (Database::num_rows($rs_check) > 0) {
  2479. $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 2
  2480. WHERE id_session = '$session_id' AND course_code = '$course_code' AND id_user = '$user_id' ";
  2481. Database::query($sql);
  2482. if (Database::affected_rows() > 0) {
  2483. return true;
  2484. } else {
  2485. return false;
  2486. }
  2487. } else {
  2488. $sql = "INSERT INTO $tbl_session_rel_course_rel_user(id_session, course_code, id_user, status)
  2489. VALUES('$session_id', '$course_code', '$user_id', 2)";
  2490. Database::query($sql);
  2491. if (Database::affected_rows() > 0) {
  2492. return true;
  2493. } else {
  2494. return false;
  2495. }
  2496. }
  2497. }
  2498. } else {
  2499. return false;
  2500. }
  2501. }
  2502. /**
  2503. * Subscribes sessions to human resource manager (Dashboard feature)
  2504. * @param array $userInfo Human Resource Manager info
  2505. * @param array $sessions_list Sessions id
  2506. * @param bool $sendEmail
  2507. * @param bool $removeOldConnections
  2508. * @return int
  2509. * */
  2510. public static function suscribe_sessions_to_hr_manager(
  2511. $userInfo,
  2512. $sessions_list,
  2513. $sendEmail = false,
  2514. $removeOldConnections = true
  2515. ) {
  2516. // Database Table Definitions
  2517. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2518. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2519. if (empty($userInfo)) {
  2520. return 0;
  2521. }
  2522. $userId = $userInfo['user_id'];
  2523. // Only subscribe DRH users.
  2524. if ($userInfo['status'] != DRH) {
  2525. return 0;
  2526. }
  2527. $affected_rows = 0;
  2528. // Deleting assigned sessions to hrm_id.
  2529. if ($removeOldConnections) {
  2530. if (api_is_multiple_url_enabled()) {
  2531. $sql = "SELECT id_session
  2532. FROM $tbl_session_rel_user s
  2533. INNER JOIN $tbl_session_rel_access_url a ON (a.session_id = s.id_session)
  2534. WHERE
  2535. id_user = $userId AND
  2536. relation_type=" . SESSION_RELATION_TYPE_RRHH . " AND
  2537. access_url_id = " . api_get_current_access_url_id() . "";
  2538. } else {
  2539. $sql = "SELECT id_session FROM $tbl_session_rel_user s
  2540. WHERE id_user = $userId AND relation_type=" . SESSION_RELATION_TYPE_RRHH . "";
  2541. }
  2542. $result = Database::query($sql);
  2543. if (Database::num_rows($result) > 0) {
  2544. while ($row = Database::fetch_array($result)) {
  2545. $sql = "DELETE FROM $tbl_session_rel_user
  2546. WHERE
  2547. id_session = {$row['id_session']} AND
  2548. id_user = $userId AND
  2549. relation_type=" . SESSION_RELATION_TYPE_RRHH . " ";
  2550. Database::query($sql);
  2551. }
  2552. }
  2553. }
  2554. // Inserting new sessions list.
  2555. if (!empty($sessions_list) && is_array($sessions_list)) {
  2556. foreach ($sessions_list as $session_id) {
  2557. $session_id = intval($session_id);
  2558. $sql = "INSERT IGNORE INTO $tbl_session_rel_user (id_session, id_user, relation_type)
  2559. VALUES ($session_id, $userId, '" . SESSION_RELATION_TYPE_RRHH . "')";
  2560. Database::query($sql);
  2561. $affected_rows++;
  2562. }
  2563. }
  2564. return $affected_rows;
  2565. }
  2566. /**
  2567. * @param int $sessionId
  2568. * @return array
  2569. */
  2570. public static function getDrhUsersInSession($sessionId)
  2571. {
  2572. return self::get_users_by_session($sessionId, SESSION_RELATION_TYPE_RRHH);
  2573. }
  2574. /**
  2575. * @param int $userId
  2576. * @param int $sessionId
  2577. * @return array
  2578. */
  2579. public static function getSessionFollowedByDrh($userId, $sessionId)
  2580. {
  2581. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2582. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2583. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2584. $userId = intval($userId);
  2585. $sessionId = intval($sessionId);
  2586. $select = " SELECT * ";
  2587. if (api_is_multiple_url_enabled()) {
  2588. $sql = " $select FROM $tbl_session s
  2589. INNER JOIN $tbl_session_rel_user sru ON (sru.id_session = s.id)
  2590. LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
  2591. WHERE
  2592. sru.id_user = '$userId' AND
  2593. sru.id_session = '$sessionId' AND
  2594. sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "' AND
  2595. access_url_id = " . api_get_current_access_url_id() . "
  2596. ";
  2597. } else {
  2598. $sql = "$select FROM $tbl_session s
  2599. INNER JOIN $tbl_session_rel_user sru
  2600. ON
  2601. sru.id_session = s.id AND
  2602. sru.id_user = '$userId' AND
  2603. sru.id_session = '$sessionId' AND
  2604. sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "'
  2605. ";
  2606. }
  2607. $result = Database::query($sql);
  2608. if (Database::num_rows($result)) {
  2609. $row = Database::fetch_array($result, 'ASSOC');
  2610. $row['course_list'] = self::get_course_list_by_session_id($sessionId);
  2611. return $row;
  2612. }
  2613. return array();
  2614. }
  2615. /**
  2616. * Get sessions followed by human resources manager
  2617. * @param int $userId
  2618. * @param int $start
  2619. * @param int $limit
  2620. * @param bool $getCount
  2621. * @param bool $getOnlySessionId
  2622. * @param bool $getSql
  2623. * @param string $orderCondition
  2624. * @param string $description
  2625. *
  2626. * @return array sessions
  2627. */
  2628. public static function get_sessions_followed_by_drh(
  2629. $userId,
  2630. $start = null,
  2631. $limit = null,
  2632. $getCount = false,
  2633. $getOnlySessionId = false,
  2634. $getSql = false,
  2635. $orderCondition = null,
  2636. $keyword = '',
  2637. $description = ''
  2638. ) {
  2639. return self::getSessionsFollowedByUser(
  2640. $userId,
  2641. DRH,
  2642. $start,
  2643. $limit,
  2644. $getCount,
  2645. $getOnlySessionId,
  2646. $getSql,
  2647. $orderCondition,
  2648. $keyword,
  2649. $description
  2650. );
  2651. }
  2652. /**
  2653. * Get sessions followed by human resources manager
  2654. * @param int $userId
  2655. * @param int $start
  2656. * @param int $limit
  2657. * @param bool $getCount
  2658. * @param bool $getOnlySessionId
  2659. * @param bool $getSql
  2660. * @param string $orderCondition
  2661. * @param string $keyword
  2662. * @param string $description
  2663. * @return array sessions
  2664. */
  2665. public static function getSessionsFollowedByUser(
  2666. $userId,
  2667. $status = null,
  2668. $start = null,
  2669. $limit = null,
  2670. $getCount = false,
  2671. $getOnlySessionId = false,
  2672. $getSql = false,
  2673. $orderCondition = null,
  2674. $keyword = '',
  2675. $description = ''
  2676. ) {
  2677. // Database Table Definitions
  2678. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2679. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2680. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2681. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2682. $userId = intval($userId);
  2683. $select = " SELECT DISTINCT * ";
  2684. if ($getCount) {
  2685. $select = " SELECT count(DISTINCT(s.id)) as count ";
  2686. }
  2687. if ($getOnlySessionId) {
  2688. $select = " SELECT DISTINCT(s.id) ";
  2689. }
  2690. $limitCondition = null;
  2691. if (!empty($start) && !empty($limit)) {
  2692. $limitCondition = " LIMIT " . intval($start) . ", " . intval($limit);
  2693. }
  2694. if (empty($orderCondition)) {
  2695. $orderCondition = " ORDER BY s.name ";
  2696. }
  2697. $whereConditions = null;
  2698. $sessionCourseConditions = null;
  2699. $sessionConditions = null;
  2700. $sessionQuery = null;
  2701. $courseSessionQuery = null;
  2702. switch ($status) {
  2703. case DRH:
  2704. $sessionQuery = "SELECT sru.id_session
  2705. FROM
  2706. $tbl_session_rel_user sru
  2707. WHERE
  2708. sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
  2709. sru.id_user = $userId";
  2710. break;
  2711. case COURSEMANAGER:
  2712. $courseSessionQuery = "
  2713. SELECT scu.id_session as id
  2714. FROM $tbl_session_rel_course_rel_user scu
  2715. WHERE (scu.status = 2 AND scu.id_user = $userId)";
  2716. $whereConditions = " OR (s.id_coach = $userId) ";
  2717. break;
  2718. default:
  2719. $sessionQuery = "SELECT sru.id_session
  2720. FROM
  2721. $tbl_session_rel_user sru
  2722. WHERE
  2723. sru.id_user = $userId";
  2724. break;
  2725. }
  2726. $keywordCondition = '';
  2727. if (!empty($keyword)) {
  2728. $keyword = Database::escape_string($keyword);
  2729. $keywordCondition = " AND (s.name LIKE '%$keyword%' ) ";
  2730. if (!empty($description)) {
  2731. $description = Database::escape_string($description);
  2732. $keywordCondition = " AND (s.name LIKE '%$keyword%' OR s.description LIKE '%$description%' ) ";
  2733. }
  2734. }
  2735. $whereConditions .= $keywordCondition;
  2736. $subQuery = $sessionQuery.$courseSessionQuery;
  2737. $sql = " $select FROM $tbl_session s
  2738. INNER JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
  2739. WHERE
  2740. access_url_id = ".api_get_current_access_url_id()." AND
  2741. s.id IN (
  2742. $subQuery
  2743. )
  2744. $whereConditions
  2745. $orderCondition
  2746. $limitCondition";
  2747. if ($getSql) {
  2748. return $sql;
  2749. }
  2750. $result = Database::query($sql);
  2751. if ($getCount) {
  2752. $row = Database::fetch_array($result);
  2753. return $row['count'];
  2754. }
  2755. $sessions = array();
  2756. if (Database::num_rows($result) > 0) {
  2757. while ($row = Database::fetch_array($result)) {
  2758. $sessions[$row['id']] = $row;
  2759. }
  2760. }
  2761. return $sessions;
  2762. }
  2763. /**
  2764. * Gets the list (or the count) of courses by session filtered by access_url
  2765. * @param int $session_id The session id
  2766. * @param string $course_name The course code
  2767. * @param string $orderBy Field to order the data
  2768. * @param boolean $getCount Optional. Count the session courses
  2769. * @return array|int List of courses. Whether $getCount is true, return the count
  2770. */
  2771. public static function get_course_list_by_session_id(
  2772. $session_id,
  2773. $course_name = '',
  2774. $orderBy = null,
  2775. $getCount = false
  2776. ) {
  2777. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2778. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2779. $session_id = intval($session_id);
  2780. $sqlSelect = "SELECT *";
  2781. if ($getCount) {
  2782. $sqlSelect = "SELECT COUNT(1)";
  2783. }
  2784. // select the courses
  2785. $sql = "$sqlSelect FROM $tbl_course c
  2786. INNER JOIN $tbl_session_rel_course src
  2787. ON c.code = src.course_code
  2788. WHERE src.id_session = '$session_id' ";
  2789. if (!empty($course_name)) {
  2790. $course_name = Database::escape_string($course_name);
  2791. $sql .= " AND c.title LIKE '%$course_name%' ";
  2792. }
  2793. if (!empty($orderBy)) {
  2794. $orderBy = Database::escape_string($orderBy);
  2795. $orderBy = " ORDER BY $orderBy";
  2796. } else {
  2797. if (SessionManager::orderCourseIsEnabled()) {
  2798. $orderBy .= " ORDER BY position ";
  2799. } else {
  2800. $orderBy .= " ORDER BY title ";
  2801. }
  2802. }
  2803. $sql .= Database::escape_string($orderBy);
  2804. $result = Database::query($sql);
  2805. $num_rows = Database::num_rows($result);
  2806. $courses = array();
  2807. if ($num_rows > 0) {
  2808. if ($getCount) {
  2809. $count = Database::fetch_array($result);
  2810. return intval($count[0]);
  2811. }
  2812. while ($row = Database::fetch_array($result,'ASSOC')) {
  2813. $courses[$row['id']] = $row;
  2814. }
  2815. }
  2816. return $courses;
  2817. }
  2818. /**
  2819. * Gets the list of courses by session filtered by access_url
  2820. *
  2821. * @param $userId
  2822. * @param $sessionId
  2823. * @param null $from
  2824. * @param null $limit
  2825. * @param null $column
  2826. * @param null $direction
  2827. * @param bool $getCount
  2828. * @return array
  2829. */
  2830. public static function getAllCoursesFollowedByUser(
  2831. $userId,
  2832. $sessionId,
  2833. $from = null,
  2834. $limit = null,
  2835. $column = null,
  2836. $direction = null,
  2837. $getCount = false,
  2838. $keyword = null
  2839. ) {
  2840. if (empty($sessionId)) {
  2841. $sessionsSQL = SessionManager::get_sessions_followed_by_drh(
  2842. $userId,
  2843. null,
  2844. null,
  2845. null,
  2846. true,
  2847. true
  2848. );
  2849. } else {
  2850. $sessionsSQL = intval($sessionId);
  2851. }
  2852. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2853. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2854. if ($getCount) {
  2855. $select = "SELECT COUNT(DISTINCT(c.code)) as count ";
  2856. } else {
  2857. $select = "SELECT DISTINCT c.* ";
  2858. }
  2859. $keywordCondition = null;
  2860. if (!empty($keyword)) {
  2861. $keyword = Database::escape_string($keyword);
  2862. $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
  2863. }
  2864. // Select the courses
  2865. $sql = "$select
  2866. FROM $tbl_course c
  2867. INNER JOIN $tbl_session_rel_course src
  2868. ON c.code = src.course_code
  2869. WHERE
  2870. src.id_session IN ($sessionsSQL)
  2871. $keywordCondition
  2872. ";
  2873. if ($getCount) {
  2874. $result = Database::query($sql);
  2875. $row = Database::fetch_array($result,'ASSOC');
  2876. return $row['count'];
  2877. }
  2878. if (isset($from) && isset($limit)) {
  2879. $from = intval($from);
  2880. $limit = intval($limit);
  2881. $sql .= " LIMIT $from, $limit";
  2882. }
  2883. $result = Database::query($sql);
  2884. $num_rows = Database::num_rows($result);
  2885. $courses = array();
  2886. if ($num_rows > 0) {
  2887. while ($row = Database::fetch_array($result,'ASSOC')) {
  2888. $courses[$row['id']] = $row;
  2889. }
  2890. }
  2891. return $courses;
  2892. }
  2893. /**
  2894. * Gets the list of courses by session filtered by access_url
  2895. * @param int session id
  2896. * @param string course_name
  2897. * @return array list of courses
  2898. */
  2899. public static function get_course_list_by_session_id_like($session_id, $course_name = '')
  2900. {
  2901. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2902. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2903. $session_id = intval($session_id);
  2904. $course_name = Database::escape_string($course_name);
  2905. // select the courses
  2906. $sql = "SELECT * FROM $tbl_course c
  2907. INNER JOIN $tbl_session_rel_course src
  2908. ON c.code = src.course_code
  2909. WHERE src.id_session LIKE '$session_id'";
  2910. if (!empty($course_name)) {
  2911. $sql .= " AND UPPER(c.title) LIKE UPPER('%$course_name%') ";
  2912. }
  2913. $sql .= "ORDER BY title;";
  2914. $result = Database::query($sql);
  2915. $num_rows = Database::num_rows($result);
  2916. $courses = array();
  2917. if ($num_rows > 0) {
  2918. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2919. $courses[$row['id']] = $row;
  2920. }
  2921. }
  2922. return $courses;
  2923. }
  2924. /**
  2925. * Gets the count of courses by session filtered by access_url
  2926. * @param int session id
  2927. * @return array list of courses
  2928. */
  2929. public static function getCourseCountBySessionId($session_id, $keyword = null)
  2930. {
  2931. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2932. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2933. $session_id = intval($session_id);
  2934. // select the courses
  2935. $sql = "SELECT COUNT(c.code) count
  2936. FROM $tbl_course c
  2937. INNER JOIN $tbl_session_rel_course src
  2938. ON c.code = src.course_code
  2939. WHERE src.id_session = '$session_id' ";
  2940. $keywordCondition = null;
  2941. if (!empty($keyword)) {
  2942. $keyword = Database::escape_string($keyword);
  2943. $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
  2944. }
  2945. $sql .= $keywordCondition;
  2946. $result = Database::query($sql);
  2947. $num_rows = Database::num_rows($result);
  2948. if ($num_rows > 0) {
  2949. $row = Database::fetch_array($result,'ASSOC');
  2950. return $row['count'];
  2951. }
  2952. return null;
  2953. }
  2954. /**
  2955. * Get the session id based on the original id and field name in the extra fields.
  2956. * Returns 0 if session was not found
  2957. *
  2958. * @param string $original_session_id_value Original session id
  2959. * @param string $original_session_id_name Original field name
  2960. * @return int Session id
  2961. */
  2962. public static function get_session_id_from_original_id($original_session_id_value, $original_session_id_name)
  2963. {
  2964. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  2965. $table_field = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  2966. $original_session_id_value = Database::escape_string($original_session_id_value);
  2967. $original_session_id_name = Database::escape_string($original_session_id_name);
  2968. $sql = "SELECT session_id
  2969. FROM $table_field sf INNER JOIN $t_sfv sfv ON sfv.field_id=sf.id
  2970. WHERE
  2971. field_variable='$original_session_id_name' AND
  2972. field_value='$original_session_id_value'";
  2973. $res_session = Database::query($sql);
  2974. $row = Database::fetch_object($res_session);
  2975. if ($row) {
  2976. return $row->session_id;
  2977. } else {
  2978. return 0;
  2979. }
  2980. }
  2981. /**
  2982. * Get users by session
  2983. * @param int $id session id
  2984. * @param int $status filter by status coach = 2
  2985. * @return array a list with an user list
  2986. */
  2987. public static function get_users_by_session($id, $status = null)
  2988. {
  2989. if (empty($id)) {
  2990. return array();
  2991. }
  2992. $id = intval($id);
  2993. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2994. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2995. $table_access_url_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  2996. $sql = "SELECT u.user_id, lastname, firstname, username, relation_type, access_url_id
  2997. FROM $tbl_user u
  2998. INNER JOIN $tbl_session_rel_user
  2999. ON u.user_id = $tbl_session_rel_user.id_user AND
  3000. $tbl_session_rel_user.id_session = $id
  3001. LEFT OUTER JOIN $table_access_url_user uu ON (uu.user_id = u.user_id)
  3002. ";
  3003. $urlId = api_get_current_access_url_id();
  3004. if (isset($status) && $status != '') {
  3005. $status = intval($status);
  3006. $sql .= " WHERE relation_type = $status (access_url_id = $urlId OR access_url_id is null )";
  3007. } else {
  3008. $sql .= " WHERE (access_url_id = $urlId OR access_url_id is null )";
  3009. }
  3010. $sql .= " ORDER BY relation_type, ";
  3011. $sql .= api_sort_by_first_name() ? ' firstname, lastname' : ' lastname, firstname';
  3012. $result = Database::query($sql);
  3013. $return_array = array();
  3014. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3015. $return_array[] = $row;
  3016. }
  3017. return $return_array;
  3018. }
  3019. /**
  3020. * The general coach (field: session.id_coach)
  3021. * @param int $user_id user id
  3022. * @return array
  3023. */
  3024. public static function get_sessions_by_general_coach($user_id)
  3025. {
  3026. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3027. $user_id = intval($user_id);
  3028. // Session where we are general coach
  3029. $sql = "SELECT DISTINCT *
  3030. FROM $session_table
  3031. WHERE id_coach = $user_id";
  3032. if (api_is_multiple_url_enabled()) {
  3033. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3034. $access_url_id = api_get_current_access_url_id();
  3035. if ($access_url_id != -1) {
  3036. $sql = 'SELECT DISTINCT session.*
  3037. FROM ' . $session_table . ' session INNER JOIN ' . $tbl_session_rel_access_url . ' session_rel_url
  3038. ON (session.id = session_rel_url.session_id)
  3039. WHERE id_coach = ' . $user_id . ' AND access_url_id = ' . $access_url_id;
  3040. }
  3041. }
  3042. $sql .= ' ORDER by name';
  3043. $result = Database::query($sql);
  3044. return Database::store_result($result, 'ASSOC');
  3045. }
  3046. /**
  3047. * @param int $user_id
  3048. * @return array
  3049. * @deprecated use get_sessions_by_general_coach()
  3050. */
  3051. public static function get_sessions_by_coach($user_id)
  3052. {
  3053. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3054. return Database::select('*', $session_table, array('where' => array('id_coach = ?' => $user_id)));
  3055. }
  3056. /**
  3057. * @param int $user_id
  3058. * @param string $course_code
  3059. * @param int $session_id
  3060. * @return array|bool
  3061. */
  3062. public static function get_user_status_in_course_session($user_id, $course_code, $session_id)
  3063. {
  3064. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3065. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3066. $sql = "SELECT session_rcru.status
  3067. FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  3068. WHERE
  3069. session_rcru.id_user = user.user_id AND
  3070. session_rcru.id_session = '" . intval($session_id) . "' AND
  3071. session_rcru.course_code ='" . Database::escape_string($course_code) . "' AND
  3072. user.user_id = " . intval($user_id);
  3073. $result = Database::query($sql);
  3074. $status = false;
  3075. if (Database::num_rows($result)) {
  3076. $status = Database::fetch_row($result);
  3077. $status = $status['0'];
  3078. }
  3079. return $status;
  3080. }
  3081. /**
  3082. * Gets user status within a session
  3083. * @param $user_id
  3084. * @param $course_code
  3085. * @param $session_id
  3086. * @return int
  3087. * @assert (null,null,null) === false
  3088. */
  3089. public static function get_user_status_in_session($user_id, $course_code, $session_id)
  3090. {
  3091. if (empty($user_id) or empty($course_code) or empty($session_id)) {
  3092. return false;
  3093. }
  3094. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3095. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3096. $sql = "SELECT session_rcru.status
  3097. FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  3098. WHERE session_rcru.id_user = user.user_id AND
  3099. session_rcru.id_session = '" . intval($session_id) . "' AND
  3100. session_rcru.course_code ='" . Database::escape_string($course_code) . "' AND
  3101. user.user_id = " . intval($user_id);
  3102. $result = Database::query($sql);
  3103. $status = false;
  3104. if (Database::num_rows($result)) {
  3105. $status = Database::fetch_row($result);
  3106. $status = $status['0'];
  3107. }
  3108. return $status;
  3109. }
  3110. /**
  3111. * @param int $id
  3112. * @return array
  3113. */
  3114. public static function get_all_sessions_by_promotion($id)
  3115. {
  3116. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  3117. return Database::select('*', $t, array('where' => array('promotion_id = ?' => $id)));
  3118. }
  3119. /**
  3120. * @param int $promotion_id
  3121. * @param array $list
  3122. */
  3123. public static function suscribe_sessions_to_promotion($promotion_id, $list)
  3124. {
  3125. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  3126. $params = array();
  3127. $params['promotion_id'] = 0;
  3128. Database::update($t, $params, array('promotion_id = ?' => $promotion_id));
  3129. $params['promotion_id'] = $promotion_id;
  3130. if (!empty($list)) {
  3131. foreach ($list as $session_id) {
  3132. $session_id = intval($session_id);
  3133. Database::update($t, $params, array('id = ?' => $session_id));
  3134. }
  3135. }
  3136. }
  3137. /**
  3138. * Updates a session status
  3139. * @param int session id
  3140. * @param int status
  3141. */
  3142. public static function set_session_status($session_id, $status)
  3143. {
  3144. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  3145. $params['visibility'] = $status;
  3146. Database::update($t, $params, array('id = ?' => $session_id));
  3147. }
  3148. /**
  3149. * Copies a session with the same data to a new session.
  3150. * The new copy is not assigned to the same promotion. @see suscribe_sessions_to_promotions() for that
  3151. * @param int Session ID
  3152. * @param bool Whether to copy the relationship with courses
  3153. * @param bool Whether to copy the relationship with users
  3154. * @param bool New courses will be created
  3155. * @return int The new session ID on success, 0 otherwise
  3156. * @todo make sure the extra session fields are copied too
  3157. */
  3158. public static function copy_session($id, $copy_courses = true, $copy_users = true, $create_new_courses = false, $set_exercises_lp_invisible = false)
  3159. {
  3160. $id = intval($id);
  3161. $s = self::fetch($id);
  3162. $s['year_start'] = substr($s['date_start'], 0, 4);
  3163. $s['month_start'] = substr($s['date_start'], 5, 2);
  3164. $s['day_start'] = substr($s['date_start'], 8, 2);
  3165. $s['year_end'] = substr($s['date_end'], 0, 4);
  3166. $s['month_end'] = substr($s['date_end'], 5, 2);
  3167. $s['day_end'] = substr($s['date_end'], 8, 2);
  3168. $consider_start = true;
  3169. if ($s['year_start'] . '-' . $s['month_start'] . '-' . $s['day_start'] == '0000-00-00') {
  3170. $consider_start = false;
  3171. }
  3172. $consider_end = true;
  3173. if ($s['year_end'] . '-' . $s['month_end'] . '-' . $s['day_end'] == '0000-00-00') {
  3174. $consider_end = false;
  3175. }
  3176. $sid = self::create_session(
  3177. $s['name'] . ' ' . get_lang('CopyLabelSuffix'),
  3178. $s['year_start'],
  3179. $s['month_start'],
  3180. $s['day_start'],
  3181. $s['year_end'],
  3182. $s['month_end'],
  3183. $s['day_end'],
  3184. $s['nb_days_acess_before_beginning'],
  3185. $s['nb_days_acess_after_end'],
  3186. false,
  3187. (int)$s['id_coach'],
  3188. $s['session_category_id'],
  3189. (int)$s['visibility'],
  3190. $consider_start,
  3191. $consider_end,
  3192. true
  3193. );
  3194. if (!is_numeric($sid) || empty($sid)) {
  3195. return false;
  3196. }
  3197. if ($copy_courses) {
  3198. // Register courses from the original session to the new session
  3199. $courses = self::get_course_list_by_session_id($id);
  3200. $short_courses = $new_short_courses = array();
  3201. if (is_array($courses) && count($courses) > 0) {
  3202. foreach ($courses as $course) {
  3203. $short_courses[] = $course;
  3204. }
  3205. }
  3206. $courses = null;
  3207. //We will copy the current courses of the session to new courses
  3208. if (!empty($short_courses)) {
  3209. if ($create_new_courses) {
  3210. //Just in case
  3211. if (function_exists('ini_set')) {
  3212. api_set_memory_limit('256M');
  3213. ini_set('max_execution_time', 0);
  3214. }
  3215. $params = array();
  3216. $params['skip_lp_dates'] = true;
  3217. foreach ($short_courses as $course_data) {
  3218. $course_info = CourseManager::copy_course_simple($course_data['title'] . ' ' . get_lang('CopyLabelSuffix'), $course_data['course_code'], $id, $sid, $params);
  3219. if ($course_info) {
  3220. //By default new elements are invisible
  3221. if ($set_exercises_lp_invisible) {
  3222. require_once api_get_path(SYS_CODE_PATH) . 'newscorm/learnpathList.class.php';
  3223. $list = new LearnpathList('', $course_info['code'], $sid);
  3224. $flat_list = $list->get_flat_list();
  3225. if (!empty($flat_list)) {
  3226. foreach ($flat_list as $lp_id => $data) {
  3227. api_item_property_update($course_info, TOOL_LEARNPATH, $lp_id, 'invisible', api_get_user_id(), 0, 0, 0, 0, $sid);
  3228. api_item_property_update($course_info, TOOL_LEARNPATH, $lp_id, 'invisible', api_get_user_id(), 0, 0, 0, 0);
  3229. }
  3230. }
  3231. $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
  3232. $course_id = $course_info['real_id'];
  3233. //@todo check this query
  3234. $sql = "UPDATE $quiz_table SET active = 0 WHERE c_id = $course_id ";
  3235. $result = Database::query($sql);
  3236. }
  3237. $new_short_courses[] = $course_info['code'];
  3238. }
  3239. }
  3240. } else {
  3241. foreach ($short_courses as $course_data) {
  3242. $new_short_courses[] = $course_data['code'];
  3243. }
  3244. }
  3245. $short_courses = $new_short_courses;
  3246. self::add_courses_to_session($sid, $short_courses, true);
  3247. $short_courses = null;
  3248. }
  3249. }
  3250. if ($copy_users) {
  3251. // Register users from the original session to the new session
  3252. $users = self::get_users_by_session($id);
  3253. $short_users = array();
  3254. if (is_array($users) && count($users) > 0) {
  3255. foreach ($users as $user) {
  3256. $short_users[] = $user['user_id'];
  3257. }
  3258. }
  3259. $users = null;
  3260. //Subscribing in read only mode
  3261. self::suscribe_users_to_session($sid, $short_users, SESSION_VISIBLE_READ_ONLY, true, false);
  3262. $short_users = null;
  3263. }
  3264. return $sid;
  3265. }
  3266. /**
  3267. * @param int $user_id
  3268. * @param int $session_id
  3269. * @return bool
  3270. */
  3271. static function user_is_general_coach($user_id, $session_id)
  3272. {
  3273. $session_id = intval($session_id);
  3274. $user_id = intval($user_id);
  3275. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3276. $sql = "SELECT DISTINCT id
  3277. FROM $session_table
  3278. WHERE session.id_coach = '" . $user_id . "' AND id = '$session_id'";
  3279. $result = Database::query($sql);
  3280. if ($result && Database::num_rows($result)) {
  3281. return true;
  3282. }
  3283. return false;
  3284. }
  3285. /**
  3286. * Get the number of sessions
  3287. * @param int ID of the URL we want to filter on (optional)
  3288. * @return int Number of sessions
  3289. */
  3290. public static function count_sessions($access_url_id = null)
  3291. {
  3292. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3293. $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3294. $sql = "SELECT count(id) FROM $session_table s";
  3295. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  3296. $sql .= ", $access_url_rel_session_table u " .
  3297. " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
  3298. }
  3299. $res = Database::query($sql);
  3300. $row = Database::fetch_row($res);
  3301. return $row[0];
  3302. }
  3303. /**
  3304. * Protect a session to be edited.
  3305. * @param int $id
  3306. */
  3307. static function protect_session_edit($id)
  3308. {
  3309. api_protect_admin_script(true);
  3310. $session_info = self::fetch($id);
  3311. if (empty($session_info)) {
  3312. api_not_allowed(true);
  3313. }
  3314. if (!api_is_platform_admin() &&
  3315. api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true'
  3316. ) {
  3317. if ($session_info['session_admin_id'] != api_get_user_id()) {
  3318. api_not_allowed(true);
  3319. }
  3320. }
  3321. }
  3322. /**
  3323. * @param $id
  3324. * @return bool
  3325. */
  3326. static function protect_teacher_session_edit($id)
  3327. {
  3328. if (!api_is_coach($id) && !api_is_platform_admin()) {
  3329. api_not_allowed(true);
  3330. } else {
  3331. return true;
  3332. }
  3333. }
  3334. /**
  3335. * @param string $course_code
  3336. * @return array
  3337. */
  3338. public static function get_session_by_course($course_code)
  3339. {
  3340. $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3341. $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3342. $course_code = Database::escape_string($course_code);
  3343. $sql = "SELECT name, s.id
  3344. FROM $table_session_course sc
  3345. INNER JOIN $table_session s ON (sc.id_session = s.id)
  3346. WHERE sc.course_code = '$course_code' ";
  3347. $result = Database::query($sql);
  3348. return Database::store_result($result);
  3349. }
  3350. /**
  3351. * @param int $user_id
  3352. * @param bool $ignore_visibility_for_admins
  3353. * @return array
  3354. */
  3355. public static function get_sessions_by_user($user_id, $ignore_visibility_for_admins = false)
  3356. {
  3357. $session_categories = UserManager::get_sessions_by_category(
  3358. $user_id,
  3359. false,
  3360. $ignore_visibility_for_admins
  3361. );
  3362. $session_array = array();
  3363. if (!empty($session_categories)) {
  3364. foreach ($session_categories as $category) {
  3365. if (isset($category['sessions'])) {
  3366. foreach ($category['sessions'] as $session) {
  3367. $session_array[] = $session;
  3368. }
  3369. }
  3370. }
  3371. }
  3372. return $session_array;
  3373. }
  3374. /**
  3375. * @param string $file
  3376. * @param bool $updateSession options:
  3377. * true: if the session exists it will be updated.
  3378. * false: if session exists a new session will be created adding a counter session1, session2, etc
  3379. * @param int $defaultUserId
  3380. * @param mixed $logger
  3381. * @param array $extraFields convert a file row to an extra field. Example in CSV file there's a SessionID then it will
  3382. * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
  3383. * @param string $extraFieldId
  3384. * @param int $daysCoachAccessBeforeBeginning
  3385. * @param int $daysCoachAccessAfterBeginning
  3386. * @param int $sessionVisibility
  3387. * @param array $fieldsToAvoidUpdate
  3388. * @param bool $deleteUsersNotInList
  3389. * @param bool $updateCourseCoaches
  3390. * @param bool $sessionWithCoursesModifier
  3391. * @param int $showDescription
  3392. * @param array $teacherBackupList
  3393. * @param array $groupBackup
  3394. *
  3395. * @return array
  3396. */
  3397. static function importCSV(
  3398. $file,
  3399. $updateSession,
  3400. $defaultUserId = null,
  3401. $logger = null,
  3402. $extraFields = array(),
  3403. $extraFieldId = null,
  3404. $daysCoachAccessBeforeBeginning = null,
  3405. $daysCoachAccessAfterBeginning = null,
  3406. $sessionVisibility = 1,
  3407. $fieldsToAvoidUpdate = array(),
  3408. $deleteUsersNotInList = false,
  3409. $updateCourseCoaches = false,
  3410. $sessionWithCoursesModifier = false,
  3411. $addOriginalCourseTeachersAsCourseSessionCoaches = true,
  3412. $removeAllTeachersFromCourse = true,
  3413. $showDescription = null,
  3414. &$teacherBackupList = array(),
  3415. &$groupBackup = array()
  3416. ) {
  3417. $content = file($file);
  3418. $error_message = null;
  3419. $session_counter = 0;
  3420. if (empty($defaultUserId)) {
  3421. $defaultUserId = api_get_user_id();
  3422. }
  3423. $eol = PHP_EOL;
  3424. if (PHP_SAPI != 'cli') {
  3425. $eol = '<br />';
  3426. }
  3427. $debug = false;
  3428. if (isset($logger)) {
  3429. $debug = true;
  3430. }
  3431. $extraParameters = null;
  3432. if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
  3433. $extraParameters .= ' , nb_days_access_before_beginning = '.intval($daysCoachAccessBeforeBeginning);
  3434. $extraParameters .= ' , nb_days_access_after_end = '.intval($daysCoachAccessAfterBeginning);
  3435. }
  3436. if (!is_null($showDescription)) {
  3437. $extraParameters .= ' , show_description = '.intval($showDescription);
  3438. }
  3439. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3440. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3441. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3442. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3443. $sessions = array();
  3444. if (!api_strstr($content[0], ';')) {
  3445. $error_message = get_lang('NotCSV');
  3446. } else {
  3447. $tag_names = array();
  3448. foreach ($content as $key => $enreg) {
  3449. $enreg = explode(';', trim($enreg));
  3450. if ($key) {
  3451. foreach ($tag_names as $tag_key => $tag_name) {
  3452. $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
  3453. }
  3454. } else {
  3455. foreach ($enreg as $tag_name) {
  3456. $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
  3457. }
  3458. if (!in_array('SessionName', $tag_names) ||
  3459. !in_array('DateStart', $tag_names) ||
  3460. !in_array('DateEnd', $tag_names)
  3461. ) {
  3462. $error_message = get_lang('NoNeededData');
  3463. break;
  3464. }
  3465. }
  3466. }
  3467. $sessionList = array();
  3468. // Looping the sessions.
  3469. foreach ($sessions as $enreg) {
  3470. $user_counter = 0;
  3471. $course_counter = 0;
  3472. if (isset($extraFields) && !empty($extraFields)) {
  3473. foreach ($extraFields as $original => $to) {
  3474. $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
  3475. }
  3476. }
  3477. $session_name = Database::escape_string($enreg['SessionName']);
  3478. // Default visibility
  3479. $visibilityAfterExpirationPerSession = $sessionVisibility;
  3480. if (isset($enreg['VisibilityAfterExpiration'])) {
  3481. $visibility = $enreg['VisibilityAfterExpiration'];
  3482. switch ($visibility) {
  3483. case 'read_only':
  3484. $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
  3485. break;
  3486. case 'accessible':
  3487. $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
  3488. break;
  3489. case 'not_accessible':
  3490. $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
  3491. break;
  3492. }
  3493. }
  3494. if (empty($session_name)) {
  3495. continue;
  3496. }
  3497. /*$date_start = $enreg['DateStart'];
  3498. $date_end = $enreg['DateEnd'];*/
  3499. $date_start = str_replace('/', '-', $enreg['DateStart']);
  3500. $date_end = str_replace('/', '-', $enreg['DateEnd']);
  3501. $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
  3502. $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
  3503. $extraSessionParameters = null;
  3504. if (!empty($sessionDescription)) {
  3505. $extraSessionParameters = " , description = '".Database::escape_string($sessionDescription)."'";
  3506. }
  3507. // Searching a general coach.
  3508. if (!empty($enreg['Coach'])) {
  3509. $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
  3510. if ($coach_id === false) {
  3511. // If the coach-user does not exist - I'm the coach.
  3512. $coach_id = $defaultUserId;
  3513. }
  3514. } else {
  3515. $coach_id = $defaultUserId;
  3516. }
  3517. if (!$updateSession) {
  3518. // Always create a session.
  3519. $unique_name = false;
  3520. $i = 0;
  3521. // Change session name, verify that session doesn't exist.
  3522. $suffix = null;
  3523. while (!$unique_name) {
  3524. if ($i > 1) {
  3525. $suffix = ' - ' . $i;
  3526. }
  3527. $sql = 'SELECT 1 FROM ' . $tbl_session . ' WHERE name="' . $session_name . $suffix . '"';
  3528. $rs = Database::query($sql);
  3529. if (Database::result($rs, 0, 0)) {
  3530. $i++;
  3531. } else {
  3532. $unique_name = true;
  3533. $session_name .= $suffix;
  3534. }
  3535. }
  3536. // Creating the session.
  3537. $sql = "INSERT IGNORE INTO $tbl_session SET
  3538. name = '" . $session_name . "',
  3539. id_coach = '$coach_id',
  3540. date_start = '$date_start',
  3541. date_end = '$date_end',
  3542. visibility = '$visibilityAfterExpirationPerSession',
  3543. session_category_id = '$session_category_id',
  3544. session_admin_id = " . intval($defaultUserId) . $extraParameters . $extraSessionParameters;
  3545. Database::query($sql);
  3546. $session_id = Database::insert_id();
  3547. if ($debug) {
  3548. if ($session_id) {
  3549. foreach ($enreg as $key => $value) {
  3550. if (substr($key, 0, 6) == 'extra_') { //an extra field
  3551. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  3552. }
  3553. }
  3554. $logger->addInfo("Sessions - Session created: #$session_id - $session_name");
  3555. } else {
  3556. $logger->addError("Sessions - Session NOT created: $session_name");
  3557. }
  3558. }
  3559. $session_counter++;
  3560. } else {
  3561. $sessionId = null;
  3562. if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_'.$extraFieldId])) {
  3563. $sessionId = self::get_session_id_from_original_id($enreg['extra_'.$extraFieldId], $extraFieldId);
  3564. if (empty($sessionId)) {
  3565. $my_session_result = false;
  3566. } else {
  3567. $my_session_result = true;
  3568. }
  3569. } else {
  3570. $my_session_result = self::get_session_by_name($enreg['SessionName']);
  3571. }
  3572. if ($my_session_result === false) {
  3573. // Creating a session.
  3574. $sql = "INSERT IGNORE INTO $tbl_session SET
  3575. name = '$session_name',
  3576. id_coach = '$coach_id',
  3577. date_start = '$date_start',
  3578. date_end = '$date_end',
  3579. visibility = '$visibilityAfterExpirationPerSession',
  3580. session_category_id = '$session_category_id' " . $extraParameters . $extraSessionParameters;
  3581. Database::query($sql);
  3582. // We get the last insert id.
  3583. $my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
  3584. $session_id = $my_session_result['id'];
  3585. if ($session_id) {
  3586. foreach ($enreg as $key => $value) {
  3587. if (substr($key, 0, 6) == 'extra_') { //an extra field
  3588. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  3589. }
  3590. }
  3591. if ($debug) {
  3592. $logger->addInfo("Sessions - #$session_id created: $session_name");
  3593. }
  3594. // Delete session-user relation only for students
  3595. $sql = "DELETE FROM $tbl_session_user
  3596. WHERE id_session = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
  3597. Database::query($sql);
  3598. $sql = "DELETE FROM $tbl_session_course WHERE id_session = '$session_id'";
  3599. Database::query($sql);
  3600. // Delete session-course-user relationships students and coaches.
  3601. if ($updateCourseCoaches) {
  3602. $sql = "DELETE FROM $tbl_session_course_user WHERE id_session = '$session_id' AND status in ('0', '2')";
  3603. Database::query($sql);
  3604. } else {
  3605. // Delete session-course-user relation ships *only* for students.
  3606. $sql = "DELETE FROM $tbl_session_course_user WHERE id_session = '$session_id' AND status <> 2";
  3607. Database::query($sql);
  3608. }
  3609. }
  3610. } else {
  3611. if ($debug) {
  3612. $logger->addError("Sessions - Session to be updated: $session_name");
  3613. }
  3614. // Updating the session.
  3615. $params = array(
  3616. 'id_coach' => $coach_id,
  3617. 'date_start' => $date_start,
  3618. 'date_end' => $date_end,
  3619. 'visibility' => $visibilityAfterExpirationPerSession,
  3620. 'session_category_id' => $session_category_id
  3621. );
  3622. if (!empty($sessionDescription)) {
  3623. $params['description'] = $sessionDescription;
  3624. }
  3625. if (!empty($fieldsToAvoidUpdate)) {
  3626. foreach ($fieldsToAvoidUpdate as $field) {
  3627. unset($params[$field]);
  3628. }
  3629. }
  3630. if (isset($sessionId) && !empty($sessionId)) {
  3631. if (!empty($enreg['SessionName'])) {
  3632. $params['name'] = $enreg['SessionName'];
  3633. }
  3634. $session_id = $sessionId;
  3635. } else {
  3636. $row = Database::query("SELECT id FROM $tbl_session WHERE name = '$session_name'");
  3637. list($session_id) = Database::fetch_array($row);
  3638. }
  3639. if ($session_id) {
  3640. if ($debug) {
  3641. $logger->addError("Sessions - Session to be updated #$session_id");
  3642. }
  3643. $sessionInfo = api_get_session_info($session_id);
  3644. $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
  3645. if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
  3646. if (empty($sessionInfo['nb_days_access_before_beginning']) ||
  3647. (!empty($sessionInfo['nb_days_access_before_beginning']) &&
  3648. $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning)
  3649. ) {
  3650. $params['nb_days_access_before_beginning'] = intval($daysCoachAccessBeforeBeginning);
  3651. }
  3652. if (empty($sessionInfo['nb_days_access_after_end']) ||
  3653. (!empty($sessionInfo['nb_days_access_after_end']) &&
  3654. $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning)
  3655. ) {
  3656. $params['nb_days_access_after_end'] = intval($daysCoachAccessAfterBeginning);
  3657. }
  3658. }
  3659. Database::update($tbl_session, $params, array('id = ?' => $session_id));
  3660. foreach ($enreg as $key => $value) {
  3661. if (substr($key, 0, 6) == 'extra_') { //an extra field
  3662. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  3663. }
  3664. }
  3665. // Delete session-user relation only for students
  3666. $sql = "DELETE FROM $tbl_session_user
  3667. WHERE id_session = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
  3668. Database::query($sql);
  3669. $sql = "DELETE FROM $tbl_session_course WHERE id_session = '$session_id'";
  3670. Database::query($sql);
  3671. // Delete session-course-user relationships students and coaches.
  3672. if ($updateCourseCoaches) {
  3673. $sql = "DELETE FROM $tbl_session_course_user
  3674. WHERE id_session = '$session_id' AND status in ('0', '2')";
  3675. Database::query($sql);
  3676. } else {
  3677. // Delete session-course-user relation ships *only* for students.
  3678. $sql = "DELETE FROM $tbl_session_course_user
  3679. WHERE id_session = '$session_id' AND status <> 2";
  3680. Database::query($sql);
  3681. }
  3682. } else {
  3683. if ($debug) {
  3684. $logger->addError(
  3685. "Sessions - Session not found"
  3686. );
  3687. }
  3688. }
  3689. }
  3690. $session_counter++;
  3691. }
  3692. $sessionList[] = $session_id;
  3693. $users = explode('|', $enreg['Users']);
  3694. // Adding the relationship "Session - User" for students
  3695. $userList = array();
  3696. if (is_array($users)) {
  3697. foreach ($users as $user) {
  3698. $user_id = UserManager::get_user_id_from_username($user);
  3699. if ($user_id !== false) {
  3700. $userList[] = $user_id;
  3701. // Insert new users.
  3702. $sql = "INSERT IGNORE INTO $tbl_session_user SET
  3703. id_user = '$user_id',
  3704. id_session = '$session_id'";
  3705. Database::query($sql);
  3706. if ($debug) {
  3707. $logger->addInfo("Sessions - Adding User #$user_id ($user) to session #$session_id");
  3708. }
  3709. $user_counter++;
  3710. }
  3711. }
  3712. }
  3713. if ($deleteUsersNotInList) {
  3714. // Getting user in DB in order to compare to the new list.
  3715. $usersListInDatabase = self::get_users_by_session($session_id, 0);
  3716. if (!empty($usersListInDatabase)) {
  3717. if (empty($userList)) {
  3718. foreach ($usersListInDatabase as $userInfo) {
  3719. self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
  3720. }
  3721. } else {
  3722. foreach ($usersListInDatabase as $userInfo) {
  3723. if (!in_array($userInfo['user_id'], $userList)) {
  3724. self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
  3725. }
  3726. }
  3727. }
  3728. }
  3729. }
  3730. $courses = explode('|', $enreg['Courses']);
  3731. // See BT#6449
  3732. $onlyAddFirstCoachOrTeacher = false;
  3733. if ($sessionWithCoursesModifier) {
  3734. if (count($courses) >= 2) {
  3735. // Only first teacher in course session;
  3736. $onlyAddFirstCoachOrTeacher = true;
  3737. // Remove all teachers from course.
  3738. $removeAllTeachersFromCourse = false;
  3739. }
  3740. }
  3741. foreach ($courses as $course) {
  3742. $courseArray = bracketsToArray($course);
  3743. $course_code = $courseArray[0];
  3744. if (CourseManager::course_exists($course_code)) {
  3745. $courseInfo = api_get_course_info($course_code);
  3746. // Adding the course to a session.
  3747. $sql = "INSERT IGNORE INTO $tbl_session_course
  3748. SET course_code = '$course_code', id_session='$session_id'";
  3749. Database::query($sql);
  3750. SessionManager::installCourse($session_id, $courseInfo['real_id']);
  3751. if ($debug) {
  3752. $logger->addInfo("Sessions - Adding course '$course_code' to session #$session_id");
  3753. }
  3754. $course_counter++;
  3755. $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
  3756. $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
  3757. $course_users = explode(',', $course_users);
  3758. $course_coaches = explode(',', $course_coaches);
  3759. // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
  3760. $addTeachersToSession = true;
  3761. if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
  3762. $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
  3763. }
  3764. // If any user provided for a course, use the users array.
  3765. if (empty($course_users)) {
  3766. if (!empty($userList)) {
  3767. SessionManager::subscribe_users_to_session_course(
  3768. $userList,
  3769. $session_id,
  3770. $course_code
  3771. );
  3772. if ($debug) {
  3773. $msg = "Sessions - Adding student list ".implode(', #', $userList)." to course: '$course_code' and session #$session_id";
  3774. $logger->addInfo($msg);
  3775. }
  3776. }
  3777. }
  3778. // Adding coaches to session course user.
  3779. if (!empty($course_coaches)) {
  3780. $savedCoaches = array();
  3781. // only edit if add_teachers_to_sessions_courses is set.
  3782. if ($addTeachersToSession) {
  3783. if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
  3784. // Adding course teachers as course session teachers.
  3785. $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code(
  3786. $course_code
  3787. );
  3788. if (!empty($alreadyAddedTeachers)) {
  3789. $teachersToAdd = array();
  3790. foreach ($alreadyAddedTeachers as $user) {
  3791. $teachersToAdd[] = $user['username'];
  3792. }
  3793. $course_coaches = array_merge(
  3794. $course_coaches,
  3795. $teachersToAdd
  3796. );
  3797. }
  3798. }
  3799. foreach ($course_coaches as $course_coach) {
  3800. $coach_id = UserManager::get_user_id_from_username($course_coach);
  3801. if ($coach_id !== false) {
  3802. // Just insert new coaches
  3803. SessionManager::updateCoaches($session_id, $course_code, array($coach_id), false);
  3804. if ($debug) {
  3805. $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  3806. }
  3807. $savedCoaches[] = $coach_id;
  3808. } else {
  3809. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  3810. }
  3811. }
  3812. }
  3813. // Custom courses/session coaches
  3814. $teacherToAdd = null;
  3815. // Only one coach is added.
  3816. if ($onlyAddFirstCoachOrTeacher == true) {
  3817. foreach ($course_coaches as $course_coach) {
  3818. $coach_id = UserManager::get_user_id_from_username($course_coach);
  3819. if ($coach_id !== false) {
  3820. $teacherToAdd = $coach_id;
  3821. break;
  3822. }
  3823. }
  3824. // Un subscribe everyone that's not in the list.
  3825. $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
  3826. if (!empty($teacherList)) {
  3827. foreach ($teacherList as $teacher) {
  3828. if ($teacherToAdd != $teacher['user_id']) {
  3829. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  3830. WHERE
  3831. user_id = ".$teacher['user_id']." AND
  3832. course_code = '".$course_code."'
  3833. ";
  3834. $result = Database::query($sql);
  3835. $userCourseData = Database::fetch_array($result, 'ASSOC');
  3836. $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
  3837. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  3838. WHERE
  3839. user_id = ".$teacher['user_id']." AND
  3840. c_id = '".$courseInfo['real_id']."'
  3841. ";
  3842. $result = Database::query($sql);
  3843. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  3844. $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  3845. }
  3846. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  3847. WHERE
  3848. user_id = ".$teacher['user_id']." AND
  3849. c_id = '".$courseInfo['real_id']."'
  3850. ";
  3851. $result = Database::query($sql);
  3852. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  3853. $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  3854. }
  3855. CourseManager::unsubscribe_user(
  3856. $teacher['user_id'],
  3857. $course_code
  3858. );
  3859. }
  3860. }
  3861. }
  3862. if (!empty($teacherToAdd)) {
  3863. SessionManager::updateCoaches($session_id, $course_code, array($teacherToAdd), true);
  3864. $userCourseCategory = '';
  3865. if (isset($teacherBackupList[$teacherToAdd]) &&
  3866. isset($teacherBackupList[$teacherToAdd][$course_code])
  3867. ) {
  3868. $courseUserData = $teacherBackupList[$teacherToAdd][$course_code];
  3869. $userCourseCategory = $courseUserData['user_course_cat'];
  3870. }
  3871. CourseManager::subscribe_user(
  3872. $teacherToAdd,
  3873. $course_code,
  3874. COURSEMANAGER,
  3875. 0,
  3876. $userCourseCategory
  3877. );
  3878. if (isset($groupBackup['user'][$teacherToAdd]) &&
  3879. isset($groupBackup['user'][$teacherToAdd][$course_code]) &&
  3880. !empty($groupBackup['user'][$teacherToAdd][$course_code])
  3881. ) {
  3882. foreach ($groupBackup['user'][$teacherToAdd][$course_code] as $data) {
  3883. GroupManager::subscribe_users(
  3884. $teacherToAdd,
  3885. $data['group_id'],
  3886. $data['c_id']
  3887. );
  3888. }
  3889. }
  3890. if (isset($groupBackup['tutor'][$teacherToAdd]) &&
  3891. isset($groupBackup['tutor'][$teacherToAdd][$course_code]) &&
  3892. !empty($groupBackup['tutor'][$teacherToAdd][$course_code])
  3893. ) {
  3894. foreach ($groupBackup['tutor'][$teacherToAdd][$course_code] as $data) {
  3895. GroupManager::subscribe_tutors(
  3896. $teacherToAdd,
  3897. $data['group_id'],
  3898. $data['c_id']
  3899. );
  3900. }
  3901. }
  3902. }
  3903. }
  3904. // See BT#6449#note-195
  3905. // All coaches are added.
  3906. if ($removeAllTeachersFromCourse) {
  3907. $teacherToAdd = null;
  3908. foreach ($course_coaches as $course_coach) {
  3909. $coach_id = UserManager::get_user_id_from_username(
  3910. $course_coach
  3911. );
  3912. if ($coach_id !== false) {
  3913. $teacherToAdd[] = $coach_id;
  3914. }
  3915. }
  3916. if (!empty($teacherToAdd)) {
  3917. // Deleting all course teachers and adding the only coach as teacher.
  3918. $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
  3919. if (!empty($teacherList)) {
  3920. foreach ($teacherList as $teacher) {
  3921. if (!in_array($teacher['user_id'], $teacherToAdd)) {
  3922. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  3923. WHERE
  3924. user_id = ".$teacher['user_id']." AND
  3925. course_code = '".$course_code."'
  3926. ";
  3927. $result = Database::query($sql);
  3928. $userCourseData = Database::fetch_array($result, 'ASSOC');
  3929. $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
  3930. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  3931. WHERE
  3932. user_id = ".$teacher['user_id']." AND
  3933. c_id = '".$courseInfo['real_id']."'
  3934. ";
  3935. $result = Database::query($sql);
  3936. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  3937. $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  3938. }
  3939. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  3940. WHERE
  3941. user_id = ".$teacher['user_id']." AND
  3942. c_id = '".$courseInfo['real_id']."'
  3943. ";
  3944. $result = Database::query($sql);
  3945. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  3946. $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  3947. }
  3948. CourseManager::unsubscribe_user(
  3949. $teacher['user_id'],
  3950. $course_code
  3951. );
  3952. }
  3953. }
  3954. }
  3955. foreach ($teacherToAdd as $teacherId) {
  3956. $userCourseCategory = '';
  3957. if (isset($teacherBackupList[$teacherId]) &&
  3958. isset($teacherBackupList[$teacherId][$course_code])
  3959. ) {
  3960. $courseUserData = $teacherBackupList[$teacherId][$course_code];
  3961. $userCourseCategory = $courseUserData['user_course_cat'];
  3962. }
  3963. CourseManager::subscribe_user(
  3964. $teacherId,
  3965. $course_code,
  3966. COURSEMANAGER,
  3967. 0,
  3968. $userCourseCategory
  3969. );
  3970. if (isset($groupBackup['user'][$teacherId]) &&
  3971. isset($groupBackup['user'][$teacherId][$course_code]) &&
  3972. !empty($groupBackup['user'][$teacherId][$course_code])
  3973. ) {
  3974. foreach ($groupBackup['user'][$teacherId][$course_code] as $data) {
  3975. GroupManager::subscribe_users(
  3976. $teacherId,
  3977. $data['group_id'],
  3978. $data['c_id']
  3979. );
  3980. }
  3981. }
  3982. if (isset($groupBackup['tutor'][$teacherId]) &&
  3983. isset($groupBackup['tutor'][$teacherId][$course_code]) &&
  3984. !empty($groupBackup['tutor'][$teacherId][$course_code])
  3985. ) {
  3986. foreach ($groupBackup['tutor'][$teacherId][$course_code] as $data) {
  3987. GroupManager::subscribe_tutors(
  3988. $teacherId,
  3989. $data['group_id'],
  3990. $data['c_id']
  3991. );
  3992. }
  3993. }
  3994. }
  3995. }
  3996. }
  3997. // Continue default behaviour.
  3998. if ($onlyAddFirstCoachOrTeacher == false) {
  3999. // Checking one more time see BT#6449#note-149
  4000. $coaches = SessionManager::getCoachesByCourseSession($session_id, $course_code);
  4001. // Update coaches if only there's 1 course see BT#6449#note-189
  4002. if (empty($coaches) || count($courses) == 1) {
  4003. foreach ($course_coaches as $course_coach) {
  4004. $course_coach = trim($course_coach);
  4005. $coach_id = UserManager::get_user_id_from_username($course_coach);
  4006. if ($coach_id !== false) {
  4007. // Just insert new coaches
  4008. SessionManager::updateCoaches(
  4009. $session_id,
  4010. $course_code,
  4011. array($coach_id),
  4012. false
  4013. );
  4014. if ($debug) {
  4015. $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  4016. }
  4017. $savedCoaches[] = $coach_id;
  4018. } else {
  4019. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  4020. }
  4021. }
  4022. }
  4023. }
  4024. }
  4025. // Adding Students, updating relationship "Session - Course - User".
  4026. $course_users = array_filter($course_users);
  4027. if (!empty($course_users)) {
  4028. foreach ($course_users as $user) {
  4029. $user_id = UserManager::get_user_id_from_username($user);
  4030. if ($user_id !== false) {
  4031. SessionManager::subscribe_users_to_session_course(
  4032. array($user_id),
  4033. $session_id,
  4034. $course_code
  4035. );
  4036. if ($debug) {
  4037. $logger->addInfo("Sessions - Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
  4038. }
  4039. } else {
  4040. $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
  4041. }
  4042. }
  4043. }
  4044. $course_info = CourseManager::get_course_information($course_code);
  4045. $inserted_in_course[$course_code] = $course_info['title'];
  4046. }
  4047. }
  4048. $access_url_id = api_get_current_access_url_id();
  4049. UrlManager::add_session_to_url($session_id, $access_url_id);
  4050. $sql = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter' WHERE id = '$session_id'";
  4051. Database::query($sql);
  4052. }
  4053. }
  4054. return array(
  4055. 'error_message' => $error_message,
  4056. 'session_counter' => $session_counter,
  4057. 'session_list' => $sessionList
  4058. );
  4059. }
  4060. /**
  4061. * @param int $sessionId
  4062. * @param string $courseCode
  4063. * @return array
  4064. */
  4065. public static function getCoachesByCourseSession($sessionId, $courseCode)
  4066. {
  4067. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4068. $sessionId = intval($sessionId);
  4069. $courseCode = Database::escape_string($courseCode);
  4070. $sql = "SELECT id_user FROM $table
  4071. WHERE
  4072. id_session = '$sessionId' AND
  4073. course_code = '$courseCode' AND
  4074. status = 2";
  4075. $result = Database::query($sql);
  4076. $coaches = array();
  4077. if (Database::num_rows($result) > 0) {
  4078. while ($row = Database::fetch_row($result)) {
  4079. $coaches[] = $row[0];
  4080. }
  4081. }
  4082. return $coaches;
  4083. }
  4084. /**
  4085. * @param int $sessionId
  4086. * @param string $courseCode
  4087. * @return string
  4088. */
  4089. public static function getCoachesByCourseSessionToString(
  4090. $sessionId,
  4091. $courseCode
  4092. ) {
  4093. $coaches = self::getCoachesByCourseSession($sessionId, $courseCode);
  4094. $list = array();
  4095. if (!empty($coaches)) {
  4096. foreach ($coaches as $coachId) {
  4097. $userInfo = api_get_user_info($coachId);
  4098. $list[] = api_get_person_name(
  4099. $userInfo['firstname'],
  4100. $userInfo['lastname']
  4101. );
  4102. }
  4103. }
  4104. return array_to_string($list, CourseManager::USER_SEPARATOR);
  4105. }
  4106. /**
  4107. * Get all coaches added in the session - course relationship
  4108. * @param int $sessionId
  4109. * @return array
  4110. */
  4111. public static function getCoachesBySession($sessionId)
  4112. {
  4113. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4114. $sessionId = intval($sessionId);
  4115. $sql = "SELECT DISTINCT id_user
  4116. FROM $table
  4117. WHERE id_session = '$sessionId' AND status = 2";
  4118. $result = Database::query($sql);
  4119. $coaches = array();
  4120. if (Database::num_rows($result) > 0) {
  4121. while ($row = Database::fetch_array($result)) {
  4122. $coaches[] = $row['id_user'];
  4123. }
  4124. }
  4125. return $coaches;
  4126. }
  4127. /**
  4128. * @param int $userId
  4129. * @return array
  4130. */
  4131. public static function getAllCoursesFromAllSessionFromDrh($userId)
  4132. {
  4133. $sessions = SessionManager::get_sessions_followed_by_drh($userId);
  4134. $coursesFromSession = array();
  4135. if (!empty($sessions)) {
  4136. foreach ($sessions as $session) {
  4137. $courseList = SessionManager::get_course_list_by_session_id($session['id']);
  4138. foreach ($courseList as $course) {
  4139. $coursesFromSession[] = $course['code'];
  4140. }
  4141. }
  4142. }
  4143. return $coursesFromSession;
  4144. }
  4145. /**
  4146. * @param string $status
  4147. * @param int $userId
  4148. * @param bool $getCount
  4149. * @param int $from
  4150. * @param int $numberItems
  4151. * @param int $column
  4152. * @param string $direction
  4153. * @param string $keyword
  4154. * @param string $active
  4155. * @param string $lastConnectionDate
  4156. * @param array $sessionIdList
  4157. * @param array $studentIdList
  4158. * @param int $filterByStatus
  4159. * @return array|int
  4160. */
  4161. public static function getAllUsersFromCoursesFromAllSessionFromStatus(
  4162. $status,
  4163. $userId,
  4164. $getCount = false,
  4165. $from = null,
  4166. $numberItems = null,
  4167. $column = 1,
  4168. $direction = 'asc',
  4169. $keyword = null,
  4170. $active = null,
  4171. $lastConnectionDate = null,
  4172. $sessionIdList = array(),
  4173. $studentIdList = array(),
  4174. $filterByStatus = null
  4175. ) {
  4176. $filterByStatus = intval($filterByStatus);
  4177. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  4178. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  4179. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  4180. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4181. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4182. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4183. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  4184. $direction = in_array(strtolower($direction), array('asc', 'desc')) ? $direction : 'asc';
  4185. $column = Database::escape_string($column);
  4186. $userId = intval($userId);
  4187. $limitCondition = null;
  4188. if (isset($from) && isset($numberItems)) {
  4189. $from = intval($from);
  4190. $numberItems = intval($numberItems);
  4191. $limitCondition = "LIMIT $from, $numberItems";
  4192. }
  4193. $urlId = api_get_current_access_url_id();
  4194. $sessionConditions = null;
  4195. $courseConditions = null;
  4196. $userConditions = null;
  4197. if (isset($active)) {
  4198. $active = intval($active);
  4199. $userConditions .= " AND active = $active";
  4200. }
  4201. switch ($status) {
  4202. case 'drh':
  4203. // Classic DRH
  4204. if (empty($studentIdList)) {
  4205. $studentListSql = UserManager::get_users_followed_by_drh(
  4206. $userId,
  4207. $filterByStatus,
  4208. true,
  4209. false
  4210. );
  4211. $studentIdList = array_keys($studentListSql);
  4212. $studentListSql = "'".implode("','", $studentIdList)."'";
  4213. } else {
  4214. $studentIdList = array_map('intval', $studentIdList);
  4215. $studentListSql = "'".implode("','", $studentIdList)."'";
  4216. }
  4217. if (!empty($studentListSql)) {
  4218. $userConditions = " AND u.user_id IN (".$studentListSql.") ";
  4219. }
  4220. break;
  4221. case 'drh_all':
  4222. // Show all by DRH
  4223. if (empty($sessionIdList)) {
  4224. $sessionsListSql = SessionManager::get_sessions_followed_by_drh(
  4225. $userId,
  4226. null,
  4227. null,
  4228. false,
  4229. true,
  4230. true
  4231. );
  4232. } else {
  4233. $sessionIdList = array_map('intval', $sessionIdList);
  4234. $sessionsListSql = "'".implode("','", $sessionIdList)."'";
  4235. }
  4236. if (!empty($sessionsListSql)) {
  4237. $sessionConditions = " AND s.id IN (".$sessionsListSql.") ";
  4238. }
  4239. break;
  4240. case 'session_admin';
  4241. $sessionConditions = " AND s.id_coach = $userId ";
  4242. break;
  4243. case 'admin':
  4244. break;
  4245. case 'teacher':
  4246. $sessionConditions = " AND s.id_coach = $userId ";
  4247. break;
  4248. }
  4249. $select = "SELECT DISTINCT u.* ";
  4250. $masterSelect = "SELECT DISTINCT * FROM ";
  4251. if ($getCount) {
  4252. $select = "SELECT DISTINCT u.user_id ";
  4253. $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
  4254. }
  4255. if (!empty($filterByStatus)) {
  4256. $userConditions .= " AND u.status = ".$filterByStatus;
  4257. }
  4258. if (!empty($lastConnectionDate)) {
  4259. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  4260. $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
  4261. }
  4262. if (!empty($keyword)) {
  4263. $keyword = Database::escape_string($keyword);
  4264. $userConditions .= " AND (
  4265. u.username LIKE '%$keyword%' OR
  4266. u.firstname LIKE '%$keyword%' OR
  4267. u.lastname LIKE '%$keyword%' OR
  4268. u.official_code LIKE '%$keyword%' OR
  4269. u.email LIKE '%$keyword%'
  4270. )";
  4271. }
  4272. $where = " WHERE
  4273. access_url_id = $urlId
  4274. $userConditions
  4275. ";
  4276. $sql = "$masterSelect (
  4277. ($select
  4278. FROM $tbl_session s
  4279. INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.id_session)
  4280. INNER JOIN $tbl_user u ON (u.user_id = su.id_user AND s.id = id_session)
  4281. INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
  4282. $where
  4283. $sessionConditions
  4284. )
  4285. UNION (
  4286. $select
  4287. FROM $tbl_course c
  4288. INNER JOIN $tbl_course_user cu ON (cu.course_code = c.code)
  4289. INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
  4290. INNER JOIN $tbl_course_rel_access_url url ON (url.course_code = c.code)
  4291. $where
  4292. $courseConditions
  4293. )
  4294. ) as t1
  4295. ";
  4296. if ($getCount) {
  4297. $result = Database::query($sql);
  4298. $count = 0;
  4299. if (Database::num_rows($result)) {
  4300. $rows = Database::fetch_array($result);
  4301. $count = $rows['count'];
  4302. }
  4303. return $count;
  4304. }
  4305. if (!empty($column) && !empty($direction)) {
  4306. $column = str_replace('u.', '', $column);
  4307. $sql .= " ORDER BY $column $direction ";
  4308. }
  4309. $sql .= $limitCondition;
  4310. $result = Database::query($sql);
  4311. $result = Database::store_result($result);
  4312. return $result ;
  4313. }
  4314. /**
  4315. * @param int $sessionId
  4316. * @param string $courseCode
  4317. * @param array $coachList
  4318. * @param bool $deleteCoachesNotInList
  4319. */
  4320. public static function updateCoaches(
  4321. $sessionId,
  4322. $courseCode,
  4323. $coachList,
  4324. $deleteCoachesNotInList = false
  4325. ) {
  4326. $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseCode);
  4327. if (!empty($coachList)) {
  4328. foreach ($coachList as $userId) {
  4329. self::set_coach_to_course_session($userId, $sessionId, $courseCode);
  4330. }
  4331. }
  4332. if ($deleteCoachesNotInList) {
  4333. if (!empty($coachList)) {
  4334. $coachesToDelete = array_diff($currentCoaches, $coachList);
  4335. } else {
  4336. $coachesToDelete = $currentCoaches;
  4337. }
  4338. if (!empty($coachesToDelete)) {
  4339. foreach ($coachesToDelete as $userId) {
  4340. self::set_coach_to_course_session(
  4341. $userId,
  4342. $sessionId,
  4343. $courseCode,
  4344. true
  4345. );
  4346. }
  4347. }
  4348. }
  4349. }
  4350. /**
  4351. * @param array $sessions
  4352. * @param array $sessionsDestination
  4353. * @return string
  4354. */
  4355. public static function copyStudentsFromSession($sessions, $sessionsDestination)
  4356. {
  4357. $messages = array();
  4358. if (!empty($sessions)) {
  4359. foreach ($sessions as $sessionId) {
  4360. $sessionInfo = self::fetch($sessionId);
  4361. $userList = self::get_users_by_session($sessionId, 0);
  4362. if (!empty($userList)) {
  4363. $newUserList = array();
  4364. $userToString = null;
  4365. foreach ($userList as $userInfo) {
  4366. $newUserList[] = $userInfo['user_id'];
  4367. $userToString .= $userInfo['firstname'] . ' ' . $userInfo['lastname'] . '<br />';
  4368. }
  4369. if (!empty($sessionsDestination)) {
  4370. foreach ($sessionsDestination as $sessionDestinationId) {
  4371. $sessionDestinationInfo = self::fetch($sessionDestinationId);
  4372. $messages[] = Display::return_message(
  4373. sprintf(get_lang('AddingStudentsFromSessionXToSessionY'), $sessionInfo['name'], $sessionDestinationInfo['name']), 'info', false
  4374. );
  4375. if ($sessionId == $sessionDestinationId) {
  4376. $messages[] = Display::return_message(sprintf(get_lang('SessionXSkipped'), $sessionDestinationId), 'warning', false);
  4377. continue;
  4378. }
  4379. $messages[] = Display::return_message(get_lang('StudentList') . '<br />' . $userToString, 'info', false);
  4380. SessionManager::suscribe_users_to_session($sessionDestinationId, $newUserList, SESSION_VISIBLE_READ_ONLY, false);
  4381. }
  4382. } else {
  4383. $messages[] = Display::return_message(get_lang('NoDestinationSessionProvided'), 'warning');
  4384. }
  4385. } else {
  4386. $messages[] = Display::return_message(get_lang('NoStudentsFoundForSession') . ' #' . $sessionInfo['name'], 'warning');
  4387. }
  4388. }
  4389. } else {
  4390. $messages[] = Display::return_message(get_lang('NoData'), 'warning');
  4391. }
  4392. return $messages;
  4393. }
  4394. /**
  4395. * Assign coaches of a session(s) as teachers to a given course (or courses)
  4396. * @param array A list of session IDs
  4397. * @param array A list of course IDs
  4398. * @return string
  4399. */
  4400. public static function copyCoachesFromSessionToCourse($sessions, $courses)
  4401. {
  4402. $coachesPerSession = array();
  4403. foreach ($sessions as $sessionId) {
  4404. $coaches = self::getCoachesBySession($sessionId);
  4405. $coachesPerSession[$sessionId] = $coaches;
  4406. }
  4407. $result = array();
  4408. if (!empty($courses)) {
  4409. foreach ($courses as $courseId) {
  4410. $courseInfo = api_get_course_info_by_id($courseId);
  4411. foreach ($coachesPerSession as $sessionId => $coachList) {
  4412. CourseManager::updateTeachers(
  4413. $courseInfo['code'], $coachList, false, false, false
  4414. );
  4415. $result[$courseInfo['code']][$sessionId] = $coachList;
  4416. }
  4417. }
  4418. }
  4419. $sessionUrl = api_get_path(WEB_CODE_PATH) . 'admin/resume_session.php?id_session=';
  4420. $htmlResult = null;
  4421. if (!empty($result)) {
  4422. foreach ($result as $courseCode => $data) {
  4423. $url = api_get_course_url($courseCode);
  4424. $htmlResult .= sprintf(get_lang('CoachesSubscribedAsATeacherInCourseX'), Display::url($courseCode, $url, array('target' => '_blank')));
  4425. foreach ($data as $sessionId => $coachList) {
  4426. $sessionInfo = self::fetch($sessionId);
  4427. $htmlResult .= '<br />';
  4428. $htmlResult .= Display::url(
  4429. get_lang('Session') . ': ' . $sessionInfo['name'] . ' <br />', $sessionUrl . $sessionId, array('target' => '_blank')
  4430. );
  4431. $teacherList = array();
  4432. foreach ($coachList as $coachId) {
  4433. $userInfo = api_get_user_info($coachId);
  4434. $teacherList[] = $userInfo['complete_name'];
  4435. }
  4436. if (!empty($teacherList)) {
  4437. $htmlResult .= implode(', ', $teacherList);
  4438. } else {
  4439. $htmlResult .= get_lang('NothingToAdd');
  4440. }
  4441. }
  4442. $htmlResult .= '<br />';
  4443. }
  4444. $htmlResult = Display::return_message($htmlResult, 'normal', false);
  4445. }
  4446. return $htmlResult;
  4447. }
  4448. /**
  4449. * @param string $keyword
  4450. * @param string $active
  4451. * @param string $lastConnectionDate
  4452. * @param array $sessionIdList
  4453. * @param array $studentIdList
  4454. * @param int $userStatus STUDENT|COURSEMANAGER constants
  4455. *
  4456. * @return array|int
  4457. */
  4458. public static function getCountUserTracking(
  4459. $keyword = null,
  4460. $active = null,
  4461. $lastConnectionDate = null,
  4462. $sessionIdList = array(),
  4463. $studentIdList = array(),
  4464. $filterUserStatus = null
  4465. ) {
  4466. $userId = api_get_user_id();
  4467. $drhLoaded = false;
  4468. if (api_is_drh()) {
  4469. if (api_drh_can_access_all_session_content()) {
  4470. $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
  4471. 'drh_all',
  4472. $userId,
  4473. true,
  4474. null,
  4475. null,
  4476. null,
  4477. null,
  4478. $keyword,
  4479. $active,
  4480. $lastConnectionDate,
  4481. $sessionIdList,
  4482. $studentIdList,
  4483. $filterUserStatus
  4484. );
  4485. $drhLoaded = true;
  4486. }
  4487. }
  4488. if ($drhLoaded == false) {
  4489. $count = UserManager::getUsersFollowedByUser(
  4490. $userId,
  4491. $filterUserStatus,
  4492. false,
  4493. false,
  4494. true,
  4495. null,
  4496. null,
  4497. null,
  4498. null,
  4499. $active,
  4500. $lastConnectionDate,
  4501. COURSEMANAGER,
  4502. $keyword
  4503. );
  4504. }
  4505. return $count;
  4506. }
  4507. /**
  4508. * Get teachers followed by a user
  4509. * @param int $userId
  4510. * @param int $active
  4511. * @param string $lastConnectionDate
  4512. * @param bool $getCount
  4513. * @param array $sessionIdList
  4514. * @return array|int
  4515. */
  4516. public static function getTeacherTracking(
  4517. $userId,
  4518. $active = 1,
  4519. $lastConnectionDate = null,
  4520. $getCount = false,
  4521. $sessionIdList = array()
  4522. ) {
  4523. $teacherResult = array();
  4524. if (api_is_drh() || api_is_platform_admin()) {
  4525. // Followed teachers by drh
  4526. if (api_drh_can_access_all_session_content()) {
  4527. if (empty($sessionIdList)) {
  4528. $sessions = SessionManager::get_sessions_followed_by_drh($userId);
  4529. $sessionIdList = array();
  4530. foreach ($sessions as $session) {
  4531. $sessionIdList[] = $session['id'];
  4532. }
  4533. }
  4534. $sessionIdList = array_map('intval', $sessionIdList);
  4535. $sessionToString = implode("', '", $sessionIdList);
  4536. $course = Database::get_main_table(TABLE_MAIN_COURSE);
  4537. $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  4538. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4539. // Select the teachers.
  4540. $sql = "SELECT DISTINCT(cu.user_id) FROM $course c
  4541. INNER JOIN $sessionCourse src ON c.code = src.course_code
  4542. INNER JOIN $courseUser cu ON (cu.course_code = c.code)
  4543. WHERE src.id_session IN ('$sessionToString') AND cu.status = 1";
  4544. $result = Database::query($sql);
  4545. $teacherListId = array();
  4546. while($row = Database::fetch_array($result, 'ASSOC')) {
  4547. $teacherListId[$row['user_id']] = $row['user_id'];
  4548. }
  4549. } else {
  4550. $teacherResult = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
  4551. $teacherListId = array();
  4552. foreach ($teacherResult as $userInfo) {
  4553. $teacherListId[] = $userInfo['user_id'];
  4554. }
  4555. }
  4556. }
  4557. if (!empty($teacherListId)) {
  4558. $tableUser = Database::get_main_table(TABLE_MAIN_USER);
  4559. $select = "SELECT DISTINCT u.* ";
  4560. if ($getCount) {
  4561. $select = "SELECT count(DISTINCT(u.user_id)) as count";
  4562. }
  4563. $sql = "$select FROM $tableUser u";
  4564. if (!empty($lastConnectionDate)) {
  4565. $tableLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  4566. //$sql .= " INNER JOIN $tableLogin l ON (l.login_user_id = u.user_id) ";
  4567. }
  4568. $active = intval($active);
  4569. $teacherListId = implode("','", $teacherListId);
  4570. $where = " WHERE u.active = $active AND u.user_id IN ('$teacherListId') ";
  4571. if (!empty($lastConnectionDate)) {
  4572. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  4573. //$where .= " AND l.login_date <= '$lastConnectionDate' ";
  4574. }
  4575. $sql .= $where;
  4576. $result = Database::query($sql);
  4577. if (Database::num_rows($result)) {
  4578. if ($getCount) {
  4579. $row = Database::fetch_array($result);
  4580. return $row['count'];
  4581. } else {
  4582. return Database::store_result($result, 'ASSOC');
  4583. }
  4584. }
  4585. }
  4586. return 0;
  4587. }
  4588. /**
  4589. * Get the list of course tools that have to be dealt with in case of
  4590. * registering any course to a session
  4591. * @return array The list of tools to be dealt with (literal names)
  4592. */
  4593. public static function getCourseToolToBeManaged()
  4594. {
  4595. return array(
  4596. 'courseDescription',
  4597. 'courseIntroduction'
  4598. );
  4599. }
  4600. /**
  4601. * Calls the methods bound to each tool when a course is registered into a session
  4602. * @param int $sessionId
  4603. * @param int $courseId
  4604. * @return void
  4605. */
  4606. public static function installCourse($sessionId, $courseId)
  4607. {
  4608. return true;
  4609. $toolList = self::getCourseToolToBeManaged();
  4610. foreach ($toolList as $tool) {
  4611. $method = 'add' . $tool;
  4612. if (method_exists(get_class(), $method)) {
  4613. self::$method($sessionId, $courseId);
  4614. }
  4615. }
  4616. }
  4617. /**
  4618. * Calls the methods bound to each tool when a course is unregistered from
  4619. * a session
  4620. * @param int $sessionId
  4621. * @param int $courseId
  4622. */
  4623. public static function unInstallCourse($sessionId, $courseId)
  4624. {
  4625. return true;
  4626. $toolList = self::getCourseToolToBeManaged();
  4627. foreach ($toolList as $tool) {
  4628. $method = 'remove' . $tool;
  4629. if (method_exists(get_class(), $method)) {
  4630. self::$method($sessionId, $courseId);
  4631. }
  4632. }
  4633. }
  4634. /**
  4635. * @param int $sessionId
  4636. * @param int $courseId
  4637. */
  4638. public static function addCourseIntroduction($sessionId, $courseId)
  4639. {
  4640. // @todo create a tool intro lib
  4641. $sessionId = intval($sessionId);
  4642. $courseId = intval($courseId);
  4643. $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
  4644. $sql = "SELECT * FROM $TBL_INTRODUCTION WHERE c_id = $courseId";
  4645. $result = Database::query($sql);
  4646. $result = Database::store_result($result, 'ASSOC');
  4647. if (!empty($result)) {
  4648. foreach ($result as $result) {
  4649. // @todo check if relation exits.
  4650. $result['session_id'] = $sessionId;
  4651. Database::insert($TBL_INTRODUCTION, $result);
  4652. }
  4653. }
  4654. }
  4655. /**
  4656. * @param int $sessionId
  4657. * @param int $courseId
  4658. */
  4659. public static function removeCourseIntroduction($sessionId, $courseId)
  4660. {
  4661. $sessionId = intval($sessionId);
  4662. $courseId = intval($courseId);
  4663. $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
  4664. $sql = "DELETE FROM $TBL_INTRODUCTION WHERE c_id = $courseId AND session_id = $sessionId";
  4665. Database::query($sql);
  4666. }
  4667. /**
  4668. * @param int $sessionId
  4669. * @param int $courseId
  4670. */
  4671. public static function addCourseDescription($sessionId, $courseId)
  4672. {
  4673. /* $description = new CourseDescription();
  4674. $descriptions = $description->get_descriptions($courseId);
  4675. foreach ($descriptions as $description) {
  4676. } */
  4677. }
  4678. /**
  4679. * @param int $sessionId
  4680. * @param int $courseId
  4681. */
  4682. public static function removeCourseDescription($sessionId, $courseId)
  4683. {
  4684. }
  4685. /**
  4686. * @param array $list format see self::importSessionDrhCSV()
  4687. * @param bool $sendEmail
  4688. * @param bool $removeOldRelationShips
  4689. * @return string
  4690. */
  4691. public static function subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips)
  4692. {
  4693. if (!empty($userSessionList)) {
  4694. foreach ($userSessionList as $userId => $data) {
  4695. $sessionList = array();
  4696. foreach ($data['session_list'] as $sessionInfo) {
  4697. $sessionList[] = $sessionInfo['session_id'];
  4698. }
  4699. $userInfo = $data['user_info'];
  4700. self::suscribe_sessions_to_hr_manager(
  4701. $userInfo,
  4702. $sessionList,
  4703. $sendEmail,
  4704. $removeOldRelationShips
  4705. );
  4706. }
  4707. }
  4708. }
  4709. /**
  4710. * @param array $userSessionList format see self::importSessionDrhCSV()
  4711. */
  4712. public static function checkSubscribeDrhToSessionList($userSessionList)
  4713. {
  4714. $message = null;
  4715. if (!empty($userSessionList)) {
  4716. if (!empty($userSessionList)) {
  4717. foreach ($userSessionList as $userId => $data) {
  4718. $userInfo = $data['user_info'];
  4719. $sessionListSubscribed = self::get_sessions_followed_by_drh($userId);
  4720. if (!empty($sessionListSubscribed)) {
  4721. $sessionListSubscribed = array_keys($sessionListSubscribed);
  4722. }
  4723. $sessionList = array();
  4724. if (!empty($data['session_list'])) {
  4725. foreach ($data['session_list'] as $sessionInfo) {
  4726. if (in_array($sessionInfo['session_id'], $sessionListSubscribed)) {
  4727. $sessionList[] = $sessionInfo['session_info']['name'];
  4728. }
  4729. }
  4730. }
  4731. $message .= '<strong>' . get_lang('User') . '</strong> ' . $userInfo['complete_name'] . ' <br />';
  4732. if (!in_array($userInfo['status'], array(DRH)) && !api_is_platform_admin_by_id($userInfo['user_id'])) {
  4733. $message .= get_lang('UserMustHaveTheDrhRole') . '<br />';
  4734. continue;
  4735. }
  4736. if (!empty($sessionList)) {
  4737. $message .= '<strong>' . get_lang('Sessions') . ':</strong> <br />';
  4738. $message .= implode(', ', $sessionList) . '<br /><br />';
  4739. } else {
  4740. $message .= get_lang('NoSessionProvided') . ' <br /><br />';
  4741. }
  4742. }
  4743. }
  4744. }
  4745. return $message;
  4746. }
  4747. /**
  4748. * @param string $file
  4749. * @param bool $sendEmail
  4750. * @param bool $removeOldRelationShips
  4751. */
  4752. public static function importSessionDrhCSV($file, $sendEmail, $removeOldRelationShips)
  4753. {
  4754. $list = Import::csv_reader($file);
  4755. if (!empty($list)) {
  4756. $userSessionList = array();
  4757. foreach ($list as $data) {
  4758. $userInfo = api_get_user_info_from_username($data['Username']);
  4759. $sessionInfo = self::get_session_by_name($data['SessionName']);
  4760. if (!empty($userInfo) && !empty($sessionInfo)) {
  4761. $userSessionList[$userInfo['user_id']]['session_list'][] = array(
  4762. 'session_id' => $sessionInfo['id'],
  4763. 'session_info' => $sessionInfo
  4764. );
  4765. $userSessionList[$userInfo['user_id']]['user_info'] = $userInfo;
  4766. }
  4767. }
  4768. self::subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips);
  4769. return self::checkSubscribeDrhToSessionList($userSessionList);
  4770. }
  4771. }
  4772. /**
  4773. * Courses re-ordering in resume_session.php flag see BT#8316
  4774. */
  4775. public static function orderCourseIsEnabled()
  4776. {
  4777. global $_configuration;
  4778. if (isset($_configuration['session_course_ordering']) &&
  4779. $_configuration['session_course_ordering']
  4780. ) {
  4781. return true;
  4782. }
  4783. return false;
  4784. }
  4785. /**
  4786. * @param string $direction (up/down)
  4787. * @param int $sessionId
  4788. * @param string $courseCode
  4789. * @return bool
  4790. */
  4791. public static function move($direction, $sessionId, $courseCode)
  4792. {
  4793. if (!self::orderCourseIsEnabled()) {
  4794. return false;
  4795. }
  4796. $sessionId = intval($sessionId);
  4797. $courseCode = Database::escape_string($courseCode);
  4798. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  4799. $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
  4800. $position = array();
  4801. $count = 0;
  4802. foreach ($courseList as $course) {
  4803. if ($course['position'] == '') {
  4804. $course['position'] = $count;
  4805. }
  4806. $position[$course['code']] = $course['position'];
  4807. // Saving current order.
  4808. $sql = "UPDATE $table SET position = $count
  4809. WHERE id_session = $sessionId AND course_code = '".$course['code']."'";
  4810. Database::query($sql);
  4811. $count++;
  4812. }
  4813. // Loading new positions.
  4814. $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
  4815. $found = false;
  4816. switch ($direction) {
  4817. case 'up':
  4818. $courseList = array_reverse($courseList);
  4819. break;
  4820. case 'down':
  4821. break;
  4822. }
  4823. foreach ($courseList as $course) {
  4824. if ($found) {
  4825. $nextId = $course['code'];
  4826. $nextOrder = $course['position'];
  4827. break;
  4828. }
  4829. if ($courseCode == $course['code']) {
  4830. $thisCourseCode = $course['code'];
  4831. $thisOrder = $course['position'];
  4832. $found = true;
  4833. }
  4834. }
  4835. $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."'
  4836. WHERE id_session = $sessionId AND course_code = '".$thisCourseCode."'";
  4837. $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."'
  4838. WHERE id_session = $sessionId AND course_code = '".$nextId."'";
  4839. Database::query($sql1);
  4840. Database::query($sql2);
  4841. return true;
  4842. }
  4843. /**
  4844. * @param int $sessionId
  4845. * @param string $courseCode
  4846. * @return bool
  4847. */
  4848. public static function moveUp($sessionId, $courseCode)
  4849. {
  4850. return self::move('up', $sessionId, $courseCode);
  4851. }
  4852. /**
  4853. * @param int $sessionId
  4854. * @param string $courseCode
  4855. * @return bool
  4856. */
  4857. public static function moveDown($sessionId, $courseCode)
  4858. {
  4859. return self::move('down', $sessionId, $courseCode);
  4860. }
  4861. /**
  4862. * Use the session duration to allow/block user access see BT#8317
  4863. * Needs these DB changes
  4864. * ALTER TABLE session ADD COLUMN duration int;
  4865. * ALTER TABLE session_rel_user ADD COLUMN duration int;
  4866. */
  4867. public static function durationPerUserIsEnabled()
  4868. {
  4869. global $_configuration;
  4870. if (isset($_configuration['session_duration_feature']) &&
  4871. $_configuration['session_duration_feature']
  4872. ) {
  4873. return true;
  4874. }
  4875. return false;
  4876. }
  4877. /**
  4878. * Returns the number of days the student has left in a session when using
  4879. * sessions durations
  4880. * @param int $userId
  4881. * @param int $sessionId
  4882. * @param int $duration in days
  4883. * @return int
  4884. */
  4885. public static function getDayLeftInSession($sessionId, $userId, $duration)
  4886. {
  4887. // Get an array with the details of the first access of the student to
  4888. // this session
  4889. $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
  4890. $sessionId,
  4891. $userId
  4892. );
  4893. $currentTime = time();
  4894. // If no previous access, return false
  4895. if (count($courseAccess) == 0) {
  4896. return false;
  4897. }
  4898. $firstAccess = api_strtotime($courseAccess['login_course_date'], 'UTC');
  4899. $endDateInSeconds = $firstAccess + $duration*24*60*60;
  4900. $leftDays = round(($endDateInSeconds- $currentTime) / 60 / 60 / 24);
  4901. return $leftDays;
  4902. }
  4903. /**
  4904. * @param int $duration
  4905. * @param int $userId
  4906. * @param int $sessionId
  4907. */
  4908. public static function editUserSessionDuration($duration, $userId, $sessionId)
  4909. {
  4910. $duration = intval($duration);
  4911. $userId = intval($userId);
  4912. $sessionId = intval($sessionId);
  4913. if (empty($userId) || empty($sessionId)) {
  4914. return false;
  4915. }
  4916. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  4917. $parameters = array('duration' => $duration);
  4918. $where = array('id_session = ? AND id_user = ? ' => array($sessionId, $userId));
  4919. Database::update($table, $parameters, $where);
  4920. }
  4921. /**
  4922. * Gets one row from the session_rel_user table
  4923. * @param int The user ID
  4924. * @param int The session ID
  4925. * @return array
  4926. */
  4927. public static function getUserSession($userId, $sessionId)
  4928. {
  4929. $userId = intval($userId);
  4930. $sessionId = intval($sessionId);
  4931. if (empty($userId) || empty($sessionId)) {
  4932. return false;
  4933. }
  4934. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  4935. $sql = "SELECT * FROM $table WHERE id_session =$sessionId AND id_user = $userId";
  4936. $result = Database::query($sql);
  4937. $values = array();
  4938. if (Database::num_rows($result)) {
  4939. $values = Database::fetch_array($result, 'ASSOC');
  4940. }
  4941. return $values;
  4942. }
  4943. /**
  4944. * Check if user is subscribed inside a session as student
  4945. * @param int $sessionId The session id
  4946. * @param int $userId The user id
  4947. * @return boolean Whether is subscribed
  4948. */
  4949. public static function isUserSusbcribedAsStudent($sessionId, $userId)
  4950. {
  4951. $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  4952. $sessionId = intval($sessionId);
  4953. $userId = intval($userId);
  4954. $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
  4955. WHERE id_session = $sessionId AND id_user = $userId AND relation_type = 0";
  4956. $result = Database::fetch_assoc(Database::query($sql));
  4957. if (!empty($result) && $result['qty'] > 0) {
  4958. return true;
  4959. }
  4960. return false;
  4961. }
  4962. /**
  4963. * Get the formatted date of a session by its start and end date
  4964. * @param array $sessionInfo The session information containing the start and end date
  4965. * @return string The formatted date
  4966. */
  4967. public static function getSessionFormattedDate($sessionInfo)
  4968. {
  4969. if ($sessionInfo['date_start'] == '0000-00-00' && $sessionInfo['date_end'] == '0000-00-00') {
  4970. return get_lang('NoTimeLimits');
  4971. } else {
  4972. if ($sessionInfo['date_start'] != '0000-00-00') {
  4973. $startDate = get_lang('From') . ' ' . api_format_date($sessionInfo['date_start'], DATE_FORMAT_LONG_NO_DAY);
  4974. } else {
  4975. $startDate = '';
  4976. }
  4977. if ($sessionInfo['date_end'] == '0000-00-00') {
  4978. $endDate = '';
  4979. } else {
  4980. $endDate = get_lang('Until') . ' ' . api_format_date($sessionInfo['date_end'], DATE_FORMAT_LONG_NO_DAY);
  4981. }
  4982. return "$startDate $endDate";
  4983. }
  4984. }
  4985. /**
  4986. * Get the session coached by a user (general coach and course-session coach)
  4987. * @param int $coachId The coach id
  4988. * @param boolean $checkSessionRelUserVisibility Check the session visibility
  4989. * @return array The session list
  4990. */
  4991. public static function getSessionsCoachedByUser($coachId, $checkSessionRelUserVisibility = false)
  4992. {
  4993. // Get all sessions where $coachId is the general coach
  4994. $sessions = self::get_sessions_by_general_coach($coachId);
  4995. // Get all sessions where $coachId is the course - session coach
  4996. $courseSessionList = self::getCoursesListByCourseCoach($coachId);
  4997. $sessionsByCoach = array();
  4998. if (!empty($courseSessionList)) {
  4999. foreach ($courseSessionList as $courseSession) {
  5000. $sessionsByCoach[$courseSession['id_session']] = api_get_session_info($courseSession['id_session']);
  5001. }
  5002. }
  5003. if (!empty($sessionsByCoach)) {
  5004. $sessions = array_merge($sessions, $sessionsByCoach);
  5005. }
  5006. // Remove repeated sessions
  5007. if (!empty($sessions)) {
  5008. $cleanSessions = array();
  5009. foreach ($sessions as $session) {
  5010. $cleanSessions[$session['id']] = $session;
  5011. }
  5012. $sessions = $cleanSessions;
  5013. }
  5014. if ($checkSessionRelUserVisibility) {
  5015. if (!empty($sessions)) {
  5016. $newSessions = array();
  5017. foreach ($sessions as $session) {
  5018. $visibility = api_get_session_visibility($session['id']);
  5019. if ($visibility == SESSION_INVISIBLE) {
  5020. continue;
  5021. }
  5022. $newSessions[] = $session;
  5023. }
  5024. $sessions = $newSessions;
  5025. }
  5026. }
  5027. return $sessions;
  5028. }
  5029. /**
  5030. * Check if the course belongs to the session
  5031. * @param int $sessionId The session id
  5032. * @param string $courseCode The course code
  5033. *
  5034. * @return bool
  5035. */
  5036. public static function sessionHasCourse($sessionId, $courseCode)
  5037. {
  5038. $sessionId = intval($sessionId);
  5039. $courseCode = Database::escape_string($courseCode);
  5040. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  5041. $sessionRelCourseTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  5042. $sql = "SELECT COUNT(1) AS qty
  5043. FROM $courseTable c
  5044. INNER JOIN $sessionRelCourseTable src
  5045. ON c.code = src.course_code
  5046. WHERE src.id_session = $sessionId
  5047. AND c.code = '$courseCode' ";
  5048. $result = Database::query($sql);
  5049. if ($result !== false) {
  5050. $data = Database::fetch_assoc($result);
  5051. if ($data['qty'] > 0) {
  5052. return true;
  5053. }
  5054. }
  5055. return false;
  5056. }
  5057. /**
  5058. * Get the list of course coaches
  5059. * @return array The list
  5060. */
  5061. public static function getAllCourseCoaches()
  5062. {
  5063. $coaches = array();
  5064. $scuTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5065. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  5066. $idResult = Database::select('DISTINCT id_user', $scuTable, array(
  5067. 'where' => array(
  5068. 'status = ?' => 2
  5069. )
  5070. ));
  5071. if ($idResult != false) {
  5072. foreach ($idResult as $idData) {
  5073. $userResult = Database::select('user_id, lastname, firstname, username', $userTable, array(
  5074. 'where' => array(
  5075. 'user_id = ?' => $idData['id_user']
  5076. )
  5077. ), 'first');
  5078. if ($userResult != false) {
  5079. $coaches[] = array(
  5080. 'id' => $userResult['user_id'],
  5081. 'lastname' => $userResult['lastname'],
  5082. 'firstname' => $userResult['firstname'],
  5083. 'username' => $userResult['username'],
  5084. 'completeName' => api_get_person_name(
  5085. $userResult['firstname'],
  5086. $userResult['lastname']
  5087. ),
  5088. );
  5089. }
  5090. }
  5091. }
  5092. return $coaches;
  5093. }
  5094. /**
  5095. * Calculate the total user time in the platform
  5096. * @param int $userId The user id
  5097. * @param string $from Optional. From date
  5098. * @param string $until Optional. Until date
  5099. * @return string The time (hh:mm:ss)
  5100. */
  5101. public static function getTotalUserTimeInPlatform($userId, $from = '', $until = '')
  5102. {
  5103. $userId = intval($userId);
  5104. $trackLoginTable = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  5105. $whereConditions = array(
  5106. 'login_user_id = ? ' => $userId
  5107. );
  5108. if (!empty($from) && !empty($until)) {
  5109. $whereConditions["AND (login_date >= '?' "] = $from;
  5110. $whereConditions["AND logout_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
  5111. }
  5112. $trackResult = Database::select(
  5113. 'SEC_TO_TIME(SUM(UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date))) as total_time',
  5114. $trackLoginTable,
  5115. array(
  5116. 'where' => $whereConditions
  5117. ), 'first'
  5118. );
  5119. if ($trackResult != false) {
  5120. return $trackResult['total_time'] ? $trackResult['total_time'] : '00:00:00';
  5121. }
  5122. return '00:00:00';
  5123. }
  5124. /**
  5125. * Get the courses list by a course coach
  5126. * @param int $coachId The coach id
  5127. * @return array
  5128. */
  5129. public static function getCoursesListByCourseCoach($coachId)
  5130. {
  5131. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5132. return Database::select('*', $table, array(
  5133. 'where' => array(
  5134. 'id_user = ? AND ' => $coachId,
  5135. 'status = ?' => 2
  5136. )
  5137. ));
  5138. }
  5139. /**
  5140. * Get the count of user courses in session
  5141. * @param int $sessionId The session id
  5142. * @return array
  5143. */
  5144. public static function getTotalUserCoursesInSession($sessionId)
  5145. {
  5146. $sql = "SELECT COUNT(1) as count, u.user_id, scu.status status_in_session, u.status user_status
  5147. FROM session_rel_course_rel_user scu
  5148. INNER JOIN user u ON scu.id_user = u.user_id
  5149. WHERE scu.id_session = " . intval($sessionId) ."
  5150. GROUP BY u.user_id";
  5151. $result = Database::query($sql);
  5152. $list = array();
  5153. while ($data = Database::fetch_assoc($result)) {
  5154. $list[] = $data;
  5155. }
  5156. return $list;
  5157. }
  5158. /**
  5159. * Return an associative array 'id_course' => [id_session1, id_session2...]
  5160. * where course id_course is in sessions id_session1, id_session2
  5161. * for course where user is coach
  5162. * i.e. coach for the course or
  5163. * main coach for a session the course is in
  5164. * for a session category (or woth no session category if empty)
  5165. *
  5166. * @param $userId
  5167. *
  5168. * @return array
  5169. */
  5170. public static function getSessionCourseForUser($userId)
  5171. {
  5172. // list of COURSES where user is COURSE session coach
  5173. $listCourseCourseCoachSession = self::getCoursesForCourseSessionCoach($userId);
  5174. // list of courses where user is MAIN session coach
  5175. $listCourseMainCoachSession = self::getCoursesForMainSessionCoach($userId);
  5176. // merge these 2 array
  5177. $listResCourseSession = $listCourseCourseCoachSession;
  5178. foreach ($listCourseMainCoachSession as $courseId2 => $listSessionId2) {
  5179. if (isset($listResCourseSession[$courseId2])) {
  5180. // if sessionId array exists for this course
  5181. // same courseId, merge the list of session
  5182. foreach ($listCourseMainCoachSession[$courseId2] as $i => $sessionId2) {
  5183. if (!in_array($sessionId2, $listResCourseSession[$courseId2])) {
  5184. $listResCourseSession[$courseId2][] = $sessionId2;
  5185. }
  5186. }
  5187. } else {
  5188. $listResCourseSession[$courseId2] = $listSessionId2;
  5189. }
  5190. }
  5191. return $listResCourseSession;
  5192. }
  5193. /**
  5194. * Return an array of courses in session for user
  5195. * and for each courses the list of session that use this course for user
  5196. *
  5197. * [0] => array
  5198. * userCatId
  5199. * userCatTitle
  5200. * courseInUserCatList
  5201. * [0] => array
  5202. * courseId
  5203. * title
  5204. * courseCode
  5205. * sessionCatList
  5206. * [0] => array
  5207. * catSessionId
  5208. * catSessionName
  5209. * sessionList
  5210. * [0] => array
  5211. * sessionId
  5212. * sessionName
  5213. *
  5214. * @param $userId
  5215. * @return array
  5216. *
  5217. */
  5218. public static function getNamedSessionCourseForCoach($userId)
  5219. {
  5220. $listResults = array();
  5221. $listCourseSession = self::getSessionCourseForUser($userId);
  5222. foreach ($listCourseSession as $courseId => $listSessionId) {
  5223. // course info
  5224. $courseInfo = api_get_course_info_by_id($courseId);
  5225. $listOneCourse = array();
  5226. $listOneCourse['courseId'] = $courseId;
  5227. $listOneCourse['title'] = $courseInfo['title'];
  5228. $listOneCourse['courseCode'] = $courseInfo['code'];
  5229. $listOneCourse['sessionCatList'] = array();
  5230. $listCat = array();
  5231. foreach ($listSessionId as $i => $sessionId) {
  5232. // here we got all session for this course
  5233. // lets check there session categories
  5234. $sessionInfo = SessionManager::fetch($sessionId);
  5235. $catId = $sessionInfo['session_category_id'];
  5236. if (!isset($listCat[$catId])) {
  5237. $listCatInfo = self::get_session_category($catId);
  5238. $listCat[$catId] = array();
  5239. $listCat[$catId]['catSessionId'] = $catId;
  5240. $listCat[$catId]['catSessionName'] = $listCatInfo['name'];
  5241. $listCat[$catId]['sessionList'] = array();
  5242. }
  5243. $listSessionInfo = SessionManager::fetch($sessionId);
  5244. $listSessionIdName = array(
  5245. "sessionId" => $sessionId,
  5246. "sessionName" => $listSessionInfo['name'],
  5247. );
  5248. $listCat[$catId]['sessionList'][] = $listSessionIdName;
  5249. }
  5250. // sort $listCat by catSessionName
  5251. usort($listCat, 'self::compareBySessionName');
  5252. // in each catSession sort sessionList by sessionName
  5253. foreach($listCat as $i => $listCatSessionInfo) {
  5254. $listSessionList = $listCatSessionInfo['sessionList'];
  5255. usort($listSessionList, 'self::compareCatSessionInfo');
  5256. $listCat[$i]['sessionList'] = $listSessionList;
  5257. }
  5258. $listOneCourse['sessionCatList'] = $listCat;
  5259. // user course category
  5260. CourseManager::getUserCourseCategoryForCourse(
  5261. list($userCatId, $userCatTitle) =
  5262. $userId,
  5263. $courseId
  5264. );
  5265. $userCatId = intval($userCatId);
  5266. $listResults[$userCatId]['courseInUserCategoryId'] = $userCatId;
  5267. $listResults[$userCatId]['courseInUserCategoryTitle'] = $userCatTitle;
  5268. $listResults[$userCatId]['courseInUserCatList'][] = $listOneCourse;
  5269. }
  5270. // sort by user course cat
  5271. uasort($listResults, 'self::compareByUserCourseCat');
  5272. // sort by course title
  5273. foreach ($listResults as $userCourseCatId => $tabCoursesInCat) {
  5274. $courseInUserCatList = $tabCoursesInCat['courseInUserCatList'];
  5275. uasort($courseInUserCatList, 'self::compareByCourse');
  5276. $listResults[$userCourseCatId]['courseInUserCatList'] = $courseInUserCatList;
  5277. }
  5278. return $listResults;
  5279. }
  5280. /**
  5281. * @param array $listA
  5282. * @param array $listB
  5283. * @return int
  5284. */
  5285. private static function compareCatSessionInfo($listA, $listB)
  5286. {
  5287. if ($listA['sessionName'] == $listB['sessionName']) {
  5288. return 0;
  5289. } else if($listA['sessionName'] > $listB['sessionName']) {
  5290. return 1;
  5291. } else {
  5292. return -1;
  5293. }
  5294. }
  5295. /**
  5296. * @param array $listA
  5297. * @param array $listB
  5298. * @return int
  5299. */
  5300. private static function compareBySessionName($listA, $listB)
  5301. {
  5302. if ($listB['catSessionName'] == '') {
  5303. return -1;
  5304. } else if ($listA['catSessionName'] == '') {
  5305. return 1;
  5306. } else if ($listA['catSessionName'] == $listB['catSessionName']) {
  5307. return 0;
  5308. } else if($listA['catSessionName'] > $listB['catSessionName']) {
  5309. return 1;
  5310. } else {
  5311. return -1;
  5312. }
  5313. }
  5314. /**
  5315. * @param array $listA
  5316. * @param array $listB
  5317. * @return int
  5318. */
  5319. private static function compareByUserCourseCat($listA, $listB)
  5320. {
  5321. if ($listA['courseInUserCategoryTitle'] == $listB['courseInUserCategoryTitle']) {
  5322. return 0;
  5323. } else if($listA['courseInUserCategoryTitle'] > $listB['courseInUserCategoryTitle']) {
  5324. return 1;
  5325. } else {
  5326. return -1;
  5327. }
  5328. }
  5329. /**
  5330. * @param array $listA
  5331. * @param array $listB
  5332. * @return int
  5333. */
  5334. private static function compareByCourse($listA, $listB)
  5335. {
  5336. if ($listA['title'] == $listB['title']) {
  5337. return 0;
  5338. } else if($listA['title'] > $listB['title']) {
  5339. return 1;
  5340. } else {
  5341. return -1;
  5342. }
  5343. }
  5344. /**
  5345. * Return HTML code for displaying session_course_for_coach
  5346. * @param $userId
  5347. * @return string
  5348. */
  5349. public static function getHtmlNamedSessionCourseForCoach($userId)
  5350. {
  5351. $htmlRes = '';
  5352. $listInfo = self::getNamedSessionCourseForCoach($userId);
  5353. foreach($listInfo as $i => $listCoursesInfo) {
  5354. $courseCode = $listCoursesInfo['courseCode'];
  5355. $courseTitle = $listCoursesInfo['title'];
  5356. $listParamsCourse = array();
  5357. $listParamsCourse['icon'] = '<div style="float:left"><input style="border:none;" type="button" onclick="$(\'#course-'.$courseCode.'\').toggle(\'fast\')" value="+" /></div>'.Display::return_icon('blackboard.png', $listCoursesInfo['title'], array(), ICON_SIZE_LARGE);
  5358. $listParamsCourse['link'] = '';
  5359. $listParamsCourse['title'] = Display::tag('a', $listCoursesInfo['title'], array('href'=>$listParamsCourse['link']));
  5360. $htmlCourse = '<div class="well" style="border-color:#27587D">'.
  5361. CourseManager::course_item_html($listParamsCourse, true);
  5362. // for each category of session
  5363. $htmlCatSessions = '';
  5364. foreach ($listCoursesInfo['sessionCatList'] as $j => $listCatSessionsInfo) {
  5365. // we got an array of session categories
  5366. $catSessionId = $listCoursesInfo['sessionCatList'][$j]['catSessionId'];
  5367. $catSessionName = $listCoursesInfo['sessionCatList'][$j]['catSessionName'];
  5368. $listParamsCatSession['icon'] = Display::return_icon('folder_blue.png', $catSessionName, array(), ICON_SIZE_LARGE);
  5369. $listParamsCatSession['link'] = '';
  5370. $listParamsCatSession['title'] = $catSessionName;
  5371. $marginShift = 20;
  5372. if ($catSessionName != '') {
  5373. $htmlCatSessions .= '<div style="margin-left:'.$marginShift.'px;">' .
  5374. CourseManager::course_item_html($listParamsCatSession, true) . '</div>';
  5375. $marginShift = 40;
  5376. }
  5377. // for each sessions
  5378. $listCatSessionSessionList = $listCoursesInfo['sessionCatList'][$j]['sessionList'];
  5379. $htmlSession = '';
  5380. foreach ($listCatSessionSessionList as $k => $listSessionInfo) {
  5381. // we got an array of session info
  5382. $sessionId = $listSessionInfo['sessionId'];
  5383. $sessionName = $listSessionInfo['sessionName'];
  5384. $listParamsSession['icon'] = Display::return_icon('blackboard_blue.png', $sessionName, array(), ICON_SIZE_LARGE);
  5385. $listParamsSession['link'] = '';
  5386. $linkToCourseSession = api_get_path(WEB_PATH).'courses/'.$courseCode.'/?id_session='.$sessionId;
  5387. $listParamsSession['title'] = $sessionName.'<div style="font-weight:normal; font-style:italic">
  5388. <a href="'.$linkToCourseSession.'">
  5389. '.get_lang('GoToCourseInsideSession').'</a></div>';
  5390. $htmlSession .= '<div style="margin-left:'.$marginShift.'px;">'.
  5391. CourseManager::course_item_html($listParamsSession, true).'</div>';
  5392. }
  5393. $htmlCatSessions .= $htmlSession;
  5394. }
  5395. $htmlRes .= $htmlCourse.'<div style="display:none" id="course-'.$courseCode.'">'.$htmlCatSessions.'</div></div>';
  5396. }
  5397. return $htmlRes;
  5398. }
  5399. /**
  5400. * Return an associative array 'id_course' => [id_session1, id_session2...]
  5401. * where course id_course is in sessions id_session1, id_session2
  5402. * @param $userId
  5403. *
  5404. * @return array
  5405. */
  5406. public static function getCoursesForCourseSessionCoach($userId)
  5407. {
  5408. $listResCourseSession = array();
  5409. $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  5410. $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5411. $sql = "SELECT id_session, course_code, c.id
  5412. FROM $tblSessionRelCourseRelUser srcru
  5413. LEFT JOIN $tblCourse c
  5414. ON c.code = srcru.course_code
  5415. WHERE
  5416. srcru.id_user=".intval($userId)."
  5417. AND srcru.status = 2";
  5418. $res = Database::query($sql);
  5419. while ($data = Database::fetch_assoc($res)) {
  5420. if (self::isSessionDateOkForCoach($data['id_session'])) {
  5421. if (!isset($listResCourseSession[$data['id']])) {
  5422. $listResCourseSession[$data['id']] = array();
  5423. }
  5424. $listResCourseSession[$data['id']][] = $data['id_session'];
  5425. }
  5426. }
  5427. return $listResCourseSession;
  5428. }
  5429. /**
  5430. * Return true if coach is allowed to access this session
  5431. * @param int $sessionId
  5432. * @return bool
  5433. */
  5434. public static function isSessionDateOkForCoach($sessionId)
  5435. {
  5436. $listSessionInfo = api_get_session_info($sessionId);
  5437. $dateStart = $listSessionInfo['date_start'];
  5438. $dateEnd = $listSessionInfo['date_end'];
  5439. $nbDaysAccessBeforeBeginning = $listSessionInfo['nb_days_access_before_beginning'];
  5440. $nbDaysAccessAfterEnd = $listSessionInfo['nb_days_access_after_end'];
  5441. // no start date
  5442. if ($dateStart == '0000-00-00') {
  5443. return true;
  5444. }
  5445. $now = time();
  5446. $dateStartForCoach = api_strtotime($dateStart.' 00:00:00') - ($nbDaysAccessBeforeBeginning * 86400);
  5447. $dateEndForCoach = api_strtotime($dateEnd.' 00:00:00') + ($nbDaysAccessAfterEnd * 86400);
  5448. if ($dateEnd == '0000-00-00') {
  5449. // start date but no end date
  5450. if ($dateStartForCoach <= $now) {
  5451. return true;
  5452. }
  5453. } else {
  5454. // start date and end date
  5455. if ($dateStartForCoach <= $now && $now <= $dateEndForCoach) {
  5456. return true;
  5457. }
  5458. }
  5459. return false;
  5460. }
  5461. /**
  5462. * Return an associative array 'id_course' => [id_session1, id_session2...]
  5463. * where course id_course is in sessions id_session1, id_session2
  5464. * @param $userId
  5465. * @return array
  5466. */
  5467. public static function getCoursesForMainSessionCoach($userId)
  5468. {
  5469. $listResCourseSession = array();
  5470. $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
  5471. // list of SESSION where user is session coach
  5472. $sql = "SELECT id FROM $tblSession
  5473. WHERE id_coach = ".intval($userId);
  5474. $res = Database::query($sql);
  5475. while ($data = Database::fetch_assoc($res)) {
  5476. $sessionId = $data['id'];
  5477. $listCoursesInSession = self::getCoursesInSession($sessionId);
  5478. foreach ($listCoursesInSession as $i => $courseId) {
  5479. if (self::isSessionDateOkForCoach($sessionId)) {
  5480. if (!isset($listResCourseSession[$courseId])) {
  5481. $listResCourseSession[$courseId] = array();
  5482. }
  5483. $listResCourseSession[$courseId][] = $sessionId;
  5484. }
  5485. }
  5486. }
  5487. return $listResCourseSession;
  5488. }
  5489. /**
  5490. * Return an array of course_id used in session $sessionId
  5491. * @param $sessionId
  5492. * @return array
  5493. */
  5494. public static function getCoursesInSession($sessionId)
  5495. {
  5496. $listResultsCourseId = array();
  5497. $tblSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  5498. $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  5499. // list of course in this session
  5500. $sql = "SELECT id_session, c.id
  5501. FROM $tblSessionRelCourse src
  5502. LEFT JOIN $tblCourse c
  5503. ON c.code = src.course_code
  5504. WHERE id_session=".intval($sessionId);
  5505. $res = Database::query($sql);
  5506. while ($data = Database::fetch_assoc($res)) {
  5507. $listResultsCourseId[] = $data['id'];
  5508. }
  5509. return $listResultsCourseId;
  5510. }
  5511. }