sessionmanager.lib.php 313 KB

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