sessionmanager.lib.php 300 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850
  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 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. if (empty($sessionId)) {
  2900. $sessionsSQL = SessionManager::get_sessions_followed_by_drh(
  2901. $userId,
  2902. null,
  2903. null,
  2904. null,
  2905. true,
  2906. true
  2907. );
  2908. } else {
  2909. $sessionsSQL = intval($sessionId);
  2910. }
  2911. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2912. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2913. if ($getCount) {
  2914. $select = "SELECT COUNT(DISTINCT(c.code)) as count ";
  2915. } else {
  2916. $select = "SELECT DISTINCT c.* ";
  2917. }
  2918. $keywordCondition = null;
  2919. if (!empty($keyword)) {
  2920. $keyword = Database::escape_string($keyword);
  2921. $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
  2922. }
  2923. // Select the courses
  2924. $sql = "$select
  2925. FROM $tbl_course c
  2926. INNER JOIN $tbl_session_rel_course src
  2927. ON c.id = src.c_id
  2928. WHERE
  2929. src.session_id IN ($sessionsSQL)
  2930. $keywordCondition
  2931. ";
  2932. if ($getCount) {
  2933. $result = Database::query($sql);
  2934. $row = Database::fetch_array($result,'ASSOC');
  2935. return $row['count'];
  2936. }
  2937. if (isset($from) && isset($limit)) {
  2938. $from = intval($from);
  2939. $limit = intval($limit);
  2940. $sql .= " LIMIT $from, $limit";
  2941. }
  2942. $result = Database::query($sql);
  2943. $num_rows = Database::num_rows($result);
  2944. $courses = array();
  2945. if ($num_rows > 0) {
  2946. while ($row = Database::fetch_array($result,'ASSOC')) {
  2947. $courses[$row['id']] = $row;
  2948. }
  2949. }
  2950. return $courses;
  2951. }
  2952. /**
  2953. * Gets the list of courses by session filtered by access_url
  2954. * @param int $session_id
  2955. * @param string $course_name
  2956. * @return array list of courses
  2957. */
  2958. public static function get_course_list_by_session_id_like($session_id, $course_name = '')
  2959. {
  2960. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2961. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2962. $session_id = intval($session_id);
  2963. $course_name = Database::escape_string($course_name);
  2964. // select the courses
  2965. $sql = "SELECT c.id, c.title FROM $tbl_course c
  2966. INNER JOIN $tbl_session_rel_course src
  2967. ON c.id = src.c_id
  2968. WHERE ";
  2969. if (!empty($session_id)) {
  2970. $sql .= "src.session_id LIKE '$session_id' AND ";
  2971. }
  2972. if (!empty($course_name)) {
  2973. $sql .= "UPPER(c.title) LIKE UPPER('%$course_name%') ";
  2974. }
  2975. $sql .= "ORDER BY title;";
  2976. $result = Database::query($sql);
  2977. $num_rows = Database::num_rows($result);
  2978. $courses = array();
  2979. if ($num_rows > 0) {
  2980. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2981. $courses[$row['id']] = $row;
  2982. }
  2983. }
  2984. return $courses;
  2985. }
  2986. /**
  2987. * Gets the count of courses by session filtered by access_url
  2988. * @param int session id
  2989. * @return array list of courses
  2990. */
  2991. public static function getCourseCountBySessionId($session_id, $keyword = null)
  2992. {
  2993. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2994. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2995. $session_id = intval($session_id);
  2996. // select the courses
  2997. $sql = "SELECT COUNT(c.code) count
  2998. FROM $tbl_course c
  2999. INNER JOIN $tbl_session_rel_course src
  3000. ON c.id = src.c_id
  3001. WHERE src.session_id = '$session_id' ";
  3002. $keywordCondition = null;
  3003. if (!empty($keyword)) {
  3004. $keyword = Database::escape_string($keyword);
  3005. $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
  3006. }
  3007. $sql .= $keywordCondition;
  3008. $result = Database::query($sql);
  3009. $num_rows = Database::num_rows($result);
  3010. if ($num_rows > 0) {
  3011. $row = Database::fetch_array($result,'ASSOC');
  3012. return $row['count'];
  3013. }
  3014. return null;
  3015. }
  3016. /**
  3017. * Get the session id based on the original id and field name in the extra fields.
  3018. * Returns 0 if session was not found
  3019. *
  3020. * @param string $value Original session id
  3021. * @param string $variable Original field name
  3022. * @return int Session id
  3023. */
  3024. public static function getSessionIdFromOriginalId($value, $variable)
  3025. {
  3026. $extraFieldValue = new ExtraFieldValue('session');
  3027. $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  3028. $variable,
  3029. $value
  3030. );
  3031. if (!empty($result)) {
  3032. return $result['item_id'];
  3033. }
  3034. return 0;
  3035. }
  3036. /**
  3037. * Get users by session
  3038. * @param int $id session id
  3039. * @param int $status filter by status coach = 2
  3040. * @return array a list with an user list
  3041. */
  3042. public static function get_users_by_session($id, $status = null)
  3043. {
  3044. if (empty($id)) {
  3045. return array();
  3046. }
  3047. $id = intval($id);
  3048. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3049. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3050. $table_access_url_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3051. $sql = "SELECT
  3052. u.user_id,
  3053. lastname,
  3054. firstname,
  3055. username,
  3056. relation_type,
  3057. access_url_id
  3058. FROM $tbl_user u
  3059. INNER JOIN $tbl_session_rel_user
  3060. ON u.user_id = $tbl_session_rel_user.user_id AND
  3061. $tbl_session_rel_user.session_id = $id
  3062. LEFT OUTER JOIN $table_access_url_user uu
  3063. ON (uu.user_id = u.user_id)
  3064. ";
  3065. $urlId = api_get_current_access_url_id();
  3066. if (isset($status) && $status != '') {
  3067. $status = intval($status);
  3068. $sql .= " WHERE relation_type = $status AND (access_url_id = $urlId OR access_url_id is null )";
  3069. } else {
  3070. $sql .= " WHERE (access_url_id = $urlId OR access_url_id is null )";
  3071. }
  3072. $sql .= " ORDER BY relation_type, ";
  3073. $sql .= api_sort_by_first_name() ? ' firstname, lastname' : ' lastname, firstname';
  3074. $result = Database::query($sql);
  3075. $return = array();
  3076. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3077. $return[] = $row;
  3078. }
  3079. return $return;
  3080. }
  3081. /**
  3082. * The general coach (field: session.id_coach)
  3083. * @param int $user_id user id
  3084. * @param boolean $asPlatformAdmin The user is platform admin, return everything
  3085. * @return array
  3086. */
  3087. public static function get_sessions_by_general_coach($user_id, $asPlatformAdmin = false)
  3088. {
  3089. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3090. $user_id = intval($user_id);
  3091. // Session where we are general coach
  3092. $sql = "SELECT DISTINCT *
  3093. FROM $session_table";
  3094. if (!$asPlatformAdmin) {
  3095. $sql .= " WHERE id_coach = $user_id";
  3096. }
  3097. if (api_is_multiple_url_enabled()) {
  3098. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3099. $access_url_id = api_get_current_access_url_id();
  3100. $sqlCoach = '';
  3101. if (!$asPlatformAdmin) {
  3102. $sqlCoach = " id_coach = $user_id AND ";
  3103. }
  3104. if ($access_url_id != -1) {
  3105. $sql = 'SELECT DISTINCT session.*
  3106. FROM ' . $session_table . ' session INNER JOIN ' . $tbl_session_rel_access_url . ' session_rel_url
  3107. ON (session.id = session_rel_url.session_id)
  3108. WHERE '.$sqlCoach.' access_url_id = ' . $access_url_id;
  3109. }
  3110. }
  3111. $sql .= ' ORDER by name';
  3112. $result = Database::query($sql);
  3113. return Database::store_result($result, 'ASSOC');
  3114. }
  3115. /**
  3116. * @param int $user_id
  3117. * @return array
  3118. * @deprecated use get_sessions_by_general_coach()
  3119. */
  3120. public static function get_sessions_by_coach($user_id)
  3121. {
  3122. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3123. return Database::select('*', $session_table, array('where' => array('id_coach = ?' => $user_id)));
  3124. }
  3125. /**
  3126. * @param int $user_id
  3127. * @param int $courseId
  3128. * @param int $session_id
  3129. * @return array|bool
  3130. */
  3131. public static function get_user_status_in_course_session($user_id, $courseId, $session_id)
  3132. {
  3133. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3134. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3135. $sql = "SELECT session_rcru.status
  3136. FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  3137. WHERE
  3138. session_rcru.user_id = user.user_id AND
  3139. session_rcru.session_id = '" . intval($session_id) . "' AND
  3140. session_rcru.c_id ='" . intval($courseId) . "' AND
  3141. user.user_id = " . intval($user_id);
  3142. $result = Database::query($sql);
  3143. $status = false;
  3144. if (Database::num_rows($result)) {
  3145. $status = Database::fetch_row($result);
  3146. $status = $status['0'];
  3147. }
  3148. return $status;
  3149. }
  3150. /**
  3151. * Gets user status within a session
  3152. * @param int $user_id
  3153. * @param int $courseId
  3154. * @param $session_id
  3155. * @return int
  3156. * @assert (null,null,null) === false
  3157. */
  3158. public static function get_user_status_in_session($user_id, $courseId, $session_id)
  3159. {
  3160. if (empty($user_id) or empty($courseId) or empty($session_id)) {
  3161. return false;
  3162. }
  3163. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3164. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3165. $sql = "SELECT session_rcru.status
  3166. FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  3167. WHERE session_rcru.user_id = user.user_id AND
  3168. session_rcru.session_id = '" . intval($session_id) . "' AND
  3169. session_rcru.c_id ='" . intval($courseId) . "' AND
  3170. user.user_id = " . intval($user_id);
  3171. $result = Database::query($sql);
  3172. $status = false;
  3173. if (Database::num_rows($result)) {
  3174. $status = Database::fetch_row($result);
  3175. $status = $status['0'];
  3176. }
  3177. return $status;
  3178. }
  3179. /**
  3180. * @param int $id
  3181. * @return array
  3182. */
  3183. public static function get_all_sessions_by_promotion($id)
  3184. {
  3185. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  3186. return Database::select('*', $t, array('where' => array('promotion_id = ?' => $id)));
  3187. }
  3188. /**
  3189. * @param int $promotion_id
  3190. * @param array $list
  3191. */
  3192. public static function suscribe_sessions_to_promotion($promotion_id, $list)
  3193. {
  3194. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  3195. $params = array();
  3196. $params['promotion_id'] = 0;
  3197. Database::update($t, $params, array('promotion_id = ?' => $promotion_id));
  3198. $params['promotion_id'] = $promotion_id;
  3199. if (!empty($list)) {
  3200. foreach ($list as $session_id) {
  3201. $session_id = intval($session_id);
  3202. Database::update($t, $params, array('id = ?' => $session_id));
  3203. }
  3204. }
  3205. }
  3206. /**
  3207. * Updates a session status
  3208. * @param int session id
  3209. * @param int status
  3210. */
  3211. public static function set_session_status($session_id, $status)
  3212. {
  3213. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  3214. $params['visibility'] = $status;
  3215. Database::update($t, $params, array('id = ?' => $session_id));
  3216. }
  3217. /**
  3218. * Copies a session with the same data to a new session.
  3219. * The new copy is not assigned to the same promotion. @see suscribe_sessions_to_promotions() for that
  3220. * @param int Session ID
  3221. * @param bool Whether to copy the relationship with courses
  3222. * @param bool Whether to copy the relationship with users
  3223. * @param bool New courses will be created
  3224. * @param bool Whether to set exercises and learning paths in the new session to invisible by default
  3225. * @return int The new session ID on success, 0 otherwise
  3226. * @todo make sure the extra session fields are copied too
  3227. */
  3228. public static function copy(
  3229. $id,
  3230. $copy_courses = true,
  3231. $copy_users = true,
  3232. $create_new_courses = false,
  3233. $set_exercises_lp_invisible = false
  3234. ) {
  3235. $id = intval($id);
  3236. $s = self::fetch($id);
  3237. // Check all dates before copying
  3238. // Get timestamp for now in UTC - see http://php.net/manual/es/function.time.php#117251
  3239. $now = time() - date('Z');
  3240. // Timestamp in one month
  3241. $inOneMonth = $now + (30*24*3600);
  3242. $inOneMonth = api_get_local_time($inOneMonth);
  3243. if (api_strtotime($s['access_start_date']) < $now) {
  3244. $s['access_start_date'] = api_get_local_time($now);
  3245. }
  3246. if (api_strtotime($s['display_start_date']) < $now) {
  3247. $s['display_start_date'] = api_get_local_time($now);
  3248. }
  3249. if (api_strtotime($s['coach_access_start_date']) < $now) {
  3250. $s['coach_access_start_date'] = api_get_local_time($now);
  3251. }
  3252. if (api_strtotime($s['access_end_date']) < $now) {
  3253. $s['access_end_date'] = $inOneMonth;
  3254. }
  3255. if (api_strtotime($s['display_end_date']) < $now) {
  3256. $s['display_end_date'] = $inOneMonth;
  3257. }
  3258. if (api_strtotime($s['coach_access_end_date']) < $now) {
  3259. $s['coach_access_end_date'] = $inOneMonth;
  3260. }
  3261. // Now try to create the session
  3262. $sid = self::create_session(
  3263. $s['name'] . ' ' . get_lang('CopyLabelSuffix'),
  3264. $s['access_start_date'],
  3265. $s['access_end_date'],
  3266. $s['display_start_date'],
  3267. $s['display_end_date'],
  3268. $s['coach_access_start_date'],
  3269. $s['coach_access_end_date'],
  3270. (int)$s['id_coach'],
  3271. $s['session_category_id'],
  3272. (int)$s['visibility'],
  3273. true
  3274. );
  3275. if (!is_numeric($sid) || empty($sid)) {
  3276. return false;
  3277. }
  3278. if ($copy_courses) {
  3279. // Register courses from the original session to the new session
  3280. $courses = self::get_course_list_by_session_id($id);
  3281. $short_courses = $new_short_courses = array();
  3282. if (is_array($courses) && count($courses) > 0) {
  3283. foreach ($courses as $course) {
  3284. $short_courses[] = $course;
  3285. }
  3286. }
  3287. $courses = null;
  3288. //We will copy the current courses of the session to new courses
  3289. if (!empty($short_courses)) {
  3290. if ($create_new_courses) {
  3291. //Just in case
  3292. if (function_exists('ini_set')) {
  3293. api_set_memory_limit('256M');
  3294. ini_set('max_execution_time', 0);
  3295. }
  3296. $params = array();
  3297. $params['skip_lp_dates'] = true;
  3298. foreach ($short_courses as $course_data) {
  3299. $course_info = CourseManager::copy_course_simple(
  3300. $course_data['title'].' '.get_lang(
  3301. 'CopyLabelSuffix'
  3302. ),
  3303. $course_data['course_code'],
  3304. $id,
  3305. $sid,
  3306. $params
  3307. );
  3308. if ($course_info) {
  3309. //By default new elements are invisible
  3310. if ($set_exercises_lp_invisible) {
  3311. $list = new LearnpathList('', $course_info['code'], $sid);
  3312. $flat_list = $list->get_flat_list();
  3313. if (!empty($flat_list)) {
  3314. foreach ($flat_list as $lp_id => $data) {
  3315. api_item_property_update(
  3316. $course_info,
  3317. TOOL_LEARNPATH,
  3318. $lp_id,
  3319. 'invisible',
  3320. api_get_user_id(),
  3321. 0,
  3322. 0,
  3323. 0,
  3324. 0,
  3325. $sid
  3326. );
  3327. }
  3328. }
  3329. $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
  3330. $course_id = $course_info['real_id'];
  3331. //@todo check this query
  3332. $sql = "UPDATE $quiz_table SET active = 0
  3333. WHERE c_id = $course_id AND session_id = $sid";
  3334. Database::query($sql);
  3335. }
  3336. $new_short_courses[] = $course_info['real_id'];
  3337. }
  3338. }
  3339. } else {
  3340. foreach ($short_courses as $course_data) {
  3341. $new_short_courses[] = $course_data['id'];
  3342. }
  3343. }
  3344. $short_courses = $new_short_courses;
  3345. self::add_courses_to_session($sid, $short_courses, true);
  3346. $short_courses = null;
  3347. }
  3348. }
  3349. if ($copy_users) {
  3350. // Register users from the original session to the new session
  3351. $users = self::get_users_by_session($id);
  3352. $short_users = array();
  3353. if (is_array($users) && count($users) > 0) {
  3354. foreach ($users as $user) {
  3355. $short_users[] = $user['user_id'];
  3356. }
  3357. }
  3358. $users = null;
  3359. //Subscribing in read only mode
  3360. self::suscribe_users_to_session($sid, $short_users, SESSION_VISIBLE_READ_ONLY, true);
  3361. $short_users = null;
  3362. }
  3363. return $sid;
  3364. }
  3365. /**
  3366. * @param int $user_id
  3367. * @param int $session_id
  3368. * @return bool
  3369. */
  3370. static function user_is_general_coach($user_id, $session_id)
  3371. {
  3372. $session_id = intval($session_id);
  3373. $user_id = intval($user_id);
  3374. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3375. $sql = "SELECT DISTINCT id
  3376. FROM $session_table
  3377. WHERE session.id_coach = '" . $user_id . "' AND id = '$session_id'";
  3378. $result = Database::query($sql);
  3379. if ($result && Database::num_rows($result)) {
  3380. return true;
  3381. }
  3382. return false;
  3383. }
  3384. /**
  3385. * Get the number of sessions
  3386. * @param int ID of the URL we want to filter on (optional)
  3387. * @return int Number of sessions
  3388. */
  3389. public static function count_sessions($access_url_id = null)
  3390. {
  3391. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  3392. $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3393. $sql = "SELECT count(id) FROM $session_table s";
  3394. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  3395. $sql .= ", $access_url_rel_session_table u " .
  3396. " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
  3397. }
  3398. $res = Database::query($sql);
  3399. $row = Database::fetch_row($res);
  3400. return $row[0];
  3401. }
  3402. /**
  3403. * Protect a session to be edited.
  3404. * @param int $id
  3405. * @param bool $checkSession
  3406. * @return mixed | bool true if pass the check, api_not_allowed otherwise
  3407. */
  3408. public static function protectSession($id, $checkSession = true)
  3409. {
  3410. // api_protect_admin_script(true);
  3411. if (self::allowToManageSessions()) {
  3412. if (api_is_platform_admin()) {
  3413. return true;
  3414. }
  3415. if ($checkSession) {
  3416. if (self::allowed($id)) {
  3417. return true;
  3418. } else {
  3419. api_not_allowed(true);
  3420. }
  3421. }
  3422. } else {
  3423. api_not_allowed(true);
  3424. }
  3425. }
  3426. /**
  3427. * @param int $id
  3428. * @return bool
  3429. */
  3430. private static function allowed($id)
  3431. {
  3432. $sessionInfo = self::fetch($id);
  3433. if (empty($sessionInfo)) {
  3434. return false;
  3435. }
  3436. if (api_is_platform_admin()) {
  3437. return true;
  3438. }
  3439. $userId = api_get_user_id();
  3440. if (api_is_session_admin() &&
  3441. api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true'
  3442. ) {
  3443. if ($sessionInfo['session_admin_id'] != $userId) {
  3444. return false;
  3445. }
  3446. }
  3447. if (api_is_teacher() &&
  3448. api_get_setting('allow_teachers_to_create_sessions') == 'true'
  3449. ) {
  3450. if ($sessionInfo['id_coach'] != $userId) {
  3451. return false;
  3452. }
  3453. }
  3454. return true;
  3455. }
  3456. /**
  3457. * @return bool
  3458. */
  3459. public static function allowToManageSessions()
  3460. {
  3461. if (self::allowManageAllSessions()) {
  3462. return true;
  3463. }
  3464. $setting = api_get_setting('allow_teachers_to_create_sessions');
  3465. if (api_is_teacher() && $setting == 'true') {
  3466. return true;
  3467. }
  3468. return false;
  3469. }
  3470. /**
  3471. * @return bool
  3472. */
  3473. public static function allowOnlyMySessions()
  3474. {
  3475. if (self::allowToManageSessions() &&
  3476. !api_is_platform_admin() &&
  3477. api_is_teacher()
  3478. ) {
  3479. return true;
  3480. }
  3481. return false;
  3482. }
  3483. /**
  3484. * @return bool
  3485. */
  3486. public static function allowManageAllSessions()
  3487. {
  3488. if (api_is_platform_admin() || api_is_session_admin()) {
  3489. return true;
  3490. }
  3491. return false;
  3492. }
  3493. /**
  3494. * @param $id
  3495. * @return bool
  3496. */
  3497. public static function protect_teacher_session_edit($id)
  3498. {
  3499. if (!api_is_coach($id) && !api_is_platform_admin()) {
  3500. api_not_allowed(true);
  3501. } else {
  3502. return true;
  3503. }
  3504. }
  3505. /**
  3506. * @param int $courseId
  3507. * @return array
  3508. */
  3509. public static function get_session_by_course($courseId)
  3510. {
  3511. $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3512. $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3513. $courseId = intval($courseId);
  3514. $sql = "SELECT name, s.id
  3515. FROM $table_session_course sc
  3516. INNER JOIN $table_session s ON (sc.session_id = s.id)
  3517. WHERE sc.c_id = '$courseId' ";
  3518. $result = Database::query($sql);
  3519. return Database::store_result($result);
  3520. }
  3521. /**
  3522. * @param int $user_id
  3523. * @param bool $ignore_visibility_for_admins
  3524. * @param bool $ignoreTimeLimit
  3525. *
  3526. * @return array
  3527. */
  3528. public static function get_sessions_by_user($user_id, $ignore_visibility_for_admins = false, $ignoreTimeLimit = false)
  3529. {
  3530. $sessionCategories = UserManager::get_sessions_by_category(
  3531. $user_id,
  3532. false,
  3533. $ignore_visibility_for_admins,
  3534. $ignoreTimeLimit
  3535. );
  3536. $sessionArray = array();
  3537. if (!empty($sessionCategories)) {
  3538. foreach ($sessionCategories as $category) {
  3539. if (isset($category['sessions'])) {
  3540. foreach ($category['sessions'] as $session) {
  3541. $sessionArray[] = $session;
  3542. }
  3543. }
  3544. }
  3545. }
  3546. return $sessionArray;
  3547. }
  3548. /**
  3549. * @param string $file
  3550. * @param bool $updateSession options:
  3551. * true: if the session exists it will be updated.
  3552. * false: if session exists a new session will be created adding a counter session1, session2, etc
  3553. * @param int $defaultUserId
  3554. * @param mixed $logger
  3555. * @param array $extraFields convert a file row to an extra field. Example in CSV file there's a SessionID then it will
  3556. * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
  3557. * @param string $extraFieldId
  3558. * @param int $daysCoachAccessBeforeBeginning
  3559. * @param int $daysCoachAccessAfterBeginning
  3560. * @param int $sessionVisibility
  3561. * @param array $fieldsToAvoidUpdate
  3562. * @param bool $deleteUsersNotInList
  3563. * @param bool $updateCourseCoaches
  3564. * @param bool $sessionWithCoursesModifier
  3565. * @param int $showDescription
  3566. * @param array $teacherBackupList
  3567. * @param array $groupBackup
  3568. * @return array
  3569. */
  3570. static function importCSV(
  3571. $file,
  3572. $updateSession,
  3573. $defaultUserId = null,
  3574. $logger = null,
  3575. $extraFields = array(),
  3576. $extraFieldId = null,
  3577. $daysCoachAccessBeforeBeginning = null,
  3578. $daysCoachAccessAfterBeginning = null,
  3579. $sessionVisibility = 1,
  3580. $fieldsToAvoidUpdate = array(),
  3581. $deleteUsersNotInList = false,
  3582. $updateCourseCoaches = false,
  3583. $sessionWithCoursesModifier = false,
  3584. $addOriginalCourseTeachersAsCourseSessionCoaches = true,
  3585. $removeAllTeachersFromCourse = true,
  3586. $showDescription = null,
  3587. &$teacherBackupList = array(),
  3588. &$groupBackup = array()
  3589. ) {
  3590. $content = file($file);
  3591. $error_message = null;
  3592. $session_counter = 0;
  3593. if (empty($defaultUserId)) {
  3594. $defaultUserId = api_get_user_id();
  3595. }
  3596. $eol = PHP_EOL;
  3597. if (PHP_SAPI != 'cli') {
  3598. $eol = '<br />';
  3599. }
  3600. $debug = false;
  3601. if (isset($logger)) {
  3602. $debug = true;
  3603. }
  3604. $extraParameters = null;
  3605. if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
  3606. $extraParameters .= ' , nb_days_access_before_beginning = '.intval($daysCoachAccessBeforeBeginning);
  3607. $extraParameters .= ' , nb_days_access_after_end = '.intval($daysCoachAccessAfterBeginning);
  3608. }
  3609. if (!is_null($showDescription)) {
  3610. $extraParameters .= ' , show_description = '.intval($showDescription);
  3611. }
  3612. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3613. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3614. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3615. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3616. $sessions = array();
  3617. if (!api_strstr($content[0], ';')) {
  3618. $error_message = get_lang('NotCSV');
  3619. } else {
  3620. $tag_names = array();
  3621. foreach ($content as $key => $enreg) {
  3622. $enreg = explode(';', trim($enreg));
  3623. if ($key) {
  3624. foreach ($tag_names as $tag_key => $tag_name) {
  3625. $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
  3626. }
  3627. } else {
  3628. foreach ($enreg as $tag_name) {
  3629. $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
  3630. }
  3631. if (!in_array('SessionName', $tag_names) ||
  3632. !in_array('DateStart', $tag_names) ||
  3633. !in_array('DateEnd', $tag_names)
  3634. ) {
  3635. $error_message = get_lang('NoNeededData');
  3636. break;
  3637. }
  3638. }
  3639. }
  3640. $sessionList = array();
  3641. // Looping the sessions.
  3642. foreach ($sessions as $enreg) {
  3643. $user_counter = 0;
  3644. $course_counter = 0;
  3645. if (isset($extraFields) && !empty($extraFields)) {
  3646. foreach ($extraFields as $original => $to) {
  3647. $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
  3648. }
  3649. }
  3650. $session_name = Database::escape_string($enreg['SessionName']);
  3651. // Default visibility
  3652. $visibilityAfterExpirationPerSession = $sessionVisibility;
  3653. if (isset($enreg['VisibilityAfterExpiration'])) {
  3654. $visibility = $enreg['VisibilityAfterExpiration'];
  3655. switch ($visibility) {
  3656. case 'read_only':
  3657. $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
  3658. break;
  3659. case 'accessible':
  3660. $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
  3661. break;
  3662. case 'not_accessible':
  3663. $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
  3664. break;
  3665. }
  3666. }
  3667. if (empty($session_name)) {
  3668. continue;
  3669. }
  3670. $date_start = $enreg['DateStart'];
  3671. $date_end = $enreg['DateEnd'];
  3672. $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
  3673. $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
  3674. $extraSessionParameters = null;
  3675. if (!empty($sessionDescription)) {
  3676. $extraSessionParameters = " , description = '".Database::escape_string($sessionDescription)."'";
  3677. }
  3678. // Searching a general coach.
  3679. if (!empty($enreg['Coach'])) {
  3680. $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
  3681. if ($coach_id === false) {
  3682. // If the coach-user does not exist - I'm the coach.
  3683. $coach_id = $defaultUserId;
  3684. }
  3685. } else {
  3686. $coach_id = $defaultUserId;
  3687. }
  3688. if (!$updateSession) {
  3689. // Always create a session.
  3690. $unique_name = false;
  3691. $i = 0;
  3692. // Change session name, verify that session doesn't exist.
  3693. $suffix = null;
  3694. while (!$unique_name) {
  3695. if ($i > 1) {
  3696. $suffix = ' - ' . $i;
  3697. }
  3698. $sql = 'SELECT 1 FROM ' . $tbl_session . '
  3699. WHERE name="' . $session_name . $suffix . '"';
  3700. $rs = Database::query($sql);
  3701. if (Database::result($rs, 0, 0)) {
  3702. $i++;
  3703. } else {
  3704. $unique_name = true;
  3705. $session_name .= $suffix;
  3706. }
  3707. }
  3708. $sessionCondition = '';
  3709. if (!empty($session_category_id)) {
  3710. $sessionCondition = "session_category_id = '$session_category_id',";
  3711. }
  3712. // Creating the session.
  3713. $sql = "INSERT IGNORE INTO $tbl_session SET
  3714. name = '" . $session_name . "',
  3715. id_coach = '$coach_id',
  3716. access_start_date = '$date_start',
  3717. access_end_date = '$date_end',
  3718. visibility = '$visibilityAfterExpirationPerSession',
  3719. $sessionCondition
  3720. session_admin_id = " . intval($defaultUserId) . $extraParameters . $extraSessionParameters;
  3721. Database::query($sql);
  3722. $session_id = Database::insert_id();
  3723. if ($debug) {
  3724. if ($session_id) {
  3725. foreach ($enreg as $key => $value) {
  3726. if (substr($key, 0, 6) == 'extra_') { //an extra field
  3727. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  3728. }
  3729. }
  3730. $logger->addInfo("Sessions - Session created: #$session_id - $session_name");
  3731. } else {
  3732. $logger->addError("Sessions - Session NOT created: $session_name");
  3733. }
  3734. }
  3735. $session_counter++;
  3736. } else {
  3737. $sessionId = null;
  3738. if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_'.$extraFieldId])) {
  3739. $sessionId = self::getSessionIdFromOriginalId($enreg['extra_'.$extraFieldId], $extraFieldId);
  3740. if (empty($sessionId)) {
  3741. $my_session_result = false;
  3742. } else {
  3743. $my_session_result = true;
  3744. }
  3745. } else {
  3746. $my_session_result = self::get_session_by_name($enreg['SessionName']);
  3747. }
  3748. if ($my_session_result === false) {
  3749. // Creating a session.
  3750. $sql = "INSERT IGNORE INTO $tbl_session SET
  3751. name = '$session_name',
  3752. id_coach = '$coach_id',
  3753. access_start_date = '$date_start',
  3754. access_end_date = '$date_end',
  3755. visibility = '$visibilityAfterExpirationPerSession',
  3756. session_category_id = '$session_category_id' " . $extraParameters . $extraSessionParameters;
  3757. Database::query($sql);
  3758. // We get the last insert id.
  3759. $my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
  3760. $session_id = $my_session_result['id'];
  3761. if ($session_id) {
  3762. foreach ($enreg as $key => $value) {
  3763. if (substr($key, 0, 6) == 'extra_') { //an extra field
  3764. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  3765. }
  3766. }
  3767. if ($debug) {
  3768. $logger->addInfo("Sessions - #$session_id created: $session_name");
  3769. }
  3770. // Delete session-user relation only for students
  3771. $sql = "DELETE FROM $tbl_session_user
  3772. WHERE session_id = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
  3773. Database::query($sql);
  3774. $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
  3775. Database::query($sql);
  3776. // Delete session-course-user relationships students and coaches.
  3777. if ($updateCourseCoaches) {
  3778. $sql = "DELETE FROM $tbl_session_course_user
  3779. WHERE session_id = '$session_id' AND status in ('0', '2')";
  3780. Database::query($sql);
  3781. } else {
  3782. // Delete session-course-user relation ships *only* for students.
  3783. $sql = "DELETE FROM $tbl_session_course_user
  3784. WHERE session_id = '$session_id' AND status <> 2";
  3785. Database::query($sql);
  3786. }
  3787. }
  3788. } else {
  3789. if ($debug) {
  3790. $logger->addError("Sessions - Session to be updated: $session_name");
  3791. }
  3792. // Updating the session.
  3793. $params = array(
  3794. 'id_coach' => $coach_id,
  3795. 'access_start_date' => $date_start,
  3796. 'access_end_date' => $date_end,
  3797. 'visibility' => $visibilityAfterExpirationPerSession,
  3798. 'session_category_id' => $session_category_id,
  3799. );
  3800. if (!empty($sessionDescription)) {
  3801. $params['description'] = $sessionDescription;
  3802. }
  3803. if (!empty($fieldsToAvoidUpdate)) {
  3804. foreach ($fieldsToAvoidUpdate as $field) {
  3805. unset($params[$field]);
  3806. }
  3807. }
  3808. if (isset($sessionId) && !empty($sessionId)) {
  3809. if (!empty($enreg['SessionName'])) {
  3810. $params['name'] = $enreg['SessionName'];
  3811. }
  3812. $session_id = $sessionId;
  3813. } else {
  3814. $row = Database::query("SELECT id FROM $tbl_session WHERE name = '$session_name'");
  3815. list($session_id) = Database::fetch_array($row);
  3816. }
  3817. if ($session_id) {
  3818. if ($debug) {
  3819. $logger->addError("Sessions - Session to be updated #$session_id");
  3820. }
  3821. $sessionInfo = api_get_session_info($session_id);
  3822. $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
  3823. if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
  3824. if (empty($sessionInfo['nb_days_access_before_beginning']) ||
  3825. (!empty($sessionInfo['nb_days_access_before_beginning']) &&
  3826. $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning)
  3827. ) {
  3828. $params['nb_days_access_before_beginning'] = intval($daysCoachAccessBeforeBeginning);
  3829. }
  3830. if (empty($sessionInfo['nb_days_access_after_end']) ||
  3831. (!empty($sessionInfo['nb_days_access_after_end']) &&
  3832. $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning)
  3833. ) {
  3834. $params['nb_days_access_after_end'] = intval($daysCoachAccessAfterBeginning);
  3835. }
  3836. }
  3837. Database::update($tbl_session, $params, array('id = ?' => $session_id));
  3838. foreach ($enreg as $key => $value) {
  3839. if (substr($key, 0, 6) == 'extra_') { //an extra field
  3840. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  3841. }
  3842. }
  3843. // Delete session-user relation only for students
  3844. $sql = "DELETE FROM $tbl_session_user
  3845. WHERE session_id = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
  3846. Database::query($sql);
  3847. $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
  3848. Database::query($sql);
  3849. // Delete session-course-user relationships students and coaches.
  3850. if ($updateCourseCoaches) {
  3851. $sql = "DELETE FROM $tbl_session_course_user
  3852. WHERE session_id = '$session_id' AND status in ('0', '2')";
  3853. Database::query($sql);
  3854. } else {
  3855. // Delete session-course-user relation ships *only* for students.
  3856. $sql = "DELETE FROM $tbl_session_course_user
  3857. WHERE session_id = '$session_id' AND status <> 2";
  3858. Database::query($sql);
  3859. }
  3860. } else {
  3861. if ($debug) {
  3862. $logger->addError(
  3863. "Sessions - Session not found"
  3864. );
  3865. }
  3866. }
  3867. }
  3868. $session_counter++;
  3869. }
  3870. $sessionList[] = $session_id;
  3871. $users = explode('|', $enreg['Users']);
  3872. // Adding the relationship "Session - User" for students
  3873. $userList = array();
  3874. if (is_array($users)) {
  3875. foreach ($users as $user) {
  3876. $user_id = UserManager::get_user_id_from_username($user);
  3877. if ($user_id !== false) {
  3878. $userList[] = $user_id;
  3879. // Insert new users.
  3880. $sql = "INSERT IGNORE INTO $tbl_session_user SET
  3881. user_id = '$user_id',
  3882. session_id = '$session_id',
  3883. registered_at = '" . api_get_utc_datetime() . "'";
  3884. Database::query($sql);
  3885. if ($debug) {
  3886. $logger->addInfo("Sessions - Adding User #$user_id ($user) to session #$session_id");
  3887. }
  3888. $user_counter++;
  3889. }
  3890. }
  3891. }
  3892. if ($deleteUsersNotInList) {
  3893. // Getting user in DB in order to compare to the new list.
  3894. $usersListInDatabase = self::get_users_by_session($session_id, 0);
  3895. if (!empty($usersListInDatabase)) {
  3896. if (empty($userList)) {
  3897. foreach ($usersListInDatabase as $userInfo) {
  3898. self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
  3899. }
  3900. } else {
  3901. foreach ($usersListInDatabase as $userInfo) {
  3902. if (!in_array($userInfo['user_id'], $userList)) {
  3903. self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
  3904. }
  3905. }
  3906. }
  3907. }
  3908. }
  3909. $courses = explode('|', $enreg['Courses']);
  3910. // See BT#6449
  3911. $onlyAddFirstCoachOrTeacher = false;
  3912. if ($sessionWithCoursesModifier) {
  3913. if (count($courses) >= 2) {
  3914. // Only first teacher in course session;
  3915. $onlyAddFirstCoachOrTeacher = true;
  3916. // Remove all teachers from course.
  3917. $removeAllTeachersFromCourse = false;
  3918. }
  3919. }
  3920. foreach ($courses as $course) {
  3921. $courseArray = bracketsToArray($course);
  3922. $course_code = $courseArray[0];
  3923. if (CourseManager::course_exists($course_code)) {
  3924. $courseInfo = api_get_course_info($course_code);
  3925. $courseId = $courseInfo['real_id'];
  3926. // Adding the course to a session.
  3927. $sql = "INSERT IGNORE INTO $tbl_session_course
  3928. SET c_id = '$courseId', session_id='$session_id'";
  3929. Database::query($sql);
  3930. SessionManager::installCourse($session_id, $courseInfo['real_id']);
  3931. if ($debug) {
  3932. $logger->addInfo("Sessions - Adding course '$course_code' to session #$session_id");
  3933. }
  3934. $course_counter++;
  3935. $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
  3936. $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
  3937. $course_users = explode(',', $course_users);
  3938. $course_coaches = explode(',', $course_coaches);
  3939. // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
  3940. $addTeachersToSession = true;
  3941. if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
  3942. $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
  3943. }
  3944. // If any user provided for a course, use the users array.
  3945. if (empty($course_users)) {
  3946. if (!empty($userList)) {
  3947. SessionManager::subscribe_users_to_session_course(
  3948. $userList,
  3949. $session_id,
  3950. $course_code
  3951. );
  3952. if ($debug) {
  3953. $msg = "Sessions - Adding student list ".implode(', #', $userList)." to course: '$course_code' and session #$session_id";
  3954. $logger->addInfo($msg);
  3955. }
  3956. }
  3957. }
  3958. // Adding coaches to session course user.
  3959. if (!empty($course_coaches)) {
  3960. $savedCoaches = array();
  3961. // only edit if add_teachers_to_sessions_courses is set.
  3962. if ($addTeachersToSession) {
  3963. if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
  3964. // Adding course teachers as course session teachers.
  3965. $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code(
  3966. $course_code
  3967. );
  3968. if (!empty($alreadyAddedTeachers)) {
  3969. $teachersToAdd = array();
  3970. foreach ($alreadyAddedTeachers as $user) {
  3971. $teachersToAdd[] = $user['username'];
  3972. }
  3973. $course_coaches = array_merge(
  3974. $course_coaches,
  3975. $teachersToAdd
  3976. );
  3977. }
  3978. }
  3979. foreach ($course_coaches as $course_coach) {
  3980. $coach_id = UserManager::get_user_id_from_username($course_coach);
  3981. if ($coach_id !== false) {
  3982. // Just insert new coaches
  3983. SessionManager::updateCoaches($session_id, $courseId, array($coach_id), false);
  3984. if ($debug) {
  3985. $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  3986. }
  3987. $savedCoaches[] = $coach_id;
  3988. } else {
  3989. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  3990. }
  3991. }
  3992. }
  3993. // Custom courses/session coaches
  3994. $teacherToAdd = null;
  3995. // Only one coach is added.
  3996. if ($onlyAddFirstCoachOrTeacher == true) {
  3997. foreach ($course_coaches as $course_coach) {
  3998. $coach_id = UserManager::get_user_id_from_username($course_coach);
  3999. if ($coach_id !== false) {
  4000. $teacherToAdd = $coach_id;
  4001. break;
  4002. }
  4003. }
  4004. // Un subscribe everyone that's not in the list.
  4005. $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
  4006. if (!empty($teacherList)) {
  4007. foreach ($teacherList as $teacher) {
  4008. if ($teacherToAdd != $teacher['user_id']) {
  4009. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  4010. WHERE
  4011. user_id = ".$teacher['user_id']." AND
  4012. course_code = '".$course_code."'
  4013. ";
  4014. $result = Database::query($sql);
  4015. $userCourseData = Database::fetch_array($result, 'ASSOC');
  4016. $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
  4017. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  4018. WHERE
  4019. user_id = ".$teacher['user_id']." AND
  4020. c_id = '".$courseInfo['real_id']."'
  4021. ";
  4022. $result = Database::query($sql);
  4023. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4024. $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4025. }
  4026. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  4027. WHERE
  4028. user_id = ".$teacher['user_id']." AND
  4029. c_id = '".$courseInfo['real_id']."'
  4030. ";
  4031. $result = Database::query($sql);
  4032. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4033. $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4034. }
  4035. CourseManager::unsubscribe_user(
  4036. $teacher['user_id'],
  4037. $course_code
  4038. );
  4039. }
  4040. }
  4041. }
  4042. if (!empty($teacherToAdd)) {
  4043. SessionManager::updateCoaches($session_id, $courseId, array($teacherToAdd), true);
  4044. $userCourseCategory = '';
  4045. if (isset($teacherBackupList[$teacherToAdd]) &&
  4046. isset($teacherBackupList[$teacherToAdd][$course_code])
  4047. ) {
  4048. $courseUserData = $teacherBackupList[$teacherToAdd][$course_code];
  4049. $userCourseCategory = $courseUserData['user_course_cat'];
  4050. }
  4051. CourseManager::subscribe_user(
  4052. $teacherToAdd,
  4053. $course_code,
  4054. COURSEMANAGER,
  4055. 0,
  4056. $userCourseCategory
  4057. );
  4058. if (isset($groupBackup['user'][$teacherToAdd]) &&
  4059. isset($groupBackup['user'][$teacherToAdd][$course_code]) &&
  4060. !empty($groupBackup['user'][$teacherToAdd][$course_code])
  4061. ) {
  4062. foreach ($groupBackup['user'][$teacherToAdd][$course_code] as $data) {
  4063. GroupManager::subscribe_users(
  4064. $teacherToAdd,
  4065. $data['group_id'],
  4066. $data['c_id']
  4067. );
  4068. }
  4069. }
  4070. if (isset($groupBackup['tutor'][$teacherToAdd]) &&
  4071. isset($groupBackup['tutor'][$teacherToAdd][$course_code]) &&
  4072. !empty($groupBackup['tutor'][$teacherToAdd][$course_code])
  4073. ) {
  4074. foreach ($groupBackup['tutor'][$teacherToAdd][$course_code] as $data) {
  4075. GroupManager::subscribe_tutors(
  4076. $teacherToAdd,
  4077. $data['group_id'],
  4078. $data['c_id']
  4079. );
  4080. }
  4081. }
  4082. }
  4083. }
  4084. // See BT#6449#note-195
  4085. // All coaches are added.
  4086. if ($removeAllTeachersFromCourse) {
  4087. $teacherToAdd = null;
  4088. foreach ($course_coaches as $course_coach) {
  4089. $coach_id = UserManager::get_user_id_from_username(
  4090. $course_coach
  4091. );
  4092. if ($coach_id !== false) {
  4093. $teacherToAdd[] = $coach_id;
  4094. }
  4095. }
  4096. if (!empty($teacherToAdd)) {
  4097. // Deleting all course teachers and adding the only coach as teacher.
  4098. $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
  4099. if (!empty($teacherList)) {
  4100. foreach ($teacherList as $teacher) {
  4101. if (!in_array($teacher['user_id'], $teacherToAdd)) {
  4102. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  4103. WHERE
  4104. user_id = ".$teacher['user_id']." AND
  4105. course_code = '".$course_code."'
  4106. ";
  4107. $result = Database::query($sql);
  4108. $userCourseData = Database::fetch_array($result, 'ASSOC');
  4109. $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
  4110. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  4111. WHERE
  4112. user_id = ".$teacher['user_id']." AND
  4113. c_id = '".$courseInfo['real_id']."'
  4114. ";
  4115. $result = Database::query($sql);
  4116. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4117. $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4118. }
  4119. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  4120. WHERE
  4121. user_id = ".$teacher['user_id']." AND
  4122. c_id = '".$courseInfo['real_id']."'
  4123. ";
  4124. $result = Database::query($sql);
  4125. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  4126. $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
  4127. }
  4128. CourseManager::unsubscribe_user(
  4129. $teacher['user_id'],
  4130. $course_code
  4131. );
  4132. }
  4133. }
  4134. }
  4135. foreach ($teacherToAdd as $teacherId) {
  4136. $userCourseCategory = '';
  4137. if (isset($teacherBackupList[$teacherId]) &&
  4138. isset($teacherBackupList[$teacherId][$course_code])
  4139. ) {
  4140. $courseUserData = $teacherBackupList[$teacherId][$course_code];
  4141. $userCourseCategory = $courseUserData['user_course_cat'];
  4142. }
  4143. CourseManager::subscribe_user(
  4144. $teacherId,
  4145. $course_code,
  4146. COURSEMANAGER,
  4147. 0,
  4148. $userCourseCategory
  4149. );
  4150. if (isset($groupBackup['user'][$teacherId]) &&
  4151. isset($groupBackup['user'][$teacherId][$course_code]) &&
  4152. !empty($groupBackup['user'][$teacherId][$course_code])
  4153. ) {
  4154. foreach ($groupBackup['user'][$teacherId][$course_code] as $data) {
  4155. GroupManager::subscribe_users(
  4156. $teacherId,
  4157. $data['group_id'],
  4158. $data['c_id']
  4159. );
  4160. }
  4161. }
  4162. if (isset($groupBackup['tutor'][$teacherId]) &&
  4163. isset($groupBackup['tutor'][$teacherId][$course_code]) &&
  4164. !empty($groupBackup['tutor'][$teacherId][$course_code])
  4165. ) {
  4166. foreach ($groupBackup['tutor'][$teacherId][$course_code] as $data) {
  4167. GroupManager::subscribe_tutors(
  4168. $teacherId,
  4169. $data['group_id'],
  4170. $data['c_id']
  4171. );
  4172. }
  4173. }
  4174. }
  4175. }
  4176. }
  4177. // Continue default behaviour.
  4178. if ($onlyAddFirstCoachOrTeacher == false) {
  4179. // Checking one more time see BT#6449#note-149
  4180. $coaches = SessionManager::getCoachesByCourseSession($session_id, $courseId);
  4181. // Update coaches if only there's 1 course see BT#6449#note-189
  4182. if (empty($coaches) || count($courses) == 1) {
  4183. foreach ($course_coaches as $course_coach) {
  4184. $course_coach = trim($course_coach);
  4185. $coach_id = UserManager::get_user_id_from_username($course_coach);
  4186. if ($coach_id !== false) {
  4187. // Just insert new coaches
  4188. SessionManager::updateCoaches(
  4189. $session_id,
  4190. $courseId,
  4191. array($coach_id),
  4192. false
  4193. );
  4194. if ($debug) {
  4195. $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  4196. }
  4197. $savedCoaches[] = $coach_id;
  4198. } else {
  4199. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  4200. }
  4201. }
  4202. }
  4203. }
  4204. }
  4205. // Adding Students, updating relationship "Session - Course - User".
  4206. $course_users = array_filter($course_users);
  4207. if (!empty($course_users)) {
  4208. foreach ($course_users as $user) {
  4209. $user_id = UserManager::get_user_id_from_username($user);
  4210. if ($user_id !== false) {
  4211. SessionManager::subscribe_users_to_session_course(
  4212. array($user_id),
  4213. $session_id,
  4214. $course_code
  4215. );
  4216. if ($debug) {
  4217. $logger->addInfo("Sessions - Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
  4218. }
  4219. } else {
  4220. $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
  4221. }
  4222. }
  4223. }
  4224. $inserted_in_course[$course_code] = $courseInfo['title'];
  4225. }
  4226. }
  4227. $access_url_id = api_get_current_access_url_id();
  4228. UrlManager::add_session_to_url($session_id, $access_url_id);
  4229. $sql = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter' WHERE id = '$session_id'";
  4230. Database::query($sql);
  4231. }
  4232. }
  4233. return array(
  4234. 'error_message' => $error_message,
  4235. 'session_counter' => $session_counter,
  4236. 'session_list' => $sessionList,
  4237. );
  4238. }
  4239. /**
  4240. * @param int $sessionId
  4241. * @param int $courseId
  4242. * @return array
  4243. */
  4244. public static function getCoachesByCourseSession($sessionId, $courseId)
  4245. {
  4246. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4247. $sessionId = intval($sessionId);
  4248. $courseId = intval($courseId);
  4249. $sql = "SELECT user_id FROM $table
  4250. WHERE
  4251. session_id = '$sessionId' AND
  4252. c_id = '$courseId' AND
  4253. status = 2";
  4254. $result = Database::query($sql);
  4255. $coaches = array();
  4256. if (Database::num_rows($result) > 0) {
  4257. while ($row = Database::fetch_row($result)) {
  4258. $coaches[] = $row[0];
  4259. }
  4260. }
  4261. return $coaches;
  4262. }
  4263. /**
  4264. * @param int $sessionId
  4265. * @param int $courseId
  4266. * @return string
  4267. */
  4268. public static function getCoachesByCourseSessionToString(
  4269. $sessionId,
  4270. $courseId
  4271. ) {
  4272. $coaches = self::getCoachesByCourseSession($sessionId, $courseId);
  4273. $list = array();
  4274. if (!empty($coaches)) {
  4275. foreach ($coaches as $coachId) {
  4276. $userInfo = api_get_user_info($coachId);
  4277. $list[] = api_get_person_name(
  4278. $userInfo['firstname'],
  4279. $userInfo['lastname']
  4280. );
  4281. }
  4282. }
  4283. return array_to_string($list, CourseManager::USER_SEPARATOR);
  4284. }
  4285. /**
  4286. * Get all coaches added in the session - course relationship
  4287. * @param int $sessionId
  4288. * @return array
  4289. */
  4290. public static function getCoachesBySession($sessionId)
  4291. {
  4292. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4293. $sessionId = intval($sessionId);
  4294. $sql = "SELECT DISTINCT user_id
  4295. FROM $table
  4296. WHERE session_id = '$sessionId' AND status = 2";
  4297. $result = Database::query($sql);
  4298. $coaches = array();
  4299. if (Database::num_rows($result) > 0) {
  4300. while ($row = Database::fetch_array($result)) {
  4301. $coaches[] = $row['user_id'];
  4302. }
  4303. }
  4304. return $coaches;
  4305. }
  4306. /**
  4307. * @param int $userId
  4308. * @return array
  4309. */
  4310. public static function getAllCoursesFromAllSessionFromDrh($userId)
  4311. {
  4312. $sessions = SessionManager::get_sessions_followed_by_drh($userId);
  4313. $coursesFromSession = array();
  4314. if (!empty($sessions)) {
  4315. foreach ($sessions as $session) {
  4316. $courseList = SessionManager::get_course_list_by_session_id($session['id']);
  4317. foreach ($courseList as $course) {
  4318. $coursesFromSession[] = $course['code'];
  4319. }
  4320. }
  4321. }
  4322. return $coursesFromSession;
  4323. }
  4324. /**
  4325. * @param string $status
  4326. * @param int $userId
  4327. * @param bool $getCount
  4328. * @param int $from
  4329. * @param int $numberItems
  4330. * @param int $column
  4331. * @param string $direction
  4332. * @param string $keyword
  4333. * @param string $active
  4334. * @param string $lastConnectionDate
  4335. * @param array $sessionIdList
  4336. * @param array $studentIdList
  4337. * @param int $filterByStatus
  4338. * @return array|int
  4339. */
  4340. public static function getAllUsersFromCoursesFromAllSessionFromStatus(
  4341. $status,
  4342. $userId,
  4343. $getCount = false,
  4344. $from = null,
  4345. $numberItems = null,
  4346. $column = 1,
  4347. $direction = 'asc',
  4348. $keyword = null,
  4349. $active = null,
  4350. $lastConnectionDate = null,
  4351. $sessionIdList = array(),
  4352. $studentIdList = array(),
  4353. $filterByStatus = null
  4354. ) {
  4355. $filterByStatus = intval($filterByStatus);
  4356. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  4357. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  4358. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  4359. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4360. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4361. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4362. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  4363. $direction = in_array(strtolower($direction), array('asc', 'desc')) ? $direction : 'asc';
  4364. $column = Database::escape_string($column);
  4365. $userId = intval($userId);
  4366. $limitCondition = null;
  4367. if (isset($from) && isset($numberItems)) {
  4368. $from = intval($from);
  4369. $numberItems = intval($numberItems);
  4370. $limitCondition = "LIMIT $from, $numberItems";
  4371. }
  4372. $urlId = api_get_current_access_url_id();
  4373. $sessionConditions = null;
  4374. $courseConditions = null;
  4375. $userConditions = null;
  4376. if (isset($active)) {
  4377. $active = intval($active);
  4378. $userConditions .= " AND active = $active";
  4379. }
  4380. switch ($status) {
  4381. case 'drh':
  4382. // Classic DRH
  4383. if (empty($studentIdList)) {
  4384. $studentListSql = UserManager::get_users_followed_by_drh(
  4385. $userId,
  4386. $filterByStatus,
  4387. true,
  4388. false
  4389. );
  4390. $studentIdList = array_keys($studentListSql);
  4391. $studentListSql = "'".implode("','", $studentIdList)."'";
  4392. } else {
  4393. $studentIdList = array_map('intval', $studentIdList);
  4394. $studentListSql = "'".implode("','", $studentIdList)."'";
  4395. }
  4396. if (!empty($studentListSql)) {
  4397. $userConditions = " AND u.user_id IN (".$studentListSql.") ";
  4398. }
  4399. break;
  4400. case 'drh_all':
  4401. // Show all by DRH
  4402. if (empty($sessionIdList)) {
  4403. $sessionsListSql = SessionManager::get_sessions_followed_by_drh(
  4404. $userId,
  4405. null,
  4406. null,
  4407. false,
  4408. true,
  4409. true
  4410. );
  4411. } else {
  4412. $sessionIdList = array_map('intval', $sessionIdList);
  4413. $sessionsListSql = "'".implode("','", $sessionIdList)."'";
  4414. }
  4415. if (!empty($sessionsListSql)) {
  4416. $sessionConditions = " AND s.id IN (".$sessionsListSql.") ";
  4417. }
  4418. break;
  4419. case 'session_admin';
  4420. $sessionConditions = " AND s.id_coach = $userId ";
  4421. break;
  4422. case 'admin':
  4423. break;
  4424. case 'teacher':
  4425. $sessionConditions = " AND s.id_coach = $userId ";
  4426. break;
  4427. }
  4428. $select = "SELECT DISTINCT u.* ";
  4429. $masterSelect = "SELECT DISTINCT * FROM ";
  4430. if ($getCount) {
  4431. $select = "SELECT DISTINCT u.user_id ";
  4432. $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
  4433. }
  4434. if (!empty($filterByStatus)) {
  4435. $userConditions .= " AND u.status = ".$filterByStatus;
  4436. }
  4437. if (!empty($lastConnectionDate)) {
  4438. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  4439. $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
  4440. }
  4441. if (!empty($keyword)) {
  4442. $keyword = Database::escape_string($keyword);
  4443. $userConditions .= " AND (
  4444. u.username LIKE '%$keyword%' OR
  4445. u.firstname LIKE '%$keyword%' OR
  4446. u.lastname LIKE '%$keyword%' OR
  4447. u.official_code LIKE '%$keyword%' OR
  4448. u.email LIKE '%$keyword%'
  4449. )";
  4450. }
  4451. $where = " WHERE
  4452. access_url_id = $urlId
  4453. $userConditions
  4454. ";
  4455. $sql = "$masterSelect (
  4456. ($select
  4457. FROM $tbl_session s
  4458. INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.session_id)
  4459. INNER JOIN $tbl_user u ON (u.user_id = su.user_id)
  4460. INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
  4461. $where
  4462. $sessionConditions
  4463. )
  4464. UNION (
  4465. $select
  4466. FROM $tbl_course c
  4467. INNER JOIN $tbl_course_user cu ON (cu.c_id = c.id)
  4468. INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
  4469. INNER JOIN $tbl_course_rel_access_url url ON (url.c_id = c.id)
  4470. $where
  4471. $courseConditions
  4472. )
  4473. ) as t1
  4474. ";
  4475. if ($getCount) {
  4476. $result = Database::query($sql);
  4477. $count = 0;
  4478. if (Database::num_rows($result)) {
  4479. $rows = Database::fetch_array($result);
  4480. $count = $rows['count'];
  4481. }
  4482. return $count;
  4483. }
  4484. if (!empty($column) && !empty($direction)) {
  4485. $column = str_replace('u.', '', $column);
  4486. $sql .= " ORDER BY $column $direction ";
  4487. }
  4488. $sql .= $limitCondition;
  4489. $result = Database::query($sql);
  4490. $result = Database::store_result($result);
  4491. return $result ;
  4492. }
  4493. /**
  4494. * @param int $sessionId
  4495. * @param int $courseId
  4496. * @param array $coachList
  4497. * @param bool $deleteCoachesNotInList
  4498. */
  4499. public static function updateCoaches(
  4500. $sessionId,
  4501. $courseId,
  4502. $coachList,
  4503. $deleteCoachesNotInList = false
  4504. ) {
  4505. $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseId);
  4506. if (!empty($coachList)) {
  4507. foreach ($coachList as $userId) {
  4508. self::set_coach_to_course_session($userId, $sessionId, $courseId);
  4509. }
  4510. }
  4511. if ($deleteCoachesNotInList) {
  4512. if (!empty($coachList)) {
  4513. $coachesToDelete = array_diff($currentCoaches, $coachList);
  4514. } else {
  4515. $coachesToDelete = $currentCoaches;
  4516. }
  4517. if (!empty($coachesToDelete)) {
  4518. foreach ($coachesToDelete as $userId) {
  4519. self::set_coach_to_course_session(
  4520. $userId,
  4521. $sessionId,
  4522. $courseId,
  4523. true
  4524. );
  4525. }
  4526. }
  4527. }
  4528. }
  4529. /**
  4530. * @param array $sessions
  4531. * @param array $sessionsDestination
  4532. * @return string
  4533. */
  4534. public static function copyStudentsFromSession($sessions, $sessionsDestination)
  4535. {
  4536. $messages = array();
  4537. if (!empty($sessions)) {
  4538. foreach ($sessions as $sessionId) {
  4539. $sessionInfo = self::fetch($sessionId);
  4540. $userList = self::get_users_by_session($sessionId, 0);
  4541. if (!empty($userList)) {
  4542. $newUserList = array();
  4543. $userToString = null;
  4544. foreach ($userList as $userInfo) {
  4545. $newUserList[] = $userInfo['user_id'];
  4546. $userToString .= $userInfo['firstname'] . ' ' . $userInfo['lastname'] . '<br />';
  4547. }
  4548. if (!empty($sessionsDestination)) {
  4549. foreach ($sessionsDestination as $sessionDestinationId) {
  4550. $sessionDestinationInfo = self::fetch($sessionDestinationId);
  4551. $messages[] = Display::return_message(
  4552. sprintf(get_lang('AddingStudentsFromSessionXToSessionY'), $sessionInfo['name'], $sessionDestinationInfo['name']), 'info', false
  4553. );
  4554. if ($sessionId == $sessionDestinationId) {
  4555. $messages[] = Display::return_message(sprintf(get_lang('SessionXSkipped'), $sessionDestinationId), 'warning', false);
  4556. continue;
  4557. }
  4558. $messages[] = Display::return_message(get_lang('StudentList') . '<br />' . $userToString, 'info', false);
  4559. SessionManager::suscribe_users_to_session(
  4560. $sessionDestinationId,
  4561. $newUserList,
  4562. SESSION_VISIBLE_READ_ONLY,
  4563. false
  4564. );
  4565. }
  4566. } else {
  4567. $messages[] = Display::return_message(get_lang('NoDestinationSessionProvided'), 'warning');
  4568. }
  4569. } else {
  4570. $messages[] = Display::return_message(
  4571. get_lang('NoStudentsFoundForSession').' #'.$sessionInfo['name'],
  4572. 'warning'
  4573. );
  4574. }
  4575. }
  4576. } else {
  4577. $messages[] = Display::return_message(get_lang('NoData'), 'warning');
  4578. }
  4579. return $messages;
  4580. }
  4581. /**
  4582. * Assign coaches of a session(s) as teachers to a given course (or courses)
  4583. * @param array A list of session IDs
  4584. * @param array A list of course IDs
  4585. * @return string
  4586. */
  4587. public static function copyCoachesFromSessionToCourse($sessions, $courses)
  4588. {
  4589. $coachesPerSession = array();
  4590. foreach ($sessions as $sessionId) {
  4591. $coaches = self::getCoachesBySession($sessionId);
  4592. $coachesPerSession[$sessionId] = $coaches;
  4593. }
  4594. $result = array();
  4595. if (!empty($courses)) {
  4596. foreach ($courses as $courseId) {
  4597. $courseInfo = api_get_course_info_by_id($courseId);
  4598. foreach ($coachesPerSession as $sessionId => $coachList) {
  4599. CourseManager::updateTeachers(
  4600. $courseInfo['real_id'], $coachList, false, false, false
  4601. );
  4602. $result[$courseInfo['code']][$sessionId] = $coachList;
  4603. }
  4604. }
  4605. }
  4606. $sessionUrl = api_get_path(WEB_CODE_PATH) . 'admin/resume_session.php?id_session=';
  4607. $htmlResult = null;
  4608. if (!empty($result)) {
  4609. foreach ($result as $courseCode => $data) {
  4610. $url = api_get_course_url($courseCode);
  4611. $htmlResult .= sprintf(
  4612. get_lang('CoachesSubscribedAsATeacherInCourseX'),
  4613. Display::url($courseCode, $url, array('target' => '_blank'))
  4614. );
  4615. foreach ($data as $sessionId => $coachList) {
  4616. $sessionInfo = self::fetch($sessionId);
  4617. $htmlResult .= '<br />';
  4618. $htmlResult .= Display::url(
  4619. get_lang('Session') . ': ' . $sessionInfo['name'] . ' <br />', $sessionUrl . $sessionId, array('target' => '_blank')
  4620. );
  4621. $teacherList = array();
  4622. foreach ($coachList as $coachId) {
  4623. $userInfo = api_get_user_info($coachId);
  4624. $teacherList[] = $userInfo['complete_name'];
  4625. }
  4626. if (!empty($teacherList)) {
  4627. $htmlResult .= implode(', ', $teacherList);
  4628. } else {
  4629. $htmlResult .= get_lang('NothingToAdd');
  4630. }
  4631. }
  4632. $htmlResult .= '<br />';
  4633. }
  4634. $htmlResult = Display::return_message($htmlResult, 'normal', false);
  4635. }
  4636. return $htmlResult;
  4637. }
  4638. /**
  4639. * @param string $keyword
  4640. * @param string $active
  4641. * @param string $lastConnectionDate
  4642. * @param array $sessionIdList
  4643. * @param array $studentIdList
  4644. * @param int $userStatus STUDENT|COURSEMANAGER constants
  4645. *
  4646. * @return array|int
  4647. */
  4648. public static function getCountUserTracking(
  4649. $keyword = null,
  4650. $active = null,
  4651. $lastConnectionDate = null,
  4652. $sessionIdList = array(),
  4653. $studentIdList = array(),
  4654. $filterUserStatus = null
  4655. ) {
  4656. $userId = api_get_user_id();
  4657. $drhLoaded = false;
  4658. if (api_is_drh()) {
  4659. if (api_drh_can_access_all_session_content()) {
  4660. $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
  4661. 'drh_all',
  4662. $userId,
  4663. true,
  4664. null,
  4665. null,
  4666. null,
  4667. null,
  4668. $keyword,
  4669. $active,
  4670. $lastConnectionDate,
  4671. $sessionIdList,
  4672. $studentIdList,
  4673. $filterUserStatus
  4674. );
  4675. $drhLoaded = true;
  4676. }
  4677. }
  4678. if ($drhLoaded == false) {
  4679. $count = UserManager::getUsersFollowedByUser(
  4680. $userId,
  4681. $filterUserStatus,
  4682. false,
  4683. false,
  4684. true,
  4685. null,
  4686. null,
  4687. null,
  4688. null,
  4689. $active,
  4690. $lastConnectionDate,
  4691. api_is_student_boss() ? STUDENT_BOSS : COURSEMANAGER,
  4692. $keyword
  4693. );
  4694. }
  4695. return $count;
  4696. }
  4697. /**
  4698. * Get teachers followed by a user
  4699. * @param int $userId
  4700. * @param int $active
  4701. * @param string $lastConnectionDate
  4702. * @param bool $getCount
  4703. * @param array $sessionIdList
  4704. * @return array|int
  4705. */
  4706. public static function getTeacherTracking(
  4707. $userId,
  4708. $active = 1,
  4709. $lastConnectionDate = null,
  4710. $getCount = false,
  4711. $sessionIdList = array()
  4712. ) {
  4713. $teacherListId = array();
  4714. if (api_is_drh() || api_is_platform_admin()) {
  4715. // Followed teachers by drh
  4716. if (api_drh_can_access_all_session_content()) {
  4717. if (empty($sessionIdList)) {
  4718. $sessions = SessionManager::get_sessions_followed_by_drh($userId);
  4719. $sessionIdList = array();
  4720. foreach ($sessions as $session) {
  4721. $sessionIdList[] = $session['id'];
  4722. }
  4723. }
  4724. $sessionIdList = array_map('intval', $sessionIdList);
  4725. $sessionToString = implode("', '", $sessionIdList);
  4726. $course = Database::get_main_table(TABLE_MAIN_COURSE);
  4727. $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  4728. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4729. // Select the teachers.
  4730. $sql = "SELECT DISTINCT(cu.user_id) FROM $course c
  4731. INNER JOIN $sessionCourse src ON c.id = src.c_id
  4732. INNER JOIN $courseUser cu ON (cu.c_id = c.id)
  4733. WHERE src.session_id IN ('$sessionToString') AND cu.status = 1";
  4734. $result = Database::query($sql);
  4735. while($row = Database::fetch_array($result, 'ASSOC')) {
  4736. $teacherListId[$row['user_id']] = $row['user_id'];
  4737. }
  4738. } else {
  4739. $teacherResult = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
  4740. foreach ($teacherResult as $userInfo) {
  4741. $teacherListId[] = $userInfo['user_id'];
  4742. }
  4743. }
  4744. }
  4745. if (!empty($teacherListId)) {
  4746. $tableUser = Database::get_main_table(TABLE_MAIN_USER);
  4747. $select = "SELECT DISTINCT u.* ";
  4748. if ($getCount) {
  4749. $select = "SELECT count(DISTINCT(u.user_id)) as count";
  4750. }
  4751. $sql = "$select FROM $tableUser u";
  4752. if (!empty($lastConnectionDate)) {
  4753. $tableLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  4754. //$sql .= " INNER JOIN $tableLogin l ON (l.login_user_id = u.user_id) ";
  4755. }
  4756. $active = intval($active);
  4757. $teacherListId = implode("','", $teacherListId);
  4758. $where = " WHERE u.active = $active AND u.user_id IN ('$teacherListId') ";
  4759. if (!empty($lastConnectionDate)) {
  4760. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  4761. //$where .= " AND l.login_date <= '$lastConnectionDate' ";
  4762. }
  4763. $sql .= $where;
  4764. $result = Database::query($sql);
  4765. if (Database::num_rows($result)) {
  4766. if ($getCount) {
  4767. $row = Database::fetch_array($result);
  4768. return $row['count'];
  4769. } else {
  4770. return Database::store_result($result, 'ASSOC');
  4771. }
  4772. }
  4773. }
  4774. return 0;
  4775. }
  4776. /**
  4777. * Get the list of course tools that have to be dealt with in case of
  4778. * registering any course to a session
  4779. * @return array The list of tools to be dealt with (literal names)
  4780. */
  4781. public static function getCourseToolToBeManaged()
  4782. {
  4783. return array(
  4784. 'courseDescription',
  4785. 'courseIntroduction',
  4786. );
  4787. }
  4788. /**
  4789. * Calls the methods bound to each tool when a course is registered into a session
  4790. * @param int $sessionId
  4791. * @param int $courseId
  4792. * @return void
  4793. */
  4794. public static function installCourse($sessionId, $courseId)
  4795. {
  4796. return true;
  4797. $toolList = self::getCourseToolToBeManaged();
  4798. foreach ($toolList as $tool) {
  4799. $method = 'add' . $tool;
  4800. if (method_exists(get_class(), $method)) {
  4801. self::$method($sessionId, $courseId);
  4802. }
  4803. }
  4804. }
  4805. /**
  4806. * Calls the methods bound to each tool when a course is unregistered from
  4807. * a session
  4808. * @param int $sessionId
  4809. * @param int $courseId
  4810. */
  4811. public static function unInstallCourse($sessionId, $courseId)
  4812. {
  4813. return true;
  4814. $toolList = self::getCourseToolToBeManaged();
  4815. foreach ($toolList as $tool) {
  4816. $method = 'remove' . $tool;
  4817. if (method_exists(get_class(), $method)) {
  4818. self::$method($sessionId, $courseId);
  4819. }
  4820. }
  4821. }
  4822. /**
  4823. * @param int $sessionId
  4824. * @param int $courseId
  4825. */
  4826. public static function addCourseIntroduction($sessionId, $courseId)
  4827. {
  4828. // @todo create a tool intro lib
  4829. $sessionId = intval($sessionId);
  4830. $courseId = intval($courseId);
  4831. $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
  4832. $sql = "SELECT * FROM $TBL_INTRODUCTION WHERE c_id = $courseId";
  4833. $result = Database::query($sql);
  4834. $result = Database::store_result($result, 'ASSOC');
  4835. if (!empty($result)) {
  4836. foreach ($result as $result) {
  4837. // @todo check if relation exits.
  4838. $result['session_id'] = $sessionId;
  4839. Database::insert($TBL_INTRODUCTION, $result);
  4840. }
  4841. }
  4842. }
  4843. /**
  4844. * @param int $sessionId
  4845. * @param int $courseId
  4846. */
  4847. public static function removeCourseIntroduction($sessionId, $courseId)
  4848. {
  4849. $sessionId = intval($sessionId);
  4850. $courseId = intval($courseId);
  4851. $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
  4852. $sql = "DELETE FROM $TBL_INTRODUCTION
  4853. WHERE c_id = $courseId AND session_id = $sessionId";
  4854. Database::query($sql);
  4855. }
  4856. /**
  4857. * @param int $sessionId
  4858. * @param int $courseId
  4859. */
  4860. public static function addCourseDescription($sessionId, $courseId)
  4861. {
  4862. /* $description = new CourseDescription();
  4863. $descriptions = $description->get_descriptions($courseId);
  4864. foreach ($descriptions as $description) {
  4865. } */
  4866. }
  4867. /**
  4868. * @param int $sessionId
  4869. * @param int $courseId
  4870. */
  4871. public static function removeCourseDescription($sessionId, $courseId)
  4872. {
  4873. }
  4874. /**
  4875. * @param array $userSessionList format see self::importSessionDrhCSV()
  4876. * @param bool $sendEmail
  4877. * @param bool $removeOldRelationShips
  4878. * @return string
  4879. */
  4880. public static function subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips)
  4881. {
  4882. if (!empty($userSessionList)) {
  4883. foreach ($userSessionList as $userId => $data) {
  4884. $sessionList = array();
  4885. foreach ($data['session_list'] as $sessionInfo) {
  4886. $sessionList[] = $sessionInfo['session_id'];
  4887. }
  4888. $userInfo = $data['user_info'];
  4889. self::suscribe_sessions_to_hr_manager(
  4890. $userInfo,
  4891. $sessionList,
  4892. $sendEmail,
  4893. $removeOldRelationShips
  4894. );
  4895. }
  4896. }
  4897. }
  4898. /**
  4899. * @param array $userSessionList format see self::importSessionDrhCSV()
  4900. *
  4901. * @return string
  4902. */
  4903. public static function checkSubscribeDrhToSessionList($userSessionList)
  4904. {
  4905. $message = null;
  4906. if (!empty($userSessionList)) {
  4907. if (!empty($userSessionList)) {
  4908. foreach ($userSessionList as $userId => $data) {
  4909. $userInfo = $data['user_info'];
  4910. $sessionListSubscribed = self::get_sessions_followed_by_drh($userId);
  4911. if (!empty($sessionListSubscribed)) {
  4912. $sessionListSubscribed = array_keys($sessionListSubscribed);
  4913. }
  4914. $sessionList = array();
  4915. if (!empty($data['session_list'])) {
  4916. foreach ($data['session_list'] as $sessionInfo) {
  4917. if (in_array($sessionInfo['session_id'], $sessionListSubscribed)) {
  4918. $sessionList[] = $sessionInfo['session_info']['name'];
  4919. }
  4920. }
  4921. }
  4922. $message .= '<strong>' . get_lang('User') . '</strong> ' . $userInfo['complete_name'] . ' <br />';
  4923. if (!in_array($userInfo['status'], array(DRH)) && !api_is_platform_admin_by_id($userInfo['user_id'])) {
  4924. $message .= get_lang('UserMustHaveTheDrhRole') . '<br />';
  4925. continue;
  4926. }
  4927. if (!empty($sessionList)) {
  4928. $message .= '<strong>' . get_lang('Sessions') . ':</strong> <br />';
  4929. $message .= implode(', ', $sessionList) . '<br /><br />';
  4930. } else {
  4931. $message .= get_lang('NoSessionProvided') . ' <br /><br />';
  4932. }
  4933. }
  4934. }
  4935. }
  4936. return $message;
  4937. }
  4938. /**
  4939. * @param string $file
  4940. * @param bool $sendEmail
  4941. * @param bool $removeOldRelationShips
  4942. *
  4943. * @return string
  4944. */
  4945. public static function importSessionDrhCSV($file, $sendEmail, $removeOldRelationShips)
  4946. {
  4947. $list = Import::csv_reader($file);
  4948. if (!empty($list)) {
  4949. $userSessionList = array();
  4950. foreach ($list as $data) {
  4951. $userInfo = api_get_user_info_from_username($data['Username']);
  4952. $sessionInfo = self::get_session_by_name($data['SessionName']);
  4953. if (!empty($userInfo) && !empty($sessionInfo)) {
  4954. $userSessionList[$userInfo['user_id']]['session_list'][] = array(
  4955. 'session_id' => $sessionInfo['id'],
  4956. 'session_info' => $sessionInfo,
  4957. );
  4958. $userSessionList[$userInfo['user_id']]['user_info'] = $userInfo;
  4959. }
  4960. }
  4961. self::subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips);
  4962. return self::checkSubscribeDrhToSessionList($userSessionList);
  4963. }
  4964. }
  4965. /**
  4966. * Courses re-ordering in resume_session.php flag see BT#8316
  4967. */
  4968. public static function orderCourseIsEnabled()
  4969. {
  4970. $sessionCourseOrder = api_get_setting('session_course_ordering');
  4971. if ($sessionCourseOrder === 'true') {
  4972. return true;
  4973. }
  4974. return false;
  4975. }
  4976. /**
  4977. * @param string $direction (up/down)
  4978. * @param int $sessionId
  4979. * @param int $courseId
  4980. * @return bool
  4981. */
  4982. public static function move($direction, $sessionId, $courseId)
  4983. {
  4984. if (!self::orderCourseIsEnabled()) {
  4985. return false;
  4986. }
  4987. $sessionId = intval($sessionId);
  4988. $courseId = intval($courseId);
  4989. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  4990. $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
  4991. $position = array();
  4992. $count = 0;
  4993. foreach ($courseList as $course) {
  4994. if ($course['position'] == '') {
  4995. $course['position'] = $count;
  4996. }
  4997. $position[$course['code']] = $course['position'];
  4998. // Saving current order.
  4999. $sql = "UPDATE $table SET position = $count
  5000. WHERE session_id = $sessionId AND c_id = '".$course['real_id']."'";
  5001. Database::query($sql);
  5002. $count++;
  5003. }
  5004. // Loading new positions.
  5005. $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
  5006. $found = false;
  5007. switch ($direction) {
  5008. case 'up':
  5009. $courseList = array_reverse($courseList);
  5010. break;
  5011. case 'down':
  5012. break;
  5013. }
  5014. foreach ($courseList as $course) {
  5015. if ($found) {
  5016. $nextId = $course['real_id'];
  5017. $nextOrder = $course['position'];
  5018. break;
  5019. }
  5020. if ($courseId == $course['real_id']) {
  5021. $thisCourseCode = $course['real_id'];
  5022. $thisOrder = $course['position'];
  5023. $found = true;
  5024. }
  5025. }
  5026. $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."'
  5027. WHERE session_id = $sessionId AND c_id = $thisCourseCode";
  5028. Database::query($sql1);
  5029. $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."'
  5030. WHERE session_id = $sessionId AND c_id = $nextId";
  5031. Database::query($sql2);
  5032. return true;
  5033. }
  5034. /**
  5035. * @param int $sessionId
  5036. * @param int $courseId
  5037. * @return bool
  5038. */
  5039. public static function moveUp($sessionId, $courseId)
  5040. {
  5041. return self::move('up', $sessionId, $courseId);
  5042. }
  5043. /**
  5044. * @param int $sessionId
  5045. * @param string $courseCode
  5046. * @return bool
  5047. */
  5048. public static function moveDown($sessionId, $courseCode)
  5049. {
  5050. return self::move('down', $sessionId, $courseCode);
  5051. }
  5052. /**
  5053. * Use the session duration to allow/block user access see BT#8317
  5054. * Needs these DB changes
  5055. * ALTER TABLE session ADD COLUMN duration int;
  5056. * ALTER TABLE session_rel_user ADD COLUMN duration int;
  5057. */
  5058. public static function durationPerUserIsEnabled()
  5059. {
  5060. return api_get_configuration_value('session_duration_feature');
  5061. }
  5062. /**
  5063. * Returns the number of days the student has left in a session when using
  5064. * sessions durations
  5065. * @param int $userId
  5066. * @param int $sessionId
  5067. * @param int $duration in days
  5068. * @return int
  5069. */
  5070. public static function getDayLeftInSession($sessionId, $userId, $duration)
  5071. {
  5072. // Get an array with the details of the first access of the student to
  5073. // this session
  5074. $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
  5075. $sessionId,
  5076. $userId
  5077. );
  5078. $currentTime = time();
  5079. // If no previous access, return false
  5080. if (count($courseAccess) == 0) {
  5081. return false;
  5082. }
  5083. $firstAccess = api_strtotime($courseAccess['login_course_date'], 'UTC');
  5084. $endDateInSeconds = $firstAccess + $duration*24*60*60;
  5085. $leftDays = round(($endDateInSeconds- $currentTime) / 60 / 60 / 24);
  5086. return $leftDays;
  5087. }
  5088. /**
  5089. * @param int $duration
  5090. * @param int $userId
  5091. * @param int $sessionId
  5092. */
  5093. public static function editUserSessionDuration($duration, $userId, $sessionId)
  5094. {
  5095. $duration = intval($duration);
  5096. $userId = intval($userId);
  5097. $sessionId = intval($sessionId);
  5098. if (empty($userId) || empty($sessionId)) {
  5099. return false;
  5100. }
  5101. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  5102. $parameters = array('duration' => $duration);
  5103. $where = array('session_id = ? AND user_id = ? ' => array($sessionId, $userId));
  5104. Database::update($table, $parameters, $where);
  5105. }
  5106. /**
  5107. * Gets one row from the session_rel_user table
  5108. * @param int $userId
  5109. * @param int $sessionId
  5110. *
  5111. * @return array
  5112. */
  5113. public static function getUserSession($userId, $sessionId)
  5114. {
  5115. $userId = intval($userId);
  5116. $sessionId = intval($sessionId);
  5117. if (empty($userId) || empty($sessionId)) {
  5118. return false;
  5119. }
  5120. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  5121. $sql = "SELECT * FROM $table
  5122. WHERE session_id = $sessionId AND user_id = $userId";
  5123. $result = Database::query($sql);
  5124. $values = array();
  5125. if (Database::num_rows($result)) {
  5126. $values = Database::fetch_array($result, 'ASSOC');
  5127. }
  5128. return $values;
  5129. }
  5130. /**
  5131. * Check if user is subscribed inside a session as student
  5132. * @param int $sessionId The session id
  5133. * @param int $userId The user id
  5134. * @return boolean Whether is subscribed
  5135. */
  5136. public static function isUserSubscribedAsStudent($sessionId, $userId)
  5137. {
  5138. $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  5139. $sessionId = intval($sessionId);
  5140. $userId = intval($userId);
  5141. // COUNT(1) actually returns the number of rows from the table (as if
  5142. // counting the results from the first column)
  5143. $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
  5144. WHERE
  5145. session_id = $sessionId AND
  5146. user_id = $userId AND
  5147. relation_type = 0";
  5148. $result = Database::fetch_assoc(Database::query($sql));
  5149. if (!empty($result) && $result['qty'] > 0) {
  5150. return true;
  5151. }
  5152. return false;
  5153. }
  5154. /**
  5155. * Get the session coached by a user (general coach and course-session coach)
  5156. * @param int $coachId The coach id
  5157. * @param boolean $checkSessionRelUserVisibility Check the session visibility
  5158. * @param boolean $asPlatformAdmin The user is a platform admin and we want all sessions
  5159. * @return array The session list
  5160. */
  5161. public static function getSessionsCoachedByUser($coachId, $checkSessionRelUserVisibility = false, $asPlatformAdmin = false)
  5162. {
  5163. // Get all sessions where $coachId is the general coach
  5164. $sessions = self::get_sessions_by_general_coach($coachId, $asPlatformAdmin);
  5165. // Get all sessions where $coachId is the course - session coach
  5166. $courseSessionList = self::getCoursesListByCourseCoach($coachId);
  5167. $sessionsByCoach = array();
  5168. if (!empty($courseSessionList)) {
  5169. foreach ($courseSessionList as $userCourseSubscription) {
  5170. $session = $userCourseSubscription->getSession();
  5171. $sessionsByCoach[$session->getId()] = api_get_session_info(
  5172. $session->getId()
  5173. );
  5174. }
  5175. }
  5176. if (!empty($sessionsByCoach)) {
  5177. $sessions = array_merge($sessions, $sessionsByCoach);
  5178. }
  5179. // Remove repeated sessions
  5180. if (!empty($sessions)) {
  5181. $cleanSessions = array();
  5182. foreach ($sessions as $session) {
  5183. $cleanSessions[$session['id']] = $session;
  5184. }
  5185. $sessions = $cleanSessions;
  5186. }
  5187. if ($checkSessionRelUserVisibility) {
  5188. if (!empty($sessions)) {
  5189. $newSessions = array();
  5190. foreach ($sessions as $session) {
  5191. $visibility = api_get_session_visibility($session['id']);
  5192. if ($visibility == SESSION_INVISIBLE) {
  5193. continue;
  5194. }
  5195. $newSessions[] = $session;
  5196. }
  5197. $sessions = $newSessions;
  5198. }
  5199. }
  5200. return $sessions;
  5201. }
  5202. /**
  5203. * Check if the course belongs to the session
  5204. * @param int $sessionId The session id
  5205. * @param string $courseCode The course code
  5206. *
  5207. * @return bool
  5208. */
  5209. public static function sessionHasCourse($sessionId, $courseCode)
  5210. {
  5211. $sessionId = intval($sessionId);
  5212. $courseCode = Database::escape_string($courseCode);
  5213. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  5214. $sessionRelCourseTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  5215. $sql = "SELECT COUNT(1) AS qty
  5216. FROM $courseTable c
  5217. INNER JOIN $sessionRelCourseTable src
  5218. ON c.id = src.c_id
  5219. WHERE src.session_id = $sessionId
  5220. AND c.code = '$courseCode' ";
  5221. $result = Database::query($sql);
  5222. if ($result !== false) {
  5223. $data = Database::fetch_assoc($result);
  5224. if ($data['qty'] > 0) {
  5225. return true;
  5226. }
  5227. }
  5228. return false;
  5229. }
  5230. /**
  5231. * Get the list of course coaches
  5232. * @return array The list
  5233. */
  5234. public static function getAllCourseCoaches()
  5235. {
  5236. $coaches = array();
  5237. $scuTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5238. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  5239. $idResult = Database::select('DISTINCT user_id', $scuTable, array(
  5240. 'where' => array(
  5241. 'status = ?' => 2,
  5242. ),
  5243. ));
  5244. if ($idResult != false) {
  5245. foreach ($idResult as $idData) {
  5246. $userResult = Database::select('user_id, lastname, firstname, username', $userTable, array(
  5247. 'where' => array(
  5248. 'user_id = ?' => $idData['user_id'],
  5249. ),
  5250. ), 'first');
  5251. if ($userResult != false) {
  5252. $coaches[] = array(
  5253. 'id' => $userResult['user_id'],
  5254. 'lastname' => $userResult['lastname'],
  5255. 'firstname' => $userResult['firstname'],
  5256. 'username' => $userResult['username'],
  5257. 'completeName' => api_get_person_name(
  5258. $userResult['firstname'],
  5259. $userResult['lastname']
  5260. ),
  5261. );
  5262. }
  5263. }
  5264. }
  5265. return $coaches;
  5266. }
  5267. /**
  5268. * Calculate the total user time in the platform
  5269. * @param int $userId The user id
  5270. * @param string $from Optional. From date
  5271. * @param string $until Optional. Until date
  5272. * @return string The time (hh:mm:ss)
  5273. */
  5274. public static function getTotalUserTimeInPlatform($userId, $from = '', $until = '')
  5275. {
  5276. $userId = intval($userId);
  5277. $trackLoginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  5278. $whereConditions = array(
  5279. 'login_user_id = ? ' => $userId,
  5280. );
  5281. if (!empty($from) && !empty($until)) {
  5282. $whereConditions["AND (login_date >= '?' "] = $from;
  5283. $whereConditions["AND logout_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
  5284. }
  5285. $trackResult = Database::select(
  5286. 'SEC_TO_TIME(SUM(UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date))) as total_time',
  5287. $trackLoginTable,
  5288. array(
  5289. 'where' => $whereConditions,
  5290. ), 'first'
  5291. );
  5292. if ($trackResult != false) {
  5293. return $trackResult['total_time'] ? $trackResult['total_time'] : '00:00:00';
  5294. }
  5295. return '00:00:00';
  5296. }
  5297. /**
  5298. * Get the courses list by a course coach
  5299. * @param int $coachId The coach id
  5300. * @return array (id, user_id, session_id, c_id, visibility, status, legal_agreement)
  5301. */
  5302. public static function getCoursesListByCourseCoach($coachId)
  5303. {
  5304. $entityManager = Database::getManager();
  5305. $scuRepo = $entityManager->getRepository(
  5306. 'ChamiloCoreBundle:SessionRelCourseRelUser'
  5307. );
  5308. return $scuRepo->findBy([
  5309. 'user' => $coachId,
  5310. 'status' => SessionRelCourseRelUser::STATUS_COURSE_COACH
  5311. ]);
  5312. }
  5313. /**
  5314. * Get the count of user courses in session
  5315. * @param int $sessionId The session id
  5316. * @return array
  5317. */
  5318. public static function getTotalUserCoursesInSession($sessionId)
  5319. {
  5320. $tableUser = Database::get_main_table(TABLE_MAIN_USER);
  5321. $tableSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5322. $sql = "SELECT COUNT(1) as count, u.id, scu.status status_in_session, u.status user_status
  5323. FROM $tableSessionRelCourseRelUser scu
  5324. INNER JOIN $tableUser u ON scu.user_id = u.id
  5325. WHERE scu.session_id = " . intval($sessionId) ."
  5326. GROUP BY u.id";
  5327. $result = Database::query($sql);
  5328. $list = array();
  5329. while ($data = Database::fetch_assoc($result)) {
  5330. $list[] = $data;
  5331. }
  5332. return $list;
  5333. }
  5334. /**
  5335. * Returns list of a few data from session (name, short description, start
  5336. * date, end date) and the given extra fields if defined based on a
  5337. * session category Id.
  5338. * @param int $categoryId The internal ID of the session category
  5339. * @param string $target Value to search for in the session field values
  5340. * @param array $extraFields A list of fields to be scanned and returned
  5341. * @return mixed
  5342. */
  5343. public static function getShortSessionListAndExtraByCategory($categoryId, $target, $extraFields = null, $publicationDate = null)
  5344. {
  5345. // Init variables
  5346. $categoryId = (int) $categoryId;
  5347. $sessionList = array();
  5348. // Check if categoryId is valid
  5349. if ($categoryId > 0) {
  5350. $target = Database::escape_string($target);
  5351. $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
  5352. $sfTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  5353. $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  5354. // Join session field and session field values tables
  5355. $joinTable = $sfTable . ' sf INNER JOIN ' . $sfvTable . ' sfv ON sf.id = sfv.field_id';
  5356. $fieldsArray = array();
  5357. foreach ($extraFields as $field) {
  5358. $fieldsArray[] = Database::escape_string($field);
  5359. }
  5360. $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::SESSION_FIELD_TYPE;
  5361. if (isset ($publicationDate)) {
  5362. $publicationDateString = $publicationDate->format('Y-m-d H:i:s');
  5363. $wherePublication = " AND id NOT IN (
  5364. SELECT sfv.item_id FROM $joinTable
  5365. WHERE
  5366. sf.extra_field_type = $extraFieldType AND
  5367. ((sf.variable = 'publication_start_date' AND sfv.value > '$publicationDateString' and sfv.value != '') OR
  5368. (sf.variable = 'publication_end_date' AND sfv.value < '$publicationDateString' and sfv.value != ''))
  5369. )";
  5370. }
  5371. // Get the session list from session category and target
  5372. $sessionList = Database::select(
  5373. 'id, name, access_start_date, access_end_date',
  5374. $sTable,
  5375. array(
  5376. 'where' => array(
  5377. "session_category_id = ? AND id IN (
  5378. SELECT sfv.item_id FROM $joinTable
  5379. WHERE
  5380. sf.extra_field_type = $extraFieldType AND
  5381. sfv.item_id = session.id AND
  5382. sf.variable = 'target' AND
  5383. sfv.value = ?
  5384. ) $wherePublication" => array($categoryId, $target),
  5385. ),
  5386. )
  5387. );
  5388. $whereFieldVariables = array();
  5389. $whereFieldIds = array();
  5390. if (
  5391. is_array($fieldsArray) &&
  5392. count($fieldsArray) > 0
  5393. ) {
  5394. $whereParams = '?';
  5395. for ($i = 1; $i < count($fieldsArray); $i++) {
  5396. $whereParams .= ', ?';
  5397. }
  5398. $whereFieldVariables = ' variable IN ( ' . $whereParams .' )';
  5399. $whereFieldIds = 'field_id IN ( ' . $whereParams . ' )';
  5400. }
  5401. // Get session fields
  5402. $extraField = new ExtraField('session');
  5403. $questionMarks = substr(str_repeat('?, ', count($fieldsArray)), 0, -2);
  5404. $fieldsList = $extraField->get_all(array(
  5405. ' variable IN ( ' . $questionMarks . ' )' => $fieldsArray,
  5406. ));
  5407. // Index session fields
  5408. foreach ($fieldsList as $field) {
  5409. $fields[$field['id']] = $field['variable'];
  5410. }
  5411. // Get session field values
  5412. $extra = new ExtraFieldValue('session');
  5413. $questionMarksFields = substr(str_repeat('?, ', count($fields)), 0, -2);
  5414. $sessionFieldValueList = $extra->get_all(array ('where' => array('field_id IN ( ' . $questionMarksFields . ' )' => array_keys($fields))));
  5415. // Add session fields values to session list
  5416. foreach ($sessionList as $id => &$session) {
  5417. foreach ($sessionFieldValueList as $sessionFieldValue) {
  5418. // Match session field values to session
  5419. if ($sessionFieldValue['item_id'] == $id) {
  5420. // Check if session field value is set in session field list
  5421. if (isset($fields[$sessionFieldValue['field_id']])) {
  5422. // Avoid overwriting the session's ID field
  5423. if ($fields[$sessionFieldValue['field_id']] != 'id') {
  5424. $var = $fields[$sessionFieldValue['field_id']];
  5425. $val = $sessionFieldValue['value'];
  5426. // Assign session field value to session
  5427. $session[$var] = $val;
  5428. }
  5429. }
  5430. }
  5431. }
  5432. }
  5433. }
  5434. return $sessionList;
  5435. }
  5436. /**
  5437. * Return the Session Category id searched by name
  5438. * @param string $categoryName Name attribute of session category used for search query
  5439. * @param bool $force boolean used to get even if something is wrong (e.g not unique name)
  5440. * @return int|array If success, return category id (int), else it will return an array
  5441. * with the next structure:
  5442. * array('error' => true, 'errorMessage' => ERROR_MESSAGE)
  5443. */
  5444. public static function getSessionCategoryIdByName($categoryName, $force = false)
  5445. {
  5446. // Start error result
  5447. $errorResult = array('error' => true, 'errorMessage' => get_lang('ThereWasAnError'));
  5448. $categoryName = Database::escape_string($categoryName);
  5449. // Check if is not empty category name
  5450. if (!empty($categoryName)) {
  5451. $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  5452. // Get all session category with same name
  5453. $result = Database::select(
  5454. 'id',
  5455. $sessionCategoryTable,
  5456. array(
  5457. 'where' => array(
  5458. 'name = ?' => $categoryName,
  5459. ),
  5460. )
  5461. );
  5462. // Check the result
  5463. if ($result < 1) {
  5464. // If not found any result, update error message
  5465. $errorResult['errorMessage'] = 'Not found any session category name ' . $categoryName;
  5466. } elseif (count($result) > 1 && !$force) {
  5467. // If found more than one result and force is disabled, update error message
  5468. $errorResult['errorMessage'] = 'Found many session categories';
  5469. } elseif (count($result) == 1 || $force) {
  5470. // If found just one session category or force option is enabled
  5471. return key($result);
  5472. }
  5473. } else {
  5474. // category name is empty, update error message
  5475. $errorResult['errorMessage'] = 'Not valid category name';
  5476. }
  5477. return $errorResult;
  5478. }
  5479. /**
  5480. * Return all data from sessions (plus extra field, course and coach data) by category id
  5481. * @param int $sessionCategoryId session category id used to search sessions
  5482. * @return array If success, return session list and more session related data, else it will return an array
  5483. * with the next structure:
  5484. * array('error' => true, 'errorMessage' => ERROR_MESSAGE)
  5485. */
  5486. public static function getSessionListAndExtraByCategoryId($sessionCategoryId)
  5487. {
  5488. // Start error result
  5489. $errorResult = array(
  5490. 'error' => true,
  5491. 'errorMessage' => get_lang('ThereWasAnError'),
  5492. );
  5493. $sessionCategoryId = intval($sessionCategoryId);
  5494. // Check if session category id is valid
  5495. if ($sessionCategoryId > 0) {
  5496. // Get table names
  5497. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  5498. $sessionFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  5499. $sessionFieldValueTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  5500. $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5501. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  5502. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  5503. // Get all data from all sessions whit the session category specified
  5504. $sessionList = Database::select(
  5505. '*',
  5506. $sessionTable,
  5507. array(
  5508. 'where' => array(
  5509. 'session_category_id = ?' => $sessionCategoryId,
  5510. ),
  5511. )
  5512. );
  5513. $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::SESSION_FIELD_TYPE;
  5514. // Check if session list query had result
  5515. if (!empty($sessionList)) {
  5516. // implode all session id
  5517. $sessionIdsString = '(' . implode(', ', array_keys($sessionList)) . ')';
  5518. // Get all field variables
  5519. $sessionFieldList = Database::select(
  5520. 'id, variable',
  5521. $sessionFieldTable,
  5522. array('extra_field_type = ? ' => array($extraFieldType))
  5523. );
  5524. // Get all field values
  5525. $sql = "SELECT item_id, field_id, value FROM
  5526. $sessionFieldValueTable v INNER JOIN $sessionFieldTable f
  5527. ON (f.id = v.field_id)
  5528. WHERE
  5529. item_id IN $sessionIdsString AND
  5530. extra_field_type = $extraFieldType
  5531. ";
  5532. $result = Database::query($sql);
  5533. $sessionFieldValueList = Database::store_result($result, 'ASSOC');
  5534. // Check if session field values had result
  5535. if (!empty($sessionFieldValueList)) {
  5536. $sessionFieldValueListBySession = array();
  5537. foreach ($sessionFieldValueList as $key => $sessionFieldValue) {
  5538. // Create an array to index ids to session id
  5539. $sessionFieldValueListBySession[$sessionFieldValue['item_id']][] = $key;
  5540. }
  5541. }
  5542. // Query used to find course-coaches from sessions
  5543. $sql = "SELECT
  5544. scu.session_id,
  5545. c.id AS course_id,
  5546. c.code AS course_code,
  5547. c.title AS course_title,
  5548. u.username AS coach_username,
  5549. u.firstname AS coach_firstname,
  5550. u.lastname AS coach_lastname
  5551. FROM $courseTable c
  5552. INNER JOIN $sessionCourseUserTable scu ON c.id = scu.c_id
  5553. INNER JOIN $userTable u ON scu.user_id = u.user_id
  5554. WHERE scu.status = 2 AND scu.session_id IN $sessionIdsString
  5555. ORDER BY scu.session_id ASC ";
  5556. $res = Database::query($sql);
  5557. $sessionCourseList = Database::store_result($res, 'ASSOC');
  5558. // Check if course list had result
  5559. if (!empty($sessionCourseList)) {
  5560. foreach ($sessionCourseList as $key => $sessionCourse) {
  5561. // Create an array to index ids to session_id
  5562. $sessionCourseListBySession[$sessionCourse['session_id']][] = $key;
  5563. }
  5564. }
  5565. // Join lists
  5566. if (is_array($sessionList)) {
  5567. foreach ($sessionList as $id => &$row) {
  5568. if (
  5569. !empty($sessionFieldValueListBySession) &&
  5570. is_array($sessionFieldValueListBySession[$id])
  5571. ) {
  5572. // If have an index array for session extra fields, use it to join arrays
  5573. foreach ($sessionFieldValueListBySession[$id] as $key) {
  5574. $row['extra'][$key] = array(
  5575. 'field_name' => $sessionFieldList[$sessionFieldValueList[$key]['field_id']]['variable'],
  5576. 'value' => $sessionFieldValueList[$key]['value'],
  5577. );
  5578. }
  5579. }
  5580. if (
  5581. !empty($sessionCourseListBySession) &&
  5582. is_array($sessionCourseListBySession[$id])
  5583. ) {
  5584. // If have an index array for session course coach, use it to join arrays
  5585. foreach ($sessionCourseListBySession[$id] as $key) {
  5586. $row['course'][$key] = array(
  5587. 'course_id' => $sessionCourseList[$key]['course_id'],
  5588. 'course_code' => $sessionCourseList[$key]['course_code'],
  5589. 'course_title' => $sessionCourseList[$key]['course_title'],
  5590. 'coach_username' => $sessionCourseList[$key]['coach_username'],
  5591. 'coach_firstname' => $sessionCourseList[$key]['coach_firstname'],
  5592. 'coach_lastname' => $sessionCourseList[$key]['coach_lastname'],
  5593. );
  5594. }
  5595. }
  5596. }
  5597. }
  5598. return $sessionList;
  5599. } else {
  5600. // Not found result, update error message
  5601. $errorResult['errorMessage'] = 'Not found any session for session category id ' . $sessionCategoryId;
  5602. }
  5603. }
  5604. return $errorResult;
  5605. }
  5606. /**
  5607. * Return session description from session id
  5608. * @param int $sessionId
  5609. * @return string
  5610. */
  5611. public static function getDescriptionFromSessionId($sessionId)
  5612. {
  5613. // Init variables
  5614. $sessionId = intval($sessionId);
  5615. $description = '';
  5616. // Check if session id is valid
  5617. if ($sessionId > 0) {
  5618. // Select query from session id
  5619. $rows = Database::select(
  5620. 'description',
  5621. Database::get_main_table(TABLE_MAIN_SESSION),
  5622. array(
  5623. 'where' => array(
  5624. 'id = ?' => $sessionId,
  5625. ),
  5626. )
  5627. );
  5628. // Check if select query result is not empty
  5629. if (!empty($rows)) {
  5630. // Get session description
  5631. $description = $rows[0]['description'];
  5632. }
  5633. }
  5634. return $description;
  5635. }
  5636. /**
  5637. * Get a session list filtered by name, description or any of the given extra fields
  5638. * @param string $term The term to search
  5639. * @param array $extraFieldsToInclude Extra fields to include in the session data
  5640. * @return array The list
  5641. */
  5642. public static function searchSession($term, $extraFieldsToInclude = array())
  5643. {
  5644. $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
  5645. $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  5646. $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  5647. $term = Database::escape_string($term);
  5648. $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::SESSION_FIELD_TYPE;
  5649. if (is_array($extraFieldsToInclude) && count($extraFieldsToInclude) > 0) {
  5650. $resultData = Database::select('*', $sTable, array(
  5651. 'where' => array(
  5652. "name LIKE %?% " => $term,
  5653. " OR description LIKE %?% " => $term,
  5654. " OR id IN (
  5655. SELECT item_id
  5656. FROM $sfvTable v INNER JOIN $extraFieldTable e
  5657. ON (v.field_id = e.id)
  5658. WHERE value LIKE %?% AND extra_field_type = $extraFieldType
  5659. ) " => $term,
  5660. ),
  5661. ));
  5662. } else {
  5663. $resultData = Database::select('*', $sTable, array(
  5664. 'where' => array(
  5665. "name LIKE %?% " => $term,
  5666. "OR description LIKE %?% " => $term,
  5667. ),
  5668. ));
  5669. return $resultData;
  5670. }
  5671. foreach ($resultData as $id => &$session) {
  5672. $session['extra'] = self::getFilteredExtraFields($id, $extraFieldsToInclude);
  5673. }
  5674. return $resultData;
  5675. }
  5676. /**
  5677. * @param $sessionId
  5678. * @param array $extraFieldsToInclude
  5679. * @return array
  5680. */
  5681. public static function getFilteredExtraFields($sessionId, $extraFieldsToInclude = array())
  5682. {
  5683. $extraData = array();
  5684. $variables = array();
  5685. $variablePlaceHolders = array();
  5686. foreach ($extraFieldsToInclude as $sessionExtraField) {
  5687. $variablePlaceHolders[] = "?";
  5688. $variables[] = Database::escape_string($sessionExtraField);
  5689. }
  5690. $sessionExtraField = new ExtraField('session');
  5691. $fieldList = $sessionExtraField->get_all(array(
  5692. "variable IN ( " . implode(", ", $variablePlaceHolders) . " ) " => $variables,
  5693. ));
  5694. $fields = array();
  5695. // Index session fields
  5696. foreach ($fieldList as $field) {
  5697. $fields[$field['id']] = $field['variable'];
  5698. }
  5699. // Get session field values
  5700. $extra = new ExtraFieldValue('session');
  5701. $sessionFieldValueList = $extra->get_all(
  5702. array(
  5703. "field_id IN ( " . implode(", ", $variablePlaceHolders) . " )" => array_keys($fields),
  5704. )
  5705. );
  5706. foreach ($sessionFieldValueList as $sessionFieldValue) {
  5707. // Match session field values to session
  5708. if ($sessionFieldValue['item_id'] != $sessionId) {
  5709. continue;
  5710. }
  5711. // Check if session field value is set in session field list
  5712. if (!isset($fields[$sessionFieldValue['field_id']])) {
  5713. continue;
  5714. }
  5715. $extrafieldVariable = $fields[$sessionFieldValue['field_id']];
  5716. $extrafieldValue = $sessionFieldValue['value'];
  5717. $extraData[] = array(
  5718. 'variable' => $extrafieldVariable,
  5719. 'value' => $extrafieldValue,
  5720. );
  5721. }
  5722. return $extraData;
  5723. }
  5724. /**
  5725. * @param int $sessionId
  5726. *
  5727. * @return bool
  5728. */
  5729. public static function isValidId($sessionId)
  5730. {
  5731. $sessionId = intval($sessionId);
  5732. if ($sessionId > 0) {
  5733. $rows = Database::select(
  5734. 'id',
  5735. Database::get_main_table(TABLE_MAIN_SESSION),
  5736. array('where' => array('id = ?' => $sessionId))
  5737. );
  5738. if (!empty($rows)) {
  5739. return true;
  5740. }
  5741. }
  5742. return false;
  5743. }
  5744. /**
  5745. * Get list of sessions based on users of a group for a group admin
  5746. * @param int $userId The user id
  5747. * @return array
  5748. */
  5749. public static function getSessionsFollowedForGroupAdmin($userId)
  5750. {
  5751. $sessionList = array();
  5752. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  5753. $sessionUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  5754. $userGroup = new UserGroup();
  5755. $userIdList = $userGroup->getGroupUsersByUser($userId);
  5756. if (empty($userIdList)) {
  5757. return [];
  5758. }
  5759. $sql = "SELECT DISTINCT s.*
  5760. FROM $sessionTable s
  5761. INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
  5762. WHERE
  5763. (sru.id_user IN (" . implode(', ', $userIdList) . ")
  5764. AND sru.relation_type = 0
  5765. )";
  5766. if (api_is_multiple_url_enabled()) {
  5767. $sessionAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  5768. $accessUrlId = api_get_current_access_url_id();
  5769. if ($accessUrlId != -1) {
  5770. $sql = "SELECT DISTINCT s.*
  5771. FROM $sessionTable s
  5772. INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
  5773. INNER JOIN $sessionAccessUrlTable srau ON s.id = srau.session_id
  5774. WHERE
  5775. srau.access_url_id = $accessUrlId
  5776. AND (
  5777. sru.id_user IN (" . implode(', ', $userIdList) . ")
  5778. AND sru.relation_type = 0
  5779. )";
  5780. }
  5781. }
  5782. $result = Database::query($sql);
  5783. while ($row = Database::fetch_assoc($result)) {
  5784. $sessionList[] = $row;
  5785. }
  5786. return $sessionList;
  5787. }
  5788. /**
  5789. * @param array $sessionInfo
  5790. * @return string
  5791. */
  5792. public static function getSessionVisibility($sessionInfo)
  5793. {
  5794. switch($sessionInfo['visibility']) {
  5795. case 1:
  5796. return get_lang('ReadOnly');
  5797. case 2:
  5798. return get_lang('Visible');
  5799. case 3:
  5800. return api_ucfirst(get_lang('Invisible'));
  5801. }
  5802. }
  5803. /**
  5804. * Converts "start date" and "end date" to "From start date to end date" string
  5805. * @param string $startDate
  5806. * @param string $endDate
  5807. *
  5808. * @return string
  5809. */
  5810. private static function convertSessionDateToString($startDate, $endDate)
  5811. {
  5812. $startDateToLocal = '';
  5813. $endDateToLocal = '';
  5814. // This will clean the variables if 0000-00-00 00:00:00 the variable will be empty
  5815. if (isset($startDateToLocal)) {
  5816. $startDateToLocal = api_get_local_time($startDate, null, null, true);
  5817. }
  5818. if (isset($endDateToLocal)) {
  5819. $endDateToLocal = api_get_local_time($endDate, null, null, true);
  5820. }
  5821. $result = '';
  5822. if (!empty($startDateToLocal) && !empty($endDateToLocal)) {
  5823. $result = sprintf(get_lang('FromDateXToDateY'), $startDateToLocal, $endDateToLocal);
  5824. } else {
  5825. if (!empty($startDateToLocal)) {
  5826. $result = get_lang('From').' '.$startDateToLocal;
  5827. }
  5828. if (!empty($endDateToLocal)) {
  5829. $result = get_lang('Until').' '.$endDateToLocal;
  5830. }
  5831. }
  5832. if (empty($result)) {
  5833. $result = get_lang('NoTimeLimits');
  5834. }
  5835. return $result;
  5836. }
  5837. /**
  5838. * Returns a human readable string
  5839. * @params array $sessionInfo An array with all the session dates
  5840. * @return string
  5841. */
  5842. public static function parseSessionDates($sessionInfo)
  5843. {
  5844. $displayDates = self::convertSessionDateToString(
  5845. $sessionInfo['display_start_date'],
  5846. $sessionInfo['display_end_date']
  5847. );
  5848. $accessDates = self::convertSessionDateToString(
  5849. $sessionInfo['access_start_date'],
  5850. $sessionInfo['access_end_date']
  5851. );
  5852. $coachDates = self::convertSessionDateToString(
  5853. $sessionInfo['coach_access_start_date'],
  5854. $sessionInfo['coach_access_end_date']
  5855. );
  5856. $result = [
  5857. 'access' => $accessDates,
  5858. 'display' => $displayDates,
  5859. 'coach' => $coachDates,
  5860. ];
  5861. return $result;
  5862. }
  5863. /**
  5864. * @param FormValidator $form
  5865. *
  5866. * @return array
  5867. */
  5868. public static function setForm(FormValidator & $form, $sessionId = 0)
  5869. {
  5870. $categoriesList = SessionManager::get_all_session_category();
  5871. $userInfo = api_get_user_info();
  5872. $categoriesOptions = array(
  5873. '0' => get_lang('None'),
  5874. );
  5875. if ($categoriesList != false) {
  5876. foreach ($categoriesList as $categoryItem) {
  5877. $categoriesOptions[$categoryItem['id']] = $categoryItem['name'];
  5878. }
  5879. }
  5880. // Database Table Definitions
  5881. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  5882. $form->addElement('text', 'name', get_lang('SessionName'), array(
  5883. 'maxlength' => 50,
  5884. ));
  5885. $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
  5886. $form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
  5887. if (!api_is_platform_admin() && api_is_teacher()) {
  5888. $form->addElement(
  5889. 'select',
  5890. 'coach_username',
  5891. get_lang('CoachName'),
  5892. [api_get_user_id() => $userInfo['complete_name']],
  5893. array(
  5894. 'id' => 'coach_username',
  5895. 'style' => 'width:370px;',
  5896. )
  5897. );
  5898. } else {
  5899. $sql = "SELECT COUNT(1) FROM $tbl_user WHERE status = 1";
  5900. $rs = Database::query($sql);
  5901. $countUsers = Database::result($rs, 0, 0);
  5902. if (intval($countUsers) < 50) {
  5903. $orderClause = "ORDER BY ";
  5904. $orderClause .= api_sort_by_first_name() ? "firstname, lastname, username" : "lastname, firstname, username";
  5905. $sql = "SELECT user_id, lastname, firstname, username
  5906. FROM $tbl_user
  5907. WHERE status = '1' ".
  5908. $orderClause;
  5909. if (api_is_multiple_url_enabled()) {
  5910. $userRelAccessUrlTable = Database::get_main_table(
  5911. TABLE_MAIN_ACCESS_URL_REL_USER
  5912. );
  5913. $accessUrlId = api_get_current_access_url_id();
  5914. if ($accessUrlId != -1) {
  5915. $sql = "SELECT user.user_id, username, lastname, firstname
  5916. FROM $tbl_user user
  5917. INNER JOIN $userRelAccessUrlTable url_user
  5918. ON (url_user.user_id = user.user_id)
  5919. WHERE
  5920. access_url_id = $accessUrlId AND
  5921. status = 1 "
  5922. .$orderClause;
  5923. }
  5924. }
  5925. $result = Database::query($sql);
  5926. $coachesList = Database::store_result($result);
  5927. $coachesOptions = array();
  5928. foreach ($coachesList as $coachItem) {
  5929. $coachesOptions[$coachItem['user_id']] =
  5930. api_get_person_name($coachItem['firstname'], $coachItem['lastname']).' ('.$coachItem['username'].')';
  5931. }
  5932. $form->addElement(
  5933. 'select',
  5934. 'coach_username',
  5935. get_lang('CoachName'),
  5936. $coachesOptions
  5937. );
  5938. } else {
  5939. $form->addElement(
  5940. 'select_ajax',
  5941. 'coach_username',
  5942. get_lang('CoachName'),
  5943. null,
  5944. [
  5945. 'url' => api_get_path(WEB_AJAX_PATH) . 'session.ajax.php?a=search_general_coach',
  5946. 'width' => '100%',
  5947. ]
  5948. );
  5949. }
  5950. }
  5951. $form->addRule('coach_username', get_lang('ThisFieldIsRequired'), 'required');
  5952. $form->addHtml('<div id="ajax_list_coachs"></div>');
  5953. $form->addButtonAdvancedSettings('advanced_params');
  5954. $form->addElement('html','<div id="advanced_params_options" style="display:none">');
  5955. $form->addSelect('session_category', get_lang('SessionCategory'), $categoriesOptions, array(
  5956. 'id' => 'session_category'
  5957. ));
  5958. $form->addHtmlEditor(
  5959. 'description',
  5960. get_lang('Description'),
  5961. false,
  5962. false,
  5963. array(
  5964. 'ToolbarSet' => 'Minimal',
  5965. )
  5966. );
  5967. $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'));
  5968. $visibilityGroup = array();
  5969. $visibilityGroup[] = $form->createElement('select', 'session_visibility', null, array(
  5970. SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
  5971. SESSION_VISIBLE => get_lang('SessionAccessible'),
  5972. SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible')),
  5973. ));
  5974. $form->addGroup($visibilityGroup, 'visibility_group', get_lang('SessionVisibility'), null, false);
  5975. $options = [
  5976. 0 => get_lang('ByDuration'),
  5977. 1 => get_lang('ByDates'),
  5978. ];
  5979. $form->addSelect('access', get_lang('Access'), $options, array(
  5980. 'onchange' => 'accessSwitcher()',
  5981. 'id' => 'access',
  5982. ));
  5983. $form->addElement('html', '<div id="duration" style="display:none">');
  5984. $form->addElement(
  5985. 'number',
  5986. 'duration',
  5987. array(
  5988. get_lang('SessionDurationTitle'),
  5989. get_lang('SessionDurationDescription'),
  5990. ),
  5991. array(
  5992. 'maxlength' => 50,
  5993. )
  5994. );
  5995. $form->addElement('html', '</div>');
  5996. $form->addElement('html', '<div id="date_fields" style="display:none">');
  5997. // Dates
  5998. $form->addDateTimePicker(
  5999. 'access_start_date',
  6000. array(get_lang('SessionStartDate'), get_lang('SessionStartDateComment')),
  6001. array('id' => 'access_start_date')
  6002. );
  6003. $form->addDateTimePicker(
  6004. 'access_end_date',
  6005. array(get_lang('SessionEndDate'), get_lang('SessionEndDateComment')),
  6006. array('id' => 'access_end_date')
  6007. );
  6008. $form->addRule(
  6009. array('access_start_date', 'access_end_date'),
  6010. get_lang('StartDateMustBeBeforeTheEndDate'),
  6011. 'compare_datetime_text',
  6012. '< allow_empty'
  6013. );
  6014. $form->addDateTimePicker(
  6015. 'display_start_date',
  6016. array(
  6017. get_lang('SessionDisplayStartDate'),
  6018. get_lang('SessionDisplayStartDateComment'),
  6019. ),
  6020. array('id' => 'display_start_date')
  6021. );
  6022. $form->addDateTimePicker(
  6023. 'display_end_date',
  6024. array(
  6025. get_lang('SessionDisplayEndDate'),
  6026. get_lang('SessionDisplayEndDateComment'),
  6027. ),
  6028. array('id' => 'display_end_date')
  6029. );
  6030. $form->addRule(
  6031. array('display_start_date', 'display_end_date'),
  6032. get_lang('StartDateMustBeBeforeTheEndDate'),
  6033. 'compare_datetime_text',
  6034. '< allow_empty'
  6035. );
  6036. $form->addDateTimePicker(
  6037. 'coach_access_start_date',
  6038. array(
  6039. get_lang('SessionCoachStartDate'),
  6040. get_lang('SessionCoachStartDateComment'),
  6041. ),
  6042. array('id' => 'coach_access_start_date')
  6043. );
  6044. $form->addDateTimePicker(
  6045. 'coach_access_end_date',
  6046. array(
  6047. get_lang('SessionCoachEndDate'),
  6048. get_lang('SessionCoachEndDateComment'),
  6049. ),
  6050. array('id' => 'coach_access_end_date')
  6051. );
  6052. $form->addRule(
  6053. array('coach_access_start_date', 'coach_access_end_date'),
  6054. get_lang('StartDateMustBeBeforeTheEndDate'),
  6055. 'compare_datetime_text',
  6056. '< allow_empty'
  6057. );
  6058. $form->addElement('html', '</div>');
  6059. $form->addCheckBox(
  6060. 'send_subscription_notification',
  6061. [
  6062. get_lang('SendSubscriptionNotification'),
  6063. get_lang('SendAnEmailWhenAUserBeingSubscribed')
  6064. ]
  6065. );
  6066. // Extra fields
  6067. $extra_field = new ExtraField('session');
  6068. $extra = $extra_field->addElements($form, $sessionId);
  6069. $form->addElement('html','</div>');
  6070. $js = $extra['jquery_ready_content'];
  6071. return ['js' => $js];
  6072. }
  6073. /**
  6074. * Gets the number of rows in the session table filtered through the given
  6075. * array of parameters
  6076. * @param array Array of options/filters/keys
  6077. * @return integer The number of rows, or false on wrong param
  6078. * @assert ('a') === false
  6079. */
  6080. static function get_count_admin_complete($options = array())
  6081. {
  6082. if (!is_array($options)) {
  6083. return false;
  6084. }
  6085. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  6086. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  6087. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  6088. $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  6089. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  6090. $where = 'WHERE 1 = 1 ';
  6091. $user_id = api_get_user_id();
  6092. if (api_is_session_admin() &&
  6093. api_get_setting('allow_session_admins_to_see_all_sessions') == 'false'
  6094. ) {
  6095. $where.=" WHERE s.session_admin_id = $user_id ";
  6096. }
  6097. if (!empty($options['where'])) {
  6098. $options['where'] = str_replace('course_title', 'c.title', $options['where']);
  6099. $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
  6100. $options['where'] = str_replace(
  6101. array("AND session_active = '1' )", " AND ( session_active = '1' )"),
  6102. array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
  6103. , $options['where']
  6104. );
  6105. $options['where'] = str_replace(
  6106. array("AND session_active = '0' )", " AND ( session_active = '0' )"),
  6107. array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
  6108. $options['where']
  6109. );
  6110. if (!empty($options['extra'])) {
  6111. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  6112. $options['where'] = str_replace('AND', 'OR', $options['where']);
  6113. foreach ($options['extra'] as $extra) {
  6114. $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
  6115. }
  6116. }
  6117. $where .= ' AND '.$options['where'];
  6118. }
  6119. $today = api_get_utc_datetime();
  6120. $query_rows = "SELECT count(*) as total_rows, c.title as course_title, s.name,
  6121. IF (
  6122. (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
  6123. (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
  6124. (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
  6125. (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
  6126. ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
  6127. , 1, 0) as session_active
  6128. FROM $tbl_session s
  6129. LEFT JOIN $tbl_session_category sc
  6130. ON s.session_category_id = sc.id
  6131. INNER JOIN $tbl_user u
  6132. ON s.id_coach = u.user_id
  6133. INNER JOIN $sessionCourseUserTable scu
  6134. ON s.id = scu.session_id
  6135. INNER JOIN $courseTable c
  6136. ON c.id = scu.c_id
  6137. $where ";
  6138. if (api_is_multiple_url_enabled()) {
  6139. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  6140. $access_url_id = api_get_current_access_url_id();
  6141. if ($access_url_id != -1) {
  6142. $where.= " AND ar.access_url_id = $access_url_id ";
  6143. $query_rows = "SELECT count(*) as total_rows
  6144. FROM $tbl_session s
  6145. LEFT JOIN $tbl_session_category sc
  6146. ON s.session_category_id = sc.id
  6147. INNER JOIN $tbl_user u
  6148. ON s.id_coach = u.user_id
  6149. INNER JOIN $table_access_url_rel_session ar
  6150. ON ar.session_id = s.id $where ";
  6151. }
  6152. }
  6153. $result = Database::query($query_rows);
  6154. $num = 0;
  6155. if (Database::num_rows($result)) {
  6156. $rows = Database::fetch_array($result);
  6157. $num = $rows['total_rows'];
  6158. }
  6159. return $num;
  6160. }
  6161. /**
  6162. * @param string $list_type
  6163. * @return array
  6164. */
  6165. public static function getGridColumns($list_type = 'simple')
  6166. {
  6167. // Column config
  6168. $operators = array('cn', 'nc');
  6169. $date_operators = array('gt', 'ge', 'lt', 'le');
  6170. switch ($list_type) {
  6171. case 'simple':
  6172. $columns = array(
  6173. get_lang('Name'),
  6174. get_lang('Category'),
  6175. get_lang('SessionDisplayStartDate'),
  6176. get_lang('SessionDisplayEndDate'),
  6177. //get_lang('Coach'),
  6178. //get_lang('Status'),
  6179. //get_lang('CourseTitle'),
  6180. get_lang('Visibility'),
  6181. );
  6182. $column_model = array (
  6183. array('name'=>'name', 'index'=>'s.name', 'width'=>'160', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
  6184. array('name'=>'category_name', 'index'=>'category_name', 'width'=>'40', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
  6185. array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'50', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
  6186. 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)),
  6187. array('name'=>'visibility', 'index'=>'visibility', 'width'=>'40', 'align'=>'left', 'search' => 'false'),
  6188. );
  6189. break;
  6190. case 'complete':
  6191. $columns = array(
  6192. get_lang('Name'),
  6193. get_lang('SessionDisplayStartDate'),
  6194. get_lang('SessionDisplayEndDate'),
  6195. get_lang('Coach'),
  6196. get_lang('Status'),
  6197. get_lang('Visibility'),
  6198. get_lang('CourseTitle'),
  6199. );
  6200. $column_model = array (
  6201. array('name'=>'name', 'index'=>'s.name', 'width'=>'200', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
  6202. array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
  6203. 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)),
  6204. array('name'=>'coach_name', 'index'=>'coach_name', 'width'=>'70', 'align'=>'left', 'search' => 'false', 'searchoptions' => array('sopt' => $operators)),
  6205. array('name'=>'session_active', 'index'=>'session_active', 'width'=>'25', 'align'=>'left', 'search' => 'true', 'stype'=>'select',
  6206. // for the bottom bar
  6207. 'searchoptions' => array(
  6208. 'defaultValue' => '1',
  6209. 'value' => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
  6210. // for the top bar
  6211. 'editoptions' => array('value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive')),
  6212. ),
  6213. array('name'=>'visibility', 'index'=>'visibility', 'width'=>'40', 'align'=>'left', 'search' => 'false'),
  6214. array('name'=>'course_title', 'index'=>'course_title', 'width'=>'50', 'hidden' => 'true', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true','sopt' => $operators)),
  6215. );
  6216. break;
  6217. }
  6218. // Inject extra session fields
  6219. $session_field = new ExtraField('session');
  6220. $rules = $session_field->getRules($columns, $column_model);
  6221. $column_model[] = array('name'=>'actions', 'index'=>'actions', 'width'=>'80', 'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false');
  6222. $columns[] = get_lang('Actions');
  6223. foreach ($column_model as $col_model) {
  6224. $simple_column_name[] = $col_model['name'];
  6225. }
  6226. $return_array = array(
  6227. 'columns' => $columns,
  6228. 'column_model' => $column_model,
  6229. 'rules' => $rules,
  6230. 'simple_column_name' => $simple_column_name,
  6231. );
  6232. return $return_array;
  6233. }
  6234. /**
  6235. * Converts all dates sent through the param array (given form) to correct dates with timezones
  6236. * @param array The dates The same array, with times converted
  6237. * @param boolean $applyFormat Whether apply the DATE_TIME_FORMAT_SHORT format for sessions
  6238. * @return array The same array, with times converted
  6239. */
  6240. static function convert_dates_to_local($params, $applyFormat = false)
  6241. {
  6242. if (!is_array($params)) {
  6243. return false;
  6244. }
  6245. $params['display_start_date'] = api_get_local_time($params['display_start_date'], null, null, true);
  6246. $params['display_end_date'] = api_get_local_time($params['display_end_date'], null, null, true);
  6247. $params['access_start_date'] = api_get_local_time($params['access_start_date'], null, null, true);
  6248. $params['access_end_date'] = api_get_local_time($params['access_end_date'], null, null, true);
  6249. $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_local_time($params['coach_access_start_date'], null, null, true) : null;
  6250. $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_local_time($params['coach_access_end_date'], null, null, true) : null;
  6251. if ($applyFormat) {
  6252. if (isset($params['display_start_date'])) {
  6253. $params['display_start_date'] = api_format_date($params['display_start_date'], DATE_TIME_FORMAT_SHORT);
  6254. }
  6255. if (isset($params['display_end_date'])) {
  6256. $params['display_end_date'] = api_format_date($params['display_end_date'], DATE_TIME_FORMAT_SHORT);
  6257. }
  6258. if (isset($params['access_start_date'])) {
  6259. $params[''] = api_format_date($params['access_start_date'], DATE_TIME_FORMAT_SHORT);
  6260. }
  6261. if (isset($params['access_end_date'])) {
  6262. $params['access_end_date'] = api_format_date($params['access_end_date'], DATE_TIME_FORMAT_SHORT);
  6263. }
  6264. if (isset($params['coach_access_start_date'])) {
  6265. $params['coach_access_start_date'] = api_format_date($params['coach_access_start_date'], DATE_TIME_FORMAT_SHORT);
  6266. }
  6267. if (isset($params['coach_access_end_date'])) {
  6268. $params['coach_access_end_date'] = api_format_date($params['coach_access_end_date'], DATE_TIME_FORMAT_SHORT);
  6269. }
  6270. }
  6271. return $params;
  6272. }
  6273. /**
  6274. * Gets the admin session list callback of the session/session_list.php
  6275. * page with all user/details in the right fomat
  6276. * @param array
  6277. * @result array Array of rows results
  6278. * @asset ('a') === false
  6279. */
  6280. public static function get_sessions_admin_complete($options = array())
  6281. {
  6282. if (!is_array($options)) {
  6283. return false;
  6284. }
  6285. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  6286. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  6287. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  6288. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  6289. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  6290. $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
  6291. $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  6292. $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  6293. $where = 'WHERE 1 = 1 ';
  6294. $user_id = api_get_user_id();
  6295. if (!api_is_platform_admin()) {
  6296. if (api_is_session_admin() &&
  6297. api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
  6298. ) {
  6299. $where.=" AND s.session_admin_id = $user_id ";
  6300. }
  6301. }
  6302. $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
  6303. if (api_is_western_name_order()) {
  6304. $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
  6305. }
  6306. $today = api_get_utc_datetime();
  6307. $inject_extra_fields = null;
  6308. $extra_fields = array();
  6309. $extra_fields_info = array();
  6310. //for now only sessions
  6311. $extra_field = new ExtraField('session');
  6312. $double_fields = array();
  6313. $extra_field_option = new ExtraFieldOption('session');
  6314. if (isset($options['extra'])) {
  6315. $extra_fields = $options['extra'];
  6316. if (!empty($extra_fields)) {
  6317. foreach ($extra_fields as $extra) {
  6318. $inject_extra_fields .= " IF (fv.field_id = {$extra['id']}, fvo.option_display_text, NULL ) as {$extra['field']} , ";
  6319. if (isset($extra_fields_info[$extra['id']])) {
  6320. $info = $extra_fields_info[$extra['id']];
  6321. } else {
  6322. $info = $extra_field->get($extra['id']);
  6323. $extra_fields_info[$extra['id']] = $info;
  6324. }
  6325. if ($info['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
  6326. $double_fields[$info['id']] = $info;
  6327. }
  6328. }
  6329. }
  6330. }
  6331. $options_by_double = array();
  6332. foreach ($double_fields as $double) {
  6333. $my_options = $extra_field_option->get_field_options_by_field(
  6334. $double['id'],
  6335. true
  6336. );
  6337. $options_by_double['extra_'.$double['field_variable']] = $my_options;
  6338. }
  6339. //sc.name as category_name,
  6340. $select = "
  6341. SELECT * FROM (
  6342. SELECT DISTINCT
  6343. IF (
  6344. (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
  6345. (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
  6346. (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
  6347. (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
  6348. ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
  6349. , 1, 0) as session_active,
  6350. s.name,
  6351. s.nbr_courses,
  6352. s.nbr_users,
  6353. s.display_start_date,
  6354. s.display_end_date,
  6355. $coach_name,
  6356. access_start_date,
  6357. access_end_date,
  6358. s.visibility,
  6359. u.user_id,
  6360. $inject_extra_fields
  6361. c.title as course_title,
  6362. s.id ";
  6363. if (!empty($options['where'])) {
  6364. if (!empty($options['extra'])) {
  6365. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  6366. $options['where'] = str_replace('AND', 'OR', $options['where']);
  6367. foreach ($options['extra'] as $extra) {
  6368. $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
  6369. }
  6370. }
  6371. $options['where'] = str_replace('course_title', 'c.title', $options['where']);
  6372. $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
  6373. $options['where'] = str_replace(
  6374. array("AND session_active = '1' )", " AND ( session_active = '1' )"),
  6375. array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
  6376. , $options['where']
  6377. );
  6378. $options['where'] = str_replace(
  6379. array("AND session_active = '0' )", " AND ( session_active = '0' )"),
  6380. array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
  6381. $options['where']
  6382. );
  6383. $where .= ' AND '.$options['where'];
  6384. }
  6385. if (!empty($options['limit'])) {
  6386. $where .= " LIMIT ".$options['limit'];
  6387. }
  6388. $query = "$select FROM $tbl_session s
  6389. LEFT JOIN $tbl_session_field_values fv
  6390. ON (fv.item_id = s.id)
  6391. LEFT JOIN $extraFieldTable f
  6392. ON f.id = fv.field_id
  6393. LEFT JOIN $tbl_session_field_options fvo
  6394. ON (fv.field_id = fvo.field_id)
  6395. LEFT JOIN $tbl_session_rel_course src
  6396. ON (src.session_id = s.id)
  6397. LEFT JOIN $tbl_course c
  6398. ON (src.c_id = c.id)
  6399. LEFT JOIN $tbl_session_category sc
  6400. ON (s.session_category_id = sc.id)
  6401. INNER JOIN $tbl_user u
  6402. ON (s.id_coach = u.user_id) ".
  6403. $where;
  6404. if (api_is_multiple_url_enabled()) {
  6405. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  6406. $access_url_id = api_get_current_access_url_id();
  6407. if ($access_url_id != -1) {
  6408. $where.= " AND ar.access_url_id = $access_url_id ";
  6409. $query = "$select
  6410. FROM $tbl_session s
  6411. LEFT JOIN $tbl_session_field_values fv ON (fv.session_id = s.id)
  6412. LEFT JOIN $tbl_session_field_options fvo ON (fv.field_id = fvo.field_id)
  6413. LEFT JOIN $tbl_session_rel_course src ON (src.id_session = s.id)
  6414. LEFT JOIN $tbl_course c ON (src.c_id = c.id)
  6415. LEFT JOIN $tbl_session_category sc ON (s.session_category_id = sc.id)
  6416. INNER JOIN $tbl_user u ON (s.id_coach = u.user_id)
  6417. INNER JOIN $table_access_url_rel_session ar ON (ar.session_id = s.id)
  6418. $where";
  6419. }
  6420. }
  6421. $query .= ") AS session_table";
  6422. if (!empty($options['order'])) {
  6423. $query .= " ORDER BY ".$options['order'];
  6424. }
  6425. //error_log($query);
  6426. //echo $query;
  6427. $result = Database::query($query);
  6428. $formatted_sessions = array();
  6429. if (Database::num_rows($result)) {
  6430. $sessions = Database::store_result($result, 'ASSOC');
  6431. foreach ($sessions as $session) {
  6432. $session_id = $session['id'];
  6433. $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
  6434. $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
  6435. if ($session['session_active'] == 1) {
  6436. $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
  6437. } else {
  6438. $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
  6439. }
  6440. $session = self::convert_dates_to_local($session);
  6441. switch ($session['visibility']) {
  6442. case SESSION_VISIBLE_READ_ONLY: //1
  6443. $session['visibility'] = get_lang('ReadOnly');
  6444. break;
  6445. case SESSION_VISIBLE: //2
  6446. case SESSION_AVAILABLE: //4
  6447. $session['visibility'] = get_lang('Visible');
  6448. break;
  6449. case SESSION_INVISIBLE: //3
  6450. $session['visibility'] = api_ucfirst(get_lang('Invisible'));
  6451. break;
  6452. }
  6453. // Cleaning double selects
  6454. foreach ($session as $key => &$value) {
  6455. if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
  6456. $options = explode('::', $value);
  6457. }
  6458. $original_key = $key;
  6459. if (strpos($key, '_second') === false) {
  6460. } else {
  6461. $key = str_replace('_second', '', $key);
  6462. }
  6463. if (isset($options_by_double[$key])) {
  6464. if (isset($options[0])) {
  6465. if (isset($options_by_double[$key][$options[0]])) {
  6466. if (strpos($original_key, '_second') === false) {
  6467. $value = $options_by_double[$key][$options[0]]['option_display_text'];
  6468. } else {
  6469. $value = $options_by_double[$key][$options[1]]['option_display_text'];
  6470. }
  6471. }
  6472. }
  6473. }
  6474. }
  6475. // Magic filter
  6476. if (isset($formatted_sessions[$session_id])) {
  6477. $formatted_sessions[$session_id] = self::compareArraysToMerge($formatted_sessions[$session_id], $session);
  6478. } else {
  6479. $formatted_sessions[$session_id] = $session;
  6480. }
  6481. }
  6482. }
  6483. return $formatted_sessions;
  6484. }
  6485. /**
  6486. * Compare two arrays
  6487. * @param array $array1
  6488. * @param array $array2
  6489. *
  6490. * @return array
  6491. */
  6492. static function compareArraysToMerge($array1, $array2)
  6493. {
  6494. if (empty($array2)) {
  6495. return $array1;
  6496. }
  6497. foreach ($array1 as $key => $item) {
  6498. if (!isset($array1[$key])) {
  6499. //My string is empty try the other one
  6500. if (isset($array2[$key]) && !empty($array2[$key])) {
  6501. $array1[$key] = $array2[$key];
  6502. }
  6503. }
  6504. }
  6505. return $array1;
  6506. }
  6507. /**
  6508. * Get link to the admin page for this session
  6509. * @param int $id Session ID
  6510. * @return mixed URL to the admin page to manage the session, or false on error
  6511. */
  6512. public static function getAdminPath($id)
  6513. {
  6514. $id = intval($id);
  6515. $session = self::fetch($id);
  6516. if (empty($session)) {
  6517. return false;
  6518. }
  6519. return api_get_path(WEB_CODE_PATH) . 'session/resume_session.php?id_session=' . $id;
  6520. }
  6521. /**
  6522. * Get link to the user page for this session.
  6523. * If a course is provided, build the link to the course
  6524. * @param int $id Session ID
  6525. * @param int $courseId Course ID (optional) in case the link has to send straight to the course
  6526. * @return mixed URL to the page to use the session, or false on error
  6527. */
  6528. public static function getPath($id, $courseId = 0)
  6529. {
  6530. $id = intval($id);
  6531. $session = self::fetch($id);
  6532. if (empty($session)) {
  6533. return false;
  6534. }
  6535. if (empty($courseId)) {
  6536. return api_get_path(WEB_CODE_PATH) . 'session/index.php?session_id=' . $id;
  6537. } else {
  6538. $courseInfo = api_get_course_info_by_id($courseId);
  6539. if ($courseInfo) {
  6540. return $courseInfo['course_public_url'].'?id_session='.$id;
  6541. }
  6542. }
  6543. return false;
  6544. }
  6545. /**
  6546. * Return an associative array 'id_course' => [id_session1, id_session2...]
  6547. * where course id_course is in sessions id_session1, id_session2
  6548. * for course where user is coach
  6549. * i.e. coach for the course or
  6550. * main coach for a session the course is in
  6551. * for a session category (or woth no session category if empty)
  6552. *
  6553. * @param $userId
  6554. *
  6555. * @return array
  6556. */
  6557. public static function getSessionCourseForUser($userId)
  6558. {
  6559. // list of COURSES where user is COURSE session coach
  6560. $listCourseCourseCoachSession = self::getCoursesForCourseSessionCoach($userId);
  6561. // list of courses where user is MAIN session coach
  6562. $listCourseMainCoachSession = self::getCoursesForMainSessionCoach($userId);
  6563. // merge these 2 array
  6564. $listResCourseSession = $listCourseCourseCoachSession;
  6565. foreach ($listCourseMainCoachSession as $courseId2 => $listSessionId2) {
  6566. if (isset($listResCourseSession[$courseId2])) {
  6567. // if sessionId array exists for this course
  6568. // same courseId, merge the list of session
  6569. foreach ($listCourseMainCoachSession[$courseId2] as $i => $sessionId2) {
  6570. if (!in_array($sessionId2, $listResCourseSession[$courseId2])) {
  6571. $listResCourseSession[$courseId2][] = $sessionId2;
  6572. }
  6573. }
  6574. } else {
  6575. $listResCourseSession[$courseId2] = $listSessionId2;
  6576. }
  6577. }
  6578. return $listResCourseSession;
  6579. }
  6580. /**
  6581. * Return an associative array 'id_course' => [id_session1, id_session2...]
  6582. * where course id_course is in sessions id_session1, id_session2
  6583. * @param $userId
  6584. *
  6585. * @return array
  6586. */
  6587. public static function getCoursesForCourseSessionCoach($userId)
  6588. {
  6589. $listResCourseSession = array();
  6590. $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  6591. $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  6592. $sql = "SELECT session_id, c_id, c.id
  6593. FROM $tblSessionRelCourseRelUser srcru
  6594. LEFT JOIN $tblCourse c
  6595. ON c.id = srcru.c_id
  6596. WHERE
  6597. srcru.user_id =".intval($userId)." AND
  6598. srcru.status = 2";
  6599. $res = Database::query($sql);
  6600. while ($data = Database::fetch_assoc($res)) {
  6601. if (self::isSessionDateOkForCoach($data['session_id'])) {
  6602. if (!isset($listResCourseSession[$data['id']])) {
  6603. $listResCourseSession[$data['id']] = array();
  6604. }
  6605. $listResCourseSession[$data['id']][] = $data['session_id'];
  6606. }
  6607. }
  6608. return $listResCourseSession;
  6609. }
  6610. /**
  6611. * Return true if coach is allowed to access this session
  6612. * @param int $sessionId
  6613. * @return bool
  6614. */
  6615. public static function isSessionDateOkForCoach($sessionId)
  6616. {
  6617. return api_get_session_visibility($sessionId);
  6618. /*
  6619. $listSessionInfo = api_get_session_info($sessionId);
  6620. $dateStart = $listSessionInfo['date_start'];
  6621. $dateEnd = $listSessionInfo['date_end'];
  6622. $nbDaysAccessBeforeBeginning = $listSessionInfo['nb_days_access_before_beginning'];
  6623. $nbDaysAccessAfterEnd = $listSessionInfo['nb_days_access_after_end'];
  6624. // no start date
  6625. if ($dateStart == '0000-00-00') {
  6626. return true;
  6627. }
  6628. $now = time();
  6629. $dateStartForCoach = api_strtotime($dateStart.' 00:00:00') - ($nbDaysAccessBeforeBeginning * 86400);
  6630. $dateEndForCoach = api_strtotime($dateEnd.' 00:00:00') + ($nbDaysAccessAfterEnd * 86400);
  6631. if ($dateEnd == '0000-00-00') {
  6632. // start date but no end date
  6633. if ($dateStartForCoach <= $now) {
  6634. return true;
  6635. }
  6636. } else {
  6637. // start date and end date
  6638. if ($dateStartForCoach <= $now && $now <= $dateEndForCoach) {
  6639. return true;
  6640. }
  6641. }
  6642. return false;*/
  6643. }
  6644. /**
  6645. * Return an associative array 'id_course' => [id_session1, id_session2...]
  6646. * where course id_course is in sessions id_session1, id_session2
  6647. * @param $userId
  6648. *
  6649. * @return array
  6650. */
  6651. public static function getCoursesForMainSessionCoach($userId)
  6652. {
  6653. $listResCourseSession = array();
  6654. $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
  6655. // list of SESSION where user is session coach
  6656. $sql = "SELECT id FROM $tblSession
  6657. WHERE id_coach = ".intval($userId);
  6658. $res = Database::query($sql);
  6659. while ($data = Database::fetch_assoc($res)) {
  6660. $sessionId = $data['id'];
  6661. $listCoursesInSession = self::getCoursesInSession($sessionId);
  6662. foreach ($listCoursesInSession as $i => $courseId) {
  6663. if (self::isSessionDateOkForCoach($sessionId)) {
  6664. if (!isset($listResCourseSession[$courseId])) {
  6665. $listResCourseSession[$courseId] = array();
  6666. }
  6667. $listResCourseSession[$courseId][] = $sessionId;
  6668. }
  6669. }
  6670. }
  6671. return $listResCourseSession;
  6672. }
  6673. /**
  6674. * Return an array of course_id used in session $sessionId
  6675. * @param $sessionId
  6676. *
  6677. * @return array
  6678. */
  6679. public static function getCoursesInSession($sessionId)
  6680. {
  6681. $listResultsCourseId = array();
  6682. $tblSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  6683. $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  6684. // list of course in this session
  6685. $sql = "SELECT session_id, c.id
  6686. FROM $tblSessionRelCourse src
  6687. LEFT JOIN $tblCourse c
  6688. ON c.id = src.c_id
  6689. WHERE session_id = ".intval($sessionId);
  6690. $res = Database::query($sql);
  6691. while ($data = Database::fetch_assoc($res)) {
  6692. $listResultsCourseId[] = $data['id'];
  6693. }
  6694. return $listResultsCourseId;
  6695. }
  6696. /**
  6697. * Return an array of courses in session for user
  6698. * and for each courses the list of session that use this course for user
  6699. *
  6700. * [0] => array
  6701. * userCatId
  6702. * userCatTitle
  6703. * courseInUserCatList
  6704. * [0] => array
  6705. * courseId
  6706. * title
  6707. * courseCode
  6708. * sessionCatList
  6709. * [0] => array
  6710. * catSessionId
  6711. * catSessionName
  6712. * sessionList
  6713. * [0] => array
  6714. * sessionId
  6715. * sessionName
  6716. *
  6717. * @param $userId
  6718. *
  6719. * @return array
  6720. *
  6721. */
  6722. public static function getNamedSessionCourseForCoach($userId)
  6723. {
  6724. $listResults = array();
  6725. $listCourseSession = self::getSessionCourseForUser($userId);
  6726. foreach ($listCourseSession as $courseId => $listSessionId) {
  6727. // Course info
  6728. $courseInfo = api_get_course_info_by_id($courseId);
  6729. $listOneCourse = array();
  6730. $listOneCourse['courseId'] = $courseId;
  6731. $listOneCourse['title'] = $courseInfo['title'];
  6732. //$listOneCourse['courseCode'] = $courseInfo['code'];
  6733. $listOneCourse['course'] = $courseInfo;
  6734. $listOneCourse['sessionCatList'] = array();
  6735. $listCat = array();
  6736. foreach ($listSessionId as $i => $sessionId) {
  6737. // here we got all session for this course
  6738. // lets check there session categories
  6739. $sessionInfo = SessionManager::fetch($sessionId);
  6740. $catId = $sessionInfo['session_category_id'];
  6741. if (!isset($listCat[$catId])) {
  6742. $listCatInfo = self::get_session_category($catId);
  6743. $listCat[$catId] = array();
  6744. $listCat[$catId]['catSessionId'] = $catId;
  6745. $listCat[$catId]['catSessionName'] = $listCatInfo['name'];
  6746. $listCat[$catId]['sessionList'] = array();
  6747. }
  6748. $listSessionInfo = SessionManager::fetch($sessionId);
  6749. $listSessionIdName = array(
  6750. "sessionId" => $sessionId,
  6751. "sessionName" => $listSessionInfo['name'],
  6752. );
  6753. $listCat[$catId]['sessionList'][] = $listSessionIdName;
  6754. }
  6755. // sort $listCat by catSessionName
  6756. usort($listCat, 'self::compareBySessionName');
  6757. // in each catSession sort sessionList by sessionName
  6758. foreach($listCat as $i => $listCatSessionInfo) {
  6759. $listSessionList = $listCatSessionInfo['sessionList'];
  6760. usort($listSessionList, 'self::compareCatSessionInfo');
  6761. $listCat[$i]['sessionList'] = $listSessionList;
  6762. }
  6763. $listOneCourse['sessionCatList'] = $listCat;
  6764. // user course category
  6765. list($userCatId, $userCatTitle) = CourseManager::getUserCourseCategoryForCourse(
  6766. $userId,
  6767. $courseId
  6768. );
  6769. $userCatId = intval($userCatId);
  6770. $listResults[$userCatId]['courseInUserCategoryId'] = $userCatId;
  6771. $listResults[$userCatId]['courseInUserCategoryTitle'] = $userCatTitle;
  6772. $listResults[$userCatId]['courseInUserCatList'][] = $listOneCourse;
  6773. }
  6774. // sort by user course cat
  6775. uasort($listResults, 'self::compareByUserCourseCat');
  6776. // sort by course title
  6777. foreach ($listResults as $userCourseCatId => $tabCoursesInCat) {
  6778. $courseInUserCatList = $tabCoursesInCat['courseInUserCatList'];
  6779. uasort($courseInUserCatList, 'self::compareByCourse');
  6780. $listResults[$userCourseCatId]['courseInUserCatList'] = $courseInUserCatList;
  6781. }
  6782. return $listResults;
  6783. }
  6784. /**
  6785. * @param array $listA
  6786. * @param array $listB
  6787. * @return int
  6788. */
  6789. private static function compareCatSessionInfo($listA, $listB)
  6790. {
  6791. if ($listA['sessionName'] == $listB['sessionName']) {
  6792. return 0;
  6793. } else if($listA['sessionName'] > $listB['sessionName']) {
  6794. return 1;
  6795. } else {
  6796. return -1;
  6797. }
  6798. }
  6799. /**
  6800. * @param array $listA
  6801. * @param array $listB
  6802. * @return int
  6803. */
  6804. private static function compareBySessionName($listA, $listB)
  6805. {
  6806. if ($listB['catSessionName'] == '') {
  6807. return -1;
  6808. } else if ($listA['catSessionName'] == '') {
  6809. return 1;
  6810. } else if ($listA['catSessionName'] == $listB['catSessionName']) {
  6811. return 0;
  6812. } else if($listA['catSessionName'] > $listB['catSessionName']) {
  6813. return 1;
  6814. } else {
  6815. return -1;
  6816. }
  6817. }
  6818. /**
  6819. * @param array $listA
  6820. * @param array $listB
  6821. * @return int
  6822. */
  6823. private static function compareByUserCourseCat($listA, $listB)
  6824. {
  6825. if ($listA['courseInUserCategoryTitle'] == $listB['courseInUserCategoryTitle']) {
  6826. return 0;
  6827. } else if($listA['courseInUserCategoryTitle'] > $listB['courseInUserCategoryTitle']) {
  6828. return 1;
  6829. } else {
  6830. return -1;
  6831. }
  6832. }
  6833. /**
  6834. * @param array $listA
  6835. * @param array $listB
  6836. * @return int
  6837. */
  6838. private static function compareByCourse($listA, $listB)
  6839. {
  6840. if ($listA['title'] == $listB['title']) {
  6841. return 0;
  6842. } else if($listA['title'] > $listB['title']) {
  6843. return 1;
  6844. } else {
  6845. return -1;
  6846. }
  6847. }
  6848. /**
  6849. * Return HTML code for displaying session_course_for_coach
  6850. * @param $userId
  6851. * @return string
  6852. */
  6853. public static function getHtmlNamedSessionCourseForCoach($userId)
  6854. {
  6855. $htmlRes = '';
  6856. $listInfo = self::getNamedSessionCourseForCoach($userId);
  6857. foreach ($listInfo as $i => $listCoursesInfo) {
  6858. $courseInfo = $listCoursesInfo['course'];
  6859. $courseCode = $listCoursesInfo['course']['code'];
  6860. $listParamsCourse = array();
  6861. $listParamsCourse['icon'] = '<div style="float:left">
  6862. <input style="border:none;" type="button" onclick="$(\'#course-'.$courseCode.'\').toggle(\'fast\')" value="+" /></div>'.
  6863. Display::return_icon('blackboard.png', $courseInfo['title'], array(), ICON_SIZE_LARGE);
  6864. $listParamsCourse['link'] = '';
  6865. $listParamsCourse['title'] = Display::tag(
  6866. 'a',
  6867. $courseInfo['title'],
  6868. array('href' => $listParamsCourse['link'])
  6869. );
  6870. $htmlCourse = '<div class="well" style="border-color:#27587D">'.
  6871. CourseManager::course_item_html($listParamsCourse, true);
  6872. // for each category of session
  6873. $htmlCatSessions = '';
  6874. foreach ($listCoursesInfo['sessionCatList'] as $j => $listCatSessionsInfo) {
  6875. // we got an array of session categories
  6876. $catSessionId = $listCoursesInfo['sessionCatList'][$j]['catSessionId'];
  6877. $catSessionName = $listCoursesInfo['sessionCatList'][$j]['catSessionName'];
  6878. $listParamsCatSession['icon'] = Display::return_icon('folder_blue.png', $catSessionName, array(), ICON_SIZE_LARGE);
  6879. $listParamsCatSession['link'] = '';
  6880. $listParamsCatSession['title'] = $catSessionName;
  6881. $marginShift = 20;
  6882. if ($catSessionName != '') {
  6883. $htmlCatSessions .= '<div style="margin-left:'.$marginShift.'px;">' .
  6884. CourseManager::course_item_html($listParamsCatSession, true) . '</div>';
  6885. $marginShift = 40;
  6886. }
  6887. // for each sessions
  6888. $listCatSessionSessionList = $listCoursesInfo['sessionCatList'][$j]['sessionList'];
  6889. $htmlSession = '';
  6890. foreach ($listCatSessionSessionList as $k => $listSessionInfo) {
  6891. // we got an array of session info
  6892. $sessionId = $listSessionInfo['sessionId'];
  6893. $sessionName = $listSessionInfo['sessionName'];
  6894. $listParamsSession['icon'] = Display::return_icon('blackboard_blue.png', $sessionName, array(), ICON_SIZE_LARGE);
  6895. $listParamsSession['link'] = '';
  6896. $linkToCourseSession = $courseInfo['course_public_url'].'?id_session='.$sessionId;
  6897. $listParamsSession['title'] =
  6898. $sessionName.'<div style="font-weight:normal; font-style:italic">
  6899. <a href="'.$linkToCourseSession.'">'.get_lang('GoToCourseInsideSession').'</a>
  6900. </div>';
  6901. $htmlSession .= '<div style="margin-left:'.$marginShift.'px;">'.
  6902. CourseManager::course_item_html($listParamsSession, true).'</div>';
  6903. }
  6904. $htmlCatSessions .= $htmlSession;
  6905. }
  6906. $htmlRes .= $htmlCourse.'<div style="display:none" id="course-'.$courseCode.'">'.$htmlCatSessions.'</div></div>';
  6907. }
  6908. return $htmlRes;
  6909. }
  6910. }