sessionmanager.lib.php 300 KB

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