sessionmanager.lib.php 302 KB

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