sessionmanager.lib.php 355 KB

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