sessionmanager.lib.php 301 KB

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