sessionmanager.lib.php 310 KB

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