sessionmanager.lib.php 339 KB

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