sessionmanager.lib.php 306 KB

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