sessionmanager.lib.php 325 KB

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