sessionmanager.lib.php 288 KB

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