sessionmanager.lib.php 327 KB

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