sessionmanager.lib.php 346 KB

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