sessionmanager.lib.php 322 KB

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