sessionmanager.lib.php 335 KB

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