sessionmanager.lib.php 325 KB

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