usermanager.lib.php 232 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
  4. use Chamilo\CoreBundle\Entity\Repository\AccessUrlRepository;
  5. use Chamilo\CoreBundle\Entity\SkillRelUser;
  6. use Chamilo\CoreBundle\Entity\SkillRelUserComment;
  7. use Chamilo\UserBundle\Entity\User;
  8. use Chamilo\UserBundle\Repository\UserRepository;
  9. use ChamiloSession as Session;
  10. use Symfony\Component\Security\Core\Encoder\EncoderFactory;
  11. /**
  12. * Class UserManager.
  13. *
  14. * This library provides functions for user management.
  15. * Include/require it in your code to use its functionality.
  16. *
  17. * @package chamilo.library
  18. *
  19. * @author Julio Montoya <gugli100@gmail.com> Social network groups added 2009/12
  20. */
  21. class UserManager
  22. {
  23. // This constants are deprecated use the constants located in ExtraField
  24. const USER_FIELD_TYPE_TEXT = 1;
  25. const USER_FIELD_TYPE_TEXTAREA = 2;
  26. const USER_FIELD_TYPE_RADIO = 3;
  27. const USER_FIELD_TYPE_SELECT = 4;
  28. const USER_FIELD_TYPE_SELECT_MULTIPLE = 5;
  29. const USER_FIELD_TYPE_DATE = 6;
  30. const USER_FIELD_TYPE_DATETIME = 7;
  31. const USER_FIELD_TYPE_DOUBLE_SELECT = 8;
  32. const USER_FIELD_TYPE_DIVIDER = 9;
  33. const USER_FIELD_TYPE_TAG = 10;
  34. const USER_FIELD_TYPE_TIMEZONE = 11;
  35. const USER_FIELD_TYPE_SOCIAL_PROFILE = 12;
  36. const USER_FIELD_TYPE_FILE = 13;
  37. const USER_FIELD_TYPE_MOBILE_PHONE_NUMBER = 14;
  38. private static $encryptionMethod;
  39. /**
  40. * Constructor.
  41. *
  42. * @assert () === null
  43. */
  44. public function __construct()
  45. {
  46. }
  47. /**
  48. * Repository is use to query the DB, selects, etc.
  49. *
  50. * @return UserRepository
  51. */
  52. public static function getRepository()
  53. {
  54. /** @var UserRepository $userRepository */
  55. $userRepository = Database::getManager()->getRepository('ChamiloUserBundle:User');
  56. return $userRepository;
  57. }
  58. /**
  59. * Create/update/delete methods are available in the UserManager
  60. * (based in the Sonata\UserBundle\Entity\UserManager).
  61. *
  62. * @return Chamilo\UserBundle\Entity\Manager\UserManager
  63. */
  64. public static function getManager()
  65. {
  66. static $userManager;
  67. if (!isset($userManager)) {
  68. $encoderFactory = self::getEncoderFactory();
  69. $userManager = new Chamilo\UserBundle\Entity\Manager\UserManager(
  70. $encoderFactory,
  71. new \FOS\UserBundle\Util\Canonicalizer(),
  72. new \FOS\UserBundle\Util\Canonicalizer(),
  73. Database::getManager(),
  74. 'Chamilo\\UserBundle\\Entity\\User'
  75. );
  76. }
  77. return $userManager;
  78. }
  79. /**
  80. * @param string $encryptionMethod
  81. */
  82. public static function setPasswordEncryption($encryptionMethod)
  83. {
  84. self::$encryptionMethod = $encryptionMethod;
  85. }
  86. /**
  87. * @return bool|mixed
  88. */
  89. public static function getPasswordEncryption()
  90. {
  91. $encryptionMethod = self::$encryptionMethod;
  92. if (empty($encryptionMethod)) {
  93. $encryptionMethod = api_get_configuration_value('password_encryption');
  94. }
  95. return $encryptionMethod;
  96. }
  97. /**
  98. * Validates the password.
  99. *
  100. * @param $encoded
  101. * @param $raw
  102. * @param $salt
  103. *
  104. * @return bool
  105. */
  106. public static function isPasswordValid($encoded, $raw, $salt)
  107. {
  108. $encoder = new \Chamilo\UserBundle\Security\Encoder(self::getPasswordEncryption());
  109. $validPassword = $encoder->isPasswordValid($encoded, $raw, $salt);
  110. return $validPassword;
  111. }
  112. /**
  113. * @param string $raw
  114. * @param User $user
  115. *
  116. * @return string
  117. */
  118. public static function encryptPassword($raw, User $user)
  119. {
  120. $encoder = self::getEncoder($user);
  121. $encodedPassword = $encoder->encodePassword(
  122. $raw,
  123. $user->getSalt()
  124. );
  125. return $encodedPassword;
  126. }
  127. /**
  128. * @param int $userId
  129. * @param string $password
  130. */
  131. public static function updatePassword($userId, $password)
  132. {
  133. $repository = self::getRepository();
  134. /** @var User $user */
  135. $user = $repository->find($userId);
  136. $userManager = self::getManager();
  137. $user->setPlainPassword($password);
  138. $userManager->updateUser($user, true);
  139. }
  140. /**
  141. * Creates a new user for the platform.
  142. *
  143. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>,
  144. * @author Roan Embrechts <roan_embrechts@yahoo.com>
  145. *
  146. * @param string $firstName
  147. * @param string $lastName
  148. * @param int $status (1 for course tutor, 5 for student, 6 for anonymous)
  149. * @param string $email
  150. * @param string $loginName
  151. * @param string $password
  152. * @param string $official_code Any official code (optional)
  153. * @param string $language User language (optional)
  154. * @param string $phone Phone number (optional)
  155. * @param string $picture_uri Picture URI (optional)
  156. * @param string $authSource Authentication source (defaults to 'platform', dependind on constant)
  157. * @param string $expirationDate Account expiration date (optional, defaults to null)
  158. * @param int $active Whether the account is enabled or disabled by default
  159. * @param int $hr_dept_id The department of HR in which the user is registered (defaults to 0)
  160. * @param array $extra Extra fields
  161. * @param string $encrypt_method Used if password is given encrypted. Set to an empty string by default
  162. * @param bool $send_mail
  163. * @param bool $isAdmin
  164. * @param string $address
  165. * @param bool $sendEmailToAllAdmins
  166. * @param FormValidator $form
  167. * @param int $creatorId
  168. * @param array $emailTemplate
  169. * @param string $redirectToURLAfterLogin
  170. *
  171. * @return mixed new user id - if the new user creation succeeds, false otherwise
  172. * @desc The function tries to retrieve user id from the session.
  173. * If it exists, the current user id is the creator id. If a problem arises,
  174. * @assert ('Sam','Gamegie',5,'sam@example.com','jo','jo') > 1
  175. * @assert ('Pippin','Took',null,null,'jo','jo') === false
  176. */
  177. public static function create_user(
  178. $firstName,
  179. $lastName,
  180. $status,
  181. $email,
  182. $loginName,
  183. $password,
  184. $official_code = '',
  185. $language = '',
  186. $phone = '',
  187. $picture_uri = '',
  188. $authSource = PLATFORM_AUTH_SOURCE,
  189. $expirationDate = null,
  190. $active = 1,
  191. $hr_dept_id = 0,
  192. $extra = [],
  193. $encrypt_method = '',
  194. $send_mail = false,
  195. $isAdmin = false,
  196. $address = '',
  197. $sendEmailToAllAdmins = false,
  198. $form = null,
  199. $creatorId = 0,
  200. $emailTemplate = [],
  201. $redirectToURLAfterLogin = ''
  202. ) {
  203. $creatorId = empty($creatorId) ? api_get_user_id() : 0;
  204. $creatorInfo = api_get_user_info($creatorId);
  205. $creatorEmail = isset($creatorInfo['email']) ? $creatorInfo['email'] : '';
  206. $hook = HookCreateUser::create();
  207. if (!empty($hook)) {
  208. $hook->notifyCreateUser(HOOK_EVENT_TYPE_PRE);
  209. }
  210. // First check wether the login already exists
  211. if (!self::is_username_available($loginName)) {
  212. Display::addFlash(
  213. Display::return_message(get_lang('LoginAlreadyTaken'))
  214. );
  215. return false;
  216. }
  217. global $_configuration;
  218. $original_password = $password;
  219. $access_url_id = 1;
  220. if (api_get_multiple_access_url()) {
  221. $access_url_id = api_get_current_access_url_id();
  222. } else {
  223. // In some cases, the first access_url ID might be different from 1
  224. // for example when using a DB cluster or hacking the DB manually.
  225. // In this case, we want the first row, not necessarily "1".
  226. $dbm = Database::getManager();
  227. /** @var AccessUrlRepository $accessUrlRepository */
  228. $accessUrlRepository = $dbm->getRepository('ChamiloCoreBundle:AccessUrl');
  229. $accessUrl = $accessUrlRepository->getFirstId();
  230. if (!empty($accessUrl[0]) && !empty($accessUrl[0][1])) {
  231. $access_url_id = $accessUrl[0][1];
  232. }
  233. }
  234. if (isset($_configuration[$access_url_id]) &&
  235. is_array($_configuration[$access_url_id]) &&
  236. isset($_configuration[$access_url_id]['hosting_limit_users']) &&
  237. $_configuration[$access_url_id]['hosting_limit_users'] > 0) {
  238. $num = self::get_number_of_users();
  239. if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) {
  240. api_warn_hosting_contact('hosting_limit_users');
  241. Display::addFlash(
  242. Display::return_message(
  243. get_lang('PortalUsersLimitReached'),
  244. 'warning'
  245. )
  246. );
  247. return false;
  248. }
  249. }
  250. if ($status === 1 &&
  251. isset($_configuration[$access_url_id]) &&
  252. is_array($_configuration[$access_url_id]) &&
  253. isset($_configuration[$access_url_id]['hosting_limit_teachers']) &&
  254. $_configuration[$access_url_id]['hosting_limit_teachers'] > 0
  255. ) {
  256. $num = self::get_number_of_users(1);
  257. if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) {
  258. Display::addFlash(
  259. Display::return_message(
  260. get_lang('PortalTeachersLimitReached'),
  261. 'warning'
  262. )
  263. );
  264. api_warn_hosting_contact('hosting_limit_teachers');
  265. return false;
  266. }
  267. }
  268. if (empty($password)) {
  269. if ($authSource === PLATFORM_AUTH_SOURCE) {
  270. Display::addFlash(
  271. Display::return_message(
  272. get_lang('ThisFieldIsRequired').': '.get_lang(
  273. 'Password'
  274. ),
  275. 'warning'
  276. )
  277. );
  278. return false;
  279. }
  280. // We use the authSource as password.
  281. // The real validation will be by processed by the auth
  282. // source not Chamilo
  283. $password = $authSource;
  284. }
  285. // database table definition
  286. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  287. // Checking the user language
  288. $languages = api_get_languages();
  289. $language = strtolower($language);
  290. if (isset($languages['folder'])) {
  291. if (!in_array($language, $languages['folder'])) {
  292. $language = api_get_setting('platformLanguage');
  293. }
  294. }
  295. $currentDate = api_get_utc_datetime();
  296. $now = new DateTime();
  297. if (empty($expirationDate) || $expirationDate == '0000-00-00 00:00:00') {
  298. // Default expiration date
  299. // if there is a default duration of a valid account then
  300. // we have to change the expiration_date accordingly
  301. // Accept 0000-00-00 00:00:00 as a null value to avoid issues with
  302. // third party code using this method with the previous (pre-1.10)
  303. // value of 0000...
  304. if (api_get_setting('account_valid_duration') != '') {
  305. $expirationDate = new DateTime($currentDate);
  306. $days = (int) api_get_setting('account_valid_duration');
  307. $expirationDate->modify('+'.$days.' day');
  308. }
  309. } else {
  310. $expirationDate = api_get_utc_datetime($expirationDate);
  311. $expirationDate = new \DateTime($expirationDate, new DateTimeZone('UTC'));
  312. }
  313. $userManager = self::getManager();
  314. /** @var User $user */
  315. $user = $userManager->createUser();
  316. $user
  317. ->setLastname($lastName)
  318. ->setFirstname($firstName)
  319. ->setUsername($loginName)
  320. ->setStatus($status)
  321. ->setPlainPassword($password)
  322. ->setEmail($email)
  323. ->setOfficialCode($official_code)
  324. ->setPictureUri($picture_uri)
  325. ->setCreatorId($creatorId)
  326. ->setAuthSource($authSource)
  327. ->setPhone($phone)
  328. ->setAddress($address)
  329. ->setLanguage($language)
  330. ->setRegistrationDate($now)
  331. ->setHrDeptId($hr_dept_id)
  332. ->setActive($active)
  333. ->setEnabled($active)
  334. ;
  335. if (!empty($expirationDate)) {
  336. $user->setExpirationDate($expirationDate);
  337. }
  338. $userManager->updateUser($user);
  339. $userId = $user->getId();
  340. if (!empty($userId)) {
  341. $return = $userId;
  342. $sql = "UPDATE $table_user SET user_id = $return WHERE id = $return";
  343. Database::query($sql);
  344. if ($isAdmin) {
  345. self::add_user_as_admin($user);
  346. }
  347. if (api_get_multiple_access_url()) {
  348. UrlManager::add_user_to_url($userId, api_get_current_access_url_id());
  349. } else {
  350. //we are adding by default the access_url_user table with access_url_id = 1
  351. UrlManager::add_user_to_url($userId, 1);
  352. }
  353. $extra['item_id'] = $userId;
  354. if (is_array($extra) && count($extra) > 0) {
  355. $courseFieldValue = new ExtraFieldValue('user');
  356. $courseFieldValue->saveFieldValues($extra);
  357. } else {
  358. // Create notify settings by default
  359. self::update_extra_field_value(
  360. $userId,
  361. 'mail_notify_invitation',
  362. '1'
  363. );
  364. self::update_extra_field_value(
  365. $userId,
  366. 'mail_notify_message',
  367. '1'
  368. );
  369. self::update_extra_field_value(
  370. $userId,
  371. 'mail_notify_group_message',
  372. '1'
  373. );
  374. }
  375. self::update_extra_field_value(
  376. $userId,
  377. 'already_logged_in',
  378. 'false'
  379. );
  380. if (!empty($redirectToURLAfterLogin) && api_get_configuration_value('plugin_redirection_enabled')) {
  381. RedirectionPlugin::insert($userId, $redirectToURLAfterLogin);
  382. }
  383. if (!empty($email) && $send_mail) {
  384. $recipient_name = api_get_person_name(
  385. $firstName,
  386. $lastName,
  387. null,
  388. PERSON_NAME_EMAIL_ADDRESS
  389. );
  390. $tplSubject = new Template(
  391. null,
  392. false,
  393. false,
  394. false,
  395. false,
  396. false
  397. );
  398. $layoutSubject = $tplSubject->get_template('mail/subject_registration_platform.tpl');
  399. $emailSubject = $tplSubject->fetch($layoutSubject);
  400. $sender_name = api_get_person_name(
  401. api_get_setting('administratorName'),
  402. api_get_setting('administratorSurname'),
  403. null,
  404. PERSON_NAME_EMAIL_ADDRESS
  405. );
  406. $email_admin = api_get_setting('emailAdministrator');
  407. $url = api_get_path(WEB_PATH);
  408. if (api_is_multiple_url_enabled()) {
  409. $access_url_id = api_get_current_access_url_id();
  410. if ($access_url_id != -1) {
  411. $urlInfo = api_get_access_url($access_url_id);
  412. if ($urlInfo) {
  413. $url = $urlInfo['url'];
  414. }
  415. }
  416. }
  417. $tplContent = new Template(
  418. null,
  419. false,
  420. false,
  421. false,
  422. false,
  423. false
  424. );
  425. // variables for the default template
  426. $tplContent->assign('complete_name', stripslashes(api_get_person_name($firstName, $lastName)));
  427. $tplContent->assign('login_name', $loginName);
  428. $tplContent->assign('original_password', stripslashes($original_password));
  429. $tplContent->assign('mailWebPath', $url);
  430. $tplContent->assign('new_user', $user);
  431. $layoutContent = $tplContent->get_template('mail/content_registration_platform.tpl');
  432. $emailBody = $tplContent->fetch($layoutContent);
  433. $userInfo = api_get_user_info($userId);
  434. $mailTemplateManager = new MailTemplateManager();
  435. /* MANAGE EVENT WITH MAIL */
  436. if (EventsMail::check_if_using_class('user_registration')) {
  437. $values["about_user"] = $return;
  438. $values["password"] = $original_password;
  439. $values["send_to"] = [$return];
  440. $values["prior_lang"] = null;
  441. EventsDispatcher::events('user_registration', $values);
  442. } else {
  443. $phoneNumber = isset($extra['mobile_phone_number']) ? $extra['mobile_phone_number'] : null;
  444. $additionalParameters = [
  445. 'smsType' => SmsPlugin::WELCOME_LOGIN_PASSWORD,
  446. 'userId' => $return,
  447. 'mobilePhoneNumber' => $phoneNumber,
  448. 'password' => $original_password,
  449. ];
  450. $emailBodyTemplate = '';
  451. if (!empty($emailTemplate)) {
  452. if (isset($emailTemplate['content_registration_platform.tpl']) &&
  453. !empty($emailTemplate['content_registration_platform.tpl'])
  454. ) {
  455. $emailBodyTemplate = $mailTemplateManager->parseTemplate(
  456. $emailTemplate['content_registration_platform.tpl'],
  457. $userInfo
  458. );
  459. }
  460. }
  461. $twoEmail = api_get_configuration_value('send_two_inscription_confirmation_mail');
  462. if ($twoEmail === true) {
  463. $layoutContent = $tplContent->get_template('mail/new_user_first_email_confirmation.tpl');
  464. $emailBody = $tplContent->fetch($layoutContent);
  465. if (!empty($emailBodyTemplate) &&
  466. isset($emailTemplate['new_user_first_email_confirmation.tpl']) &&
  467. !empty($emailTemplate['new_user_first_email_confirmation.tpl'])
  468. ) {
  469. $emailBody = $mailTemplateManager->parseTemplate(
  470. $emailTemplate['new_user_first_email_confirmation.tpl'],
  471. $userInfo
  472. );
  473. }
  474. api_mail_html(
  475. $recipient_name,
  476. $email,
  477. $emailSubject,
  478. $emailBody,
  479. $sender_name,
  480. $email_admin,
  481. null,
  482. null,
  483. null,
  484. $additionalParameters,
  485. $creatorEmail
  486. );
  487. $layoutContent = $tplContent->get_template('mail/new_user_second_email_confirmation.tpl');
  488. $emailBody = $tplContent->fetch($layoutContent);
  489. if (!empty($emailBodyTemplate) &&
  490. isset($emailTemplate['new_user_second_email_confirmation.tpl']) &&
  491. !empty($emailTemplate['new_user_second_email_confirmation.tpl'])
  492. ) {
  493. $emailBody = $mailTemplateManager->parseTemplate(
  494. $emailTemplate['new_user_second_email_confirmation.tpl'],
  495. $userInfo
  496. );
  497. }
  498. api_mail_html(
  499. $recipient_name,
  500. $email,
  501. $emailSubject,
  502. $emailBody,
  503. $sender_name,
  504. $email_admin,
  505. null,
  506. null,
  507. null,
  508. $additionalParameters,
  509. $creatorEmail
  510. );
  511. } else {
  512. if (!empty($emailBodyTemplate)) {
  513. $emailBody = $emailBodyTemplate;
  514. }
  515. $sendToInbox = api_get_configuration_value('send_inscription_msg_to_inbox');
  516. if ($sendToInbox) {
  517. $adminList = self::get_all_administrators();
  518. $senderId = 1;
  519. if (!empty($adminList)) {
  520. $adminInfo = current($adminList);
  521. $senderId = $adminInfo['user_id'];
  522. }
  523. MessageManager::send_message_simple(
  524. $userId,
  525. $emailSubject,
  526. $emailBody,
  527. $senderId
  528. );
  529. } else {
  530. api_mail_html(
  531. $recipient_name,
  532. $email,
  533. $emailSubject,
  534. $emailBody,
  535. $sender_name,
  536. $email_admin,
  537. null,
  538. null,
  539. null,
  540. $additionalParameters,
  541. $creatorEmail
  542. );
  543. }
  544. }
  545. $notification = api_get_configuration_value('send_notification_when_user_added');
  546. if (!empty($notification) && isset($notification['admins']) && is_array($notification['admins'])) {
  547. foreach ($notification['admins'] as $adminId) {
  548. $emailSubjectToAdmin = get_lang('UserAdded').': '.api_get_person_name($firstName, $lastName);
  549. MessageManager::send_message_simple($adminId, $emailSubjectToAdmin, $emailBody, $userId);
  550. }
  551. }
  552. }
  553. if ($sendEmailToAllAdmins) {
  554. $adminList = self::get_all_administrators();
  555. $tplContent = new Template(
  556. null,
  557. false,
  558. false,
  559. false,
  560. false,
  561. false
  562. );
  563. // variables for the default template
  564. $tplContent->assign('complete_name', stripslashes(api_get_person_name($firstName, $lastName)));
  565. $tplContent->assign('user_added', $user);
  566. $renderer = FormValidator::getDefaultRenderer();
  567. // Form template
  568. $elementTemplate = ' {label}: {element} <br />';
  569. $renderer->setElementTemplate($elementTemplate);
  570. /** @var FormValidator $form */
  571. $form->freeze(null, $elementTemplate);
  572. $form->removeElement('submit');
  573. $formData = $form->returnForm();
  574. $url = api_get_path(WEB_CODE_PATH).'admin/user_information.php?user_id='.$user->getId();
  575. $tplContent->assign('link', Display::url($url, $url));
  576. $tplContent->assign('form', $formData);
  577. $layoutContent = $tplContent->get_template('mail/content_registration_platform_to_admin.tpl');
  578. $emailBody = $tplContent->fetch($layoutContent);
  579. if (!empty($emailBodyTemplate) &&
  580. isset($emailTemplate['content_registration_platform_to_admin.tpl']) &&
  581. !empty($emailTemplate['content_registration_platform_to_admin.tpl'])
  582. ) {
  583. $emailBody = $mailTemplateManager->parseTemplate(
  584. $emailTemplate['content_registration_platform_to_admin.tpl'],
  585. $userInfo
  586. );
  587. }
  588. $subject = get_lang('UserAdded');
  589. foreach ($adminList as $adminId => $data) {
  590. MessageManager::send_message_simple(
  591. $adminId,
  592. $subject,
  593. $emailBody,
  594. $userId
  595. );
  596. }
  597. }
  598. /* ENDS MANAGE EVENT WITH MAIL */
  599. }
  600. if (!empty($hook)) {
  601. $hook->setEventData([
  602. 'return' => $userId,
  603. 'originalPassword' => $original_password,
  604. ]);
  605. $hook->notifyCreateUser(HOOK_EVENT_TYPE_POST);
  606. }
  607. Event::addEvent(LOG_USER_CREATE, LOG_USER_ID, $userId);
  608. } else {
  609. Display::addFlash(
  610. Display::return_message(get_lang('ErrorContactPlatformAdmin'))
  611. );
  612. return false;
  613. }
  614. return $return;
  615. }
  616. /**
  617. * Can user be deleted? This function checks whether there's a course
  618. * in which the given user is the
  619. * only course administrator. If that is the case, the user can't be
  620. * deleted because the course would remain without a course admin.
  621. *
  622. * @param int $user_id The user id
  623. *
  624. * @return bool true if user can be deleted
  625. *
  626. * @assert (null) === false
  627. * @assert (-1) === false
  628. * @assert ('abc') === false
  629. */
  630. public static function canDeleteUser($user_id)
  631. {
  632. $deny = api_get_configuration_value('deny_delete_users');
  633. if ($deny) {
  634. return false;
  635. }
  636. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  637. $user_id = (int) $user_id;
  638. if (empty($user_id)) {
  639. return false;
  640. }
  641. $sql = "SELECT * FROM $table_course_user
  642. WHERE status = 1 AND user_id = ".$user_id;
  643. $res = Database::query($sql);
  644. while ($course = Database::fetch_object($res)) {
  645. $sql = "SELECT id FROM $table_course_user
  646. WHERE status=1 AND c_id = ".intval($course->c_id);
  647. $res2 = Database::query($sql);
  648. if (Database::num_rows($res2) == 1) {
  649. return false;
  650. }
  651. }
  652. return true;
  653. }
  654. /**
  655. * Delete a user from the platform, and all its belongings. This is a
  656. * very dangerous function that should only be accessible by
  657. * super-admins. Other roles should only be able to disable a user,
  658. * which removes access to the platform but doesn't delete anything.
  659. *
  660. * @param int The ID of th user to be deleted
  661. *
  662. * @throws Exception
  663. *
  664. * @return bool true if user is successfully deleted, false otherwise
  665. * @assert (null) === false
  666. * @assert ('abc') === false
  667. */
  668. public static function delete_user($user_id)
  669. {
  670. $user_id = (int) $user_id;
  671. if (empty($user_id)) {
  672. return false;
  673. }
  674. if (!self::canDeleteUser($user_id)) {
  675. return false;
  676. }
  677. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  678. $usergroup_rel_user = Database::get_main_table(TABLE_USERGROUP_REL_USER);
  679. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  680. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  681. $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
  682. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  683. $table_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  684. $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  685. $table_group = Database::get_course_table(TABLE_GROUP_USER);
  686. $table_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  687. // Unsubscribe the user from all groups in all his courses
  688. $sql = "SELECT c.id
  689. FROM $table_course c
  690. INNER JOIN $table_course_user cu
  691. ON (c.id = cu.c_id)
  692. WHERE
  693. cu.user_id = '".$user_id."' AND
  694. relation_type<>".COURSE_RELATION_TYPE_RRHH."
  695. ";
  696. $res = Database::query($sql);
  697. while ($course = Database::fetch_object($res)) {
  698. $sql = "DELETE FROM $table_group
  699. WHERE c_id = {$course->id} AND user_id = $user_id";
  700. Database::query($sql);
  701. }
  702. // Unsubscribe user from usergroup_rel_user
  703. $sql = "DELETE FROM $usergroup_rel_user WHERE user_id = '".$user_id."'";
  704. Database::query($sql);
  705. // Unsubscribe user from all courses
  706. $sql = "DELETE FROM $table_course_user WHERE user_id = '".$user_id."'";
  707. Database::query($sql);
  708. // Unsubscribe user from all courses in sessions
  709. $sql = "DELETE FROM $table_session_course_user WHERE user_id = '".$user_id."'";
  710. Database::query($sql);
  711. // If the user was added as a id_coach then set the current admin as coach see BT#
  712. $currentUserId = api_get_user_id();
  713. $sql = "UPDATE $table_session SET id_coach = $currentUserId
  714. WHERE id_coach = '".$user_id."'";
  715. Database::query($sql);
  716. $sql = "UPDATE $table_session SET id_coach = $currentUserId
  717. WHERE session_admin_id = '".$user_id."'";
  718. Database::query($sql);
  719. // Unsubscribe user from all sessions
  720. $sql = "DELETE FROM $table_session_user
  721. WHERE user_id = '".$user_id."'";
  722. Database::query($sql);
  723. if (api_get_configuration_value('plugin_redirection_enabled')) {
  724. RedirectionPlugin::deleteUserRedirection($user_id);
  725. }
  726. // Delete user picture
  727. /* TODO: Logic about api_get_setting('split_users_upload_directory') == 'true'
  728. a user has 4 different sized photos to be deleted. */
  729. $user_info = api_get_user_info($user_id);
  730. if (strlen($user_info['picture_uri']) > 0) {
  731. $path = self::getUserPathById($user_id, 'system');
  732. $img_path = $path.$user_info['picture_uri'];
  733. if (file_exists($img_path)) {
  734. unlink($img_path);
  735. }
  736. }
  737. // Delete the personal course categories
  738. $course_cat_table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  739. $sql = "DELETE FROM $course_cat_table WHERE user_id = '".$user_id."'";
  740. Database::query($sql);
  741. // Delete user from the admin table
  742. $sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
  743. Database::query($sql);
  744. // Delete the personal agenda-items from this user
  745. $agenda_table = Database::get_main_table(TABLE_PERSONAL_AGENDA);
  746. $sql = "DELETE FROM $agenda_table WHERE user = '".$user_id."'";
  747. Database::query($sql);
  748. $gradebook_results_table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
  749. $sql = 'DELETE FROM '.$gradebook_results_table.' WHERE user_id = '.$user_id;
  750. Database::query($sql);
  751. $extraFieldValue = new ExtraFieldValue('user');
  752. $extraFieldValue->deleteValuesByItem($user_id);
  753. UrlManager::deleteUserFromAllUrls($user_id);
  754. if (api_get_setting('allow_social_tool') === 'true') {
  755. $userGroup = new UserGroup();
  756. //Delete user from portal groups
  757. $group_list = $userGroup->get_groups_by_user($user_id);
  758. if (!empty($group_list)) {
  759. foreach ($group_list as $group_id => $data) {
  760. $userGroup->delete_user_rel_group($user_id, $group_id);
  761. }
  762. }
  763. // Delete user from friend lists
  764. SocialManager::remove_user_rel_user($user_id, true);
  765. }
  766. // Removing survey invitation
  767. SurveyManager::delete_all_survey_invitations_by_user($user_id);
  768. // Delete students works
  769. $sql = "DELETE FROM $table_work WHERE user_id = $user_id AND c_id <> 0";
  770. Database::query($sql);
  771. $sql = "UPDATE c_item_property SET to_user_id = NULL
  772. WHERE to_user_id = '".$user_id."'";
  773. Database::query($sql);
  774. $sql = "UPDATE c_item_property SET insert_user_id = NULL
  775. WHERE insert_user_id = '".$user_id."'";
  776. Database::query($sql);
  777. $sql = "UPDATE c_item_property SET lastedit_user_id = NULL
  778. WHERE lastedit_user_id = '".$user_id."'";
  779. Database::query($sql);
  780. // Skills
  781. $em = Database::getManager();
  782. $criteria = ['user' => $user_id];
  783. $skills = $em->getRepository('ChamiloCoreBundle:SkillRelUser')->findBy($criteria);
  784. if ($skills) {
  785. /** @var SkillRelUser $skill */
  786. foreach ($skills as $skill) {
  787. $comments = $skill->getComments();
  788. if ($comments) {
  789. /** @var SkillRelUserComment $comment */
  790. foreach ($comments as $comment) {
  791. $em->remove($comment);
  792. }
  793. }
  794. $em->remove($skill);
  795. }
  796. $em->flush();
  797. }
  798. // ExtraFieldSavedSearch
  799. $criteria = ['user' => $user_id];
  800. $searchList = $em->getRepository('ChamiloCoreBundle:ExtraFieldSavedSearch')->findBy($criteria);
  801. if ($searchList) {
  802. foreach ($searchList as $search) {
  803. $em->remove($search);
  804. }
  805. $em->flush();
  806. }
  807. $connection = Database::getManager()->getConnection();
  808. $tableExists = $connection->getSchemaManager()->tablesExist(['plugin_bbb_room']);
  809. if ($tableExists) {
  810. // Delete user from database
  811. $sql = "DELETE FROM plugin_bbb_room WHERE participant_id = $user_id";
  812. Database::query($sql);
  813. }
  814. // Delete user/ticket relationships :(
  815. $tableExists = $connection->getSchemaManager()->tablesExist(['ticket_ticket']);
  816. if ($tableExists) {
  817. TicketManager::deleteUserFromTicketSystem($user_id);
  818. }
  819. $tableExists = $connection->getSchemaManager()->tablesExist(['c_lp_category_user']);
  820. if ($tableExists) {
  821. $sql = "DELETE FROM c_lp_category_user WHERE user_id = $user_id";
  822. Database::query($sql);
  823. }
  824. $app_plugin = new AppPlugin();
  825. $app_plugin->performActionsWhenDeletingItem('user', $user_id);
  826. // Delete user from database
  827. $sql = "DELETE FROM $table_user WHERE id = '".$user_id."'";
  828. Database::query($sql);
  829. // Add event to system log
  830. $user_id_manager = api_get_user_id();
  831. Event::addEvent(
  832. LOG_USER_DELETE,
  833. LOG_USER_ID,
  834. $user_id,
  835. api_get_utc_datetime(),
  836. $user_id_manager
  837. );
  838. Event::addEvent(
  839. LOG_USER_DELETE,
  840. LOG_USER_OBJECT,
  841. $user_info,
  842. api_get_utc_datetime(),
  843. $user_id_manager
  844. );
  845. $cacheAvailable = api_get_configuration_value('apc');
  846. if ($cacheAvailable === true) {
  847. $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$user_id;
  848. if (apcu_exists($apcVar)) {
  849. apcu_delete($apcVar);
  850. }
  851. }
  852. return true;
  853. }
  854. /**
  855. * Deletes users completely. Can be called either as:
  856. * - UserManager::delete_users(1, 2, 3); or
  857. * - UserManager::delete_users(array(1, 2, 3));.
  858. *
  859. * @param array|int $ids
  860. *
  861. * @return bool True if at least one user was successfuly deleted. False otherwise.
  862. *
  863. * @author Laurent Opprecht
  864. *
  865. * @uses \UserManager::delete_user() to actually delete each user
  866. * @assert (null) === false
  867. * @assert (-1) === false
  868. * @assert (array(-1)) === false
  869. */
  870. public static function delete_users($ids = [])
  871. {
  872. $result = false;
  873. $ids = is_array($ids) ? $ids : func_get_args();
  874. if (!is_array($ids) || count($ids) == 0) {
  875. return false;
  876. }
  877. $ids = array_map('intval', $ids);
  878. foreach ($ids as $id) {
  879. if (empty($id) || $id < 1) {
  880. continue;
  881. }
  882. $deleted = self::delete_user($id);
  883. $result = $deleted || $result;
  884. }
  885. return $result;
  886. }
  887. /**
  888. * Disable users. Can be called either as:
  889. * - UserManager::deactivate_users(1, 2, 3);
  890. * - UserManager::deactivate_users(array(1, 2, 3));.
  891. *
  892. * @param array|int $ids
  893. *
  894. * @return bool
  895. *
  896. * @author Laurent Opprecht
  897. * @assert (null) === false
  898. * @assert (array(-1)) === false
  899. */
  900. public static function deactivate_users($ids = [])
  901. {
  902. if (empty($ids)) {
  903. return false;
  904. }
  905. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  906. $ids = is_array($ids) ? $ids : func_get_args();
  907. $ids = array_map('intval', $ids);
  908. $ids = implode(',', $ids);
  909. $sql = "UPDATE $table_user SET active = 0 WHERE id IN ($ids)";
  910. $r = Database::query($sql);
  911. if ($r !== false) {
  912. Event::addEvent(LOG_USER_DISABLE, LOG_USER_ID, $ids);
  913. return true;
  914. }
  915. return false;
  916. }
  917. /**
  918. * Enable users. Can be called either as:
  919. * - UserManager::activate_users(1, 2, 3);
  920. * - UserManager::activate_users(array(1, 2, 3));.
  921. *
  922. * @param array|int IDs of the users to enable
  923. *
  924. * @return bool
  925. *
  926. * @author Laurent Opprecht
  927. * @assert (null) === false
  928. * @assert (array(-1)) === false
  929. */
  930. public static function activate_users($ids = [])
  931. {
  932. if (empty($ids)) {
  933. return false;
  934. }
  935. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  936. $ids = is_array($ids) ? $ids : func_get_args();
  937. $ids = array_map('intval', $ids);
  938. $ids = implode(',', $ids);
  939. $sql = "UPDATE $table_user SET active = 1 WHERE id IN ($ids)";
  940. $r = Database::query($sql);
  941. if ($r !== false) {
  942. Event::addEvent(LOG_USER_ENABLE, LOG_USER_ID, $ids);
  943. return true;
  944. }
  945. return false;
  946. }
  947. /**
  948. * Update user information with new openid.
  949. *
  950. * @param int $user_id
  951. * @param string $openid
  952. *
  953. * @return bool true if the user information was updated
  954. * @assert (false,'') === false
  955. * @assert (-1,'') === false
  956. */
  957. public static function update_openid($user_id, $openid)
  958. {
  959. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  960. if ($user_id != strval(intval($user_id))) {
  961. return false;
  962. }
  963. if ($user_id === false) {
  964. return false;
  965. }
  966. $sql = "UPDATE $table_user SET
  967. openid='".Database::escape_string($openid)."'";
  968. $sql .= " WHERE id= $user_id";
  969. if (Database::query($sql) !== false) {
  970. return true;
  971. }
  972. return false;
  973. }
  974. /**
  975. * Update user information with all the parameters passed to this function.
  976. *
  977. * @param int $user_id The ID of the user to be updated
  978. * @param string $firstname The user's firstname
  979. * @param string $lastname The user's lastname
  980. * @param string $username The user's username (login)
  981. * @param string $password The user's password
  982. * @param string $auth_source The authentication source (default: "platform")
  983. * @param string $email The user's e-mail address
  984. * @param int $status The user's status
  985. * @param string $official_code The user's official code (usually just an internal institutional code)
  986. * @param string $phone The user's phone number
  987. * @param string $picture_uri The user's picture URL (internal to the Chamilo directory)
  988. * @param string $expiration_date The date at which this user will be automatically disabled
  989. * @param int $active Whether this account needs to be enabled (1) or disabled (0)
  990. * @param int $creator_id The user ID of the person who registered this user (optional, defaults to null)
  991. * @param int $hr_dept_id The department of HR in which the user is registered (optional, defaults to 0)
  992. * @param array $extra Additional fields to add to this user as extra fields (defaults to null)
  993. * @param string $language The language to which the user account will be set
  994. * @param string $encrypt_method The cipher method. This parameter is deprecated. It will use the system's default
  995. * @param bool $send_email Whether to send an e-mail to the user after the update is complete
  996. * @param int $reset_password Method used to reset password (0, 1, 2 or 3 - see usage examples for details)
  997. * @param string $address
  998. * @param array $emailTemplate
  999. *
  1000. * @return bool|int False on error, or the user ID if the user information was updated
  1001. * @assert (false, false, false, false, false, false, false, false, false, false, false, false, false) === false
  1002. */
  1003. public static function update_user(
  1004. $user_id,
  1005. $firstname,
  1006. $lastname,
  1007. $username,
  1008. $password = null,
  1009. $auth_source = null,
  1010. $email,
  1011. $status,
  1012. $official_code,
  1013. $phone,
  1014. $picture_uri,
  1015. $expiration_date,
  1016. $active,
  1017. $creator_id = null,
  1018. $hr_dept_id = 0,
  1019. $extra = null,
  1020. $language = 'english',
  1021. $encrypt_method = '',
  1022. $send_email = false,
  1023. $reset_password = 0,
  1024. $address = null,
  1025. $emailTemplate = []
  1026. ) {
  1027. $hook = HookUpdateUser::create();
  1028. if (!empty($hook)) {
  1029. $hook->notifyUpdateUser(HOOK_EVENT_TYPE_PRE);
  1030. }
  1031. $original_password = $password;
  1032. $user_id = (int) $user_id;
  1033. $creator_id = (int) $creator_id;
  1034. if (empty($user_id)) {
  1035. return false;
  1036. }
  1037. $userManager = self::getManager();
  1038. /** @var User $user */
  1039. $user = self::getRepository()->find($user_id);
  1040. if (empty($user)) {
  1041. return false;
  1042. }
  1043. if ($reset_password == 0) {
  1044. $password = null;
  1045. $auth_source = $user->getAuthSource();
  1046. } elseif ($reset_password == 1) {
  1047. $original_password = $password = api_generate_password();
  1048. $auth_source = PLATFORM_AUTH_SOURCE;
  1049. } elseif ($reset_password == 2) {
  1050. //$password = $password;
  1051. $auth_source = PLATFORM_AUTH_SOURCE;
  1052. } elseif ($reset_password == 3) {
  1053. //$password = $password;
  1054. //$auth_source = $auth_source;
  1055. }
  1056. // Checking the user language
  1057. $languages = api_get_languages();
  1058. if (!in_array($language, $languages['folder'])) {
  1059. $language = api_get_setting('platformLanguage');
  1060. }
  1061. $change_active = 0;
  1062. $isUserActive = $user->getActive();
  1063. if ($isUserActive != $active) {
  1064. $change_active = 1;
  1065. }
  1066. $originalUsername = $user->getUsername();
  1067. // If username is different from original then check if it exists.
  1068. if ($originalUsername !== $username) {
  1069. $available = self::is_username_available($username);
  1070. if ($available === false) {
  1071. return false;
  1072. }
  1073. }
  1074. if (!empty($expiration_date)) {
  1075. $expiration_date = api_get_utc_datetime($expiration_date);
  1076. $expiration_date = new \DateTime(
  1077. $expiration_date,
  1078. new DateTimeZone('UTC')
  1079. );
  1080. }
  1081. $user
  1082. ->setLastname($lastname)
  1083. ->setFirstname($firstname)
  1084. ->setUsername($username)
  1085. ->setStatus($status)
  1086. ->setAuthSource($auth_source)
  1087. ->setLanguage($language)
  1088. ->setEmail($email)
  1089. ->setOfficialCode($official_code)
  1090. ->setPhone($phone)
  1091. ->setAddress($address)
  1092. ->setPictureUri($picture_uri)
  1093. ->setExpirationDate($expiration_date)
  1094. ->setActive($active)
  1095. ->setEnabled($active)
  1096. ->setHrDeptId($hr_dept_id)
  1097. ;
  1098. if (!is_null($password)) {
  1099. $user->setPlainPassword($password);
  1100. }
  1101. $userManager->updateUser($user, true);
  1102. if ($change_active == 1) {
  1103. if ($active == 1) {
  1104. $event_title = LOG_USER_ENABLE;
  1105. } else {
  1106. $event_title = LOG_USER_DISABLE;
  1107. }
  1108. Event::addEvent($event_title, LOG_USER_ID, $user_id);
  1109. }
  1110. if (is_array($extra) && count($extra) > 0) {
  1111. $res = true;
  1112. foreach ($extra as $fname => $fvalue) {
  1113. $res = $res && self::update_extra_field_value(
  1114. $user_id,
  1115. $fname,
  1116. $fvalue
  1117. );
  1118. }
  1119. }
  1120. if (!empty($email) && $send_email) {
  1121. $recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
  1122. $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
  1123. $sender_name = api_get_person_name(
  1124. api_get_setting('administratorName'),
  1125. api_get_setting('administratorSurname'),
  1126. null,
  1127. PERSON_NAME_EMAIL_ADDRESS
  1128. );
  1129. $email_admin = api_get_setting('emailAdministrator');
  1130. $url = api_get_path(WEB_PATH);
  1131. if (api_is_multiple_url_enabled()) {
  1132. $access_url_id = api_get_current_access_url_id();
  1133. if ($access_url_id != -1) {
  1134. $url = api_get_access_url($access_url_id);
  1135. $url = $url['url'];
  1136. }
  1137. }
  1138. $tplContent = new Template(
  1139. null,
  1140. false,
  1141. false,
  1142. false,
  1143. false,
  1144. false
  1145. );
  1146. // variables for the default template
  1147. $tplContent->assign('complete_name', stripslashes(api_get_person_name($firstname, $lastname)));
  1148. $tplContent->assign('login_name', $username);
  1149. $originalPassword = '';
  1150. if ($reset_password > 0) {
  1151. $originalPassword = stripslashes($original_password);
  1152. }
  1153. $tplContent->assign('original_password', $originalPassword);
  1154. $tplContent->assign('portal_url', $url);
  1155. $layoutContent = $tplContent->get_template('mail/user_edit_content.tpl');
  1156. $emailBody = $tplContent->fetch($layoutContent);
  1157. $mailTemplateManager = new MailTemplateManager();
  1158. if (!empty($emailTemplate) &&
  1159. isset($emailTemplate['user_edit_content.tpl']) &&
  1160. !empty($emailTemplate['user_edit_content.tpl'])
  1161. ) {
  1162. $userInfo = api_get_user_info($user_id);
  1163. $emailBody = $mailTemplateManager->parseTemplate($emailTemplate['user_edit_content.tpl'], $userInfo);
  1164. }
  1165. $creatorInfo = api_get_user_info($creator_id);
  1166. $creatorEmail = isset($creatorInfo['email']) ? $creatorInfo['email'] : '';
  1167. api_mail_html(
  1168. $recipient_name,
  1169. $email,
  1170. $emailsubject,
  1171. $emailBody,
  1172. $sender_name,
  1173. $email_admin,
  1174. null,
  1175. null,
  1176. null,
  1177. null,
  1178. $creatorEmail
  1179. );
  1180. }
  1181. if (!empty($hook)) {
  1182. $hook->setEventData(['user' => $user]);
  1183. $hook->notifyUpdateUser(HOOK_EVENT_TYPE_POST);
  1184. }
  1185. $cacheAvailable = api_get_configuration_value('apc');
  1186. if ($cacheAvailable === true) {
  1187. $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$user_id;
  1188. if (apcu_exists($apcVar)) {
  1189. apcu_delete($apcVar);
  1190. }
  1191. }
  1192. return $user->getId();
  1193. }
  1194. /**
  1195. * Disables a user.
  1196. *
  1197. * @param int User id
  1198. *
  1199. * @return bool
  1200. *
  1201. * @uses \UserManager::change_active_state() to actually disable the user
  1202. * @assert (0) === false
  1203. */
  1204. public static function disable($user_id)
  1205. {
  1206. if (empty($user_id)) {
  1207. return false;
  1208. }
  1209. self::change_active_state($user_id, 0);
  1210. return true;
  1211. }
  1212. /**
  1213. * Enable a user.
  1214. *
  1215. * @param int User id
  1216. *
  1217. * @return bool
  1218. *
  1219. * @uses \UserManager::change_active_state() to actually disable the user
  1220. * @assert (0) === false
  1221. */
  1222. public static function enable($user_id)
  1223. {
  1224. if (empty($user_id)) {
  1225. return false;
  1226. }
  1227. self::change_active_state($user_id, 1);
  1228. return true;
  1229. }
  1230. /**
  1231. * Returns the user's id based on the original id and field name in
  1232. * the extra fields. Returns 0 if no user was found. This function is
  1233. * mostly useful in the context of a web services-based sinchronization.
  1234. *
  1235. * @param string Original user id
  1236. * @param string Original field name
  1237. *
  1238. * @return int User id
  1239. * @assert ('0','---') === 0
  1240. */
  1241. public static function get_user_id_from_original_id(
  1242. $original_user_id_value,
  1243. $original_user_id_name
  1244. ) {
  1245. $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
  1246. $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  1247. $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
  1248. $original_user_id_name = Database::escape_string($original_user_id_name);
  1249. $original_user_id_value = Database::escape_string($original_user_id_value);
  1250. $sql = "SELECT item_id as user_id
  1251. FROM $t_uf uf
  1252. INNER JOIN $t_ufv ufv
  1253. ON ufv.field_id = uf.id
  1254. WHERE
  1255. variable = '$original_user_id_name' AND
  1256. value = '$original_user_id_value' AND
  1257. extra_field_type = $extraFieldType
  1258. ";
  1259. $res = Database::query($sql);
  1260. $row = Database::fetch_object($res);
  1261. if ($row) {
  1262. return $row->user_id;
  1263. }
  1264. return 0;
  1265. }
  1266. /**
  1267. * Check if a username is available.
  1268. *
  1269. * @param string $username the wanted username
  1270. *
  1271. * @return bool true if the wanted username is available
  1272. * @assert ('') === false
  1273. * @assert ('xyzxyzxyz') === true
  1274. */
  1275. public static function is_username_available($username)
  1276. {
  1277. if (empty($username)) {
  1278. return false;
  1279. }
  1280. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1281. $sql = "SELECT username FROM $table_user
  1282. WHERE username = '".Database::escape_string($username)."'";
  1283. $res = Database::query($sql);
  1284. return Database::num_rows($res) == 0;
  1285. }
  1286. /**
  1287. * Creates a username using person's names, i.e. creates jmontoya from Julio Montoya.
  1288. *
  1289. * @param string $firstname the first name of the user
  1290. * @param string $lastname the last name of the user
  1291. *
  1292. * @return string suggests a username that contains only ASCII-letters and digits,
  1293. * without check for uniqueness within the system
  1294. *
  1295. * @author Julio Montoya Armas
  1296. * @author Ivan Tcholakov, 2009 - rework about internationalization.
  1297. * @assert ('','') === false
  1298. * @assert ('a','b') === 'ab'
  1299. */
  1300. public static function create_username($firstname, $lastname)
  1301. {
  1302. if (empty($firstname) && empty($lastname)) {
  1303. return false;
  1304. }
  1305. // The first letter only.
  1306. $firstname = api_substr(
  1307. preg_replace(USERNAME_PURIFIER, '', $firstname),
  1308. 0,
  1309. 1
  1310. );
  1311. //Looking for a space in the lastname
  1312. $pos = api_strpos($lastname, ' ');
  1313. if ($pos !== false) {
  1314. $lastname = api_substr($lastname, 0, $pos);
  1315. }
  1316. $lastname = preg_replace(USERNAME_PURIFIER, '', $lastname);
  1317. $username = $firstname.$lastname;
  1318. if (empty($username)) {
  1319. $username = 'user';
  1320. }
  1321. $username = URLify::transliterate($username);
  1322. return strtolower(substr($username, 0, USERNAME_MAX_LENGTH - 3));
  1323. }
  1324. /**
  1325. * Creates a unique username, using:
  1326. * 1. the first name and the last name of a user;
  1327. * 2. an already created username but not checked for uniqueness yet.
  1328. *
  1329. * @param string $firstname The first name of a given user. If the second parameter $lastname is NULL, then this
  1330. * parameter is treated as username which is to be checked f
  1331. * or uniqueness and to be modified when it is necessary.
  1332. * @param string $lastname the last name of the user
  1333. *
  1334. * @return string Returns a username that contains only ASCII-letters and digits and that is unique in the system.
  1335. * Note: When the method is called several times with same parameters,
  1336. * its results look like the following sequence: ivan, ivan2, ivan3, ivan4, ...
  1337. *
  1338. * @author Ivan Tcholakov, 2009
  1339. */
  1340. public static function create_unique_username($firstname, $lastname = null)
  1341. {
  1342. if (is_null($lastname)) {
  1343. // In this case the actual input parameter $firstname should contain ASCII-letters and digits only.
  1344. // For making this method tolerant of mistakes,
  1345. // let us transliterate and purify the suggested input username anyway.
  1346. // So, instead of the sentence $username = $firstname; we place the following:
  1347. $username = strtolower(preg_replace(USERNAME_PURIFIER, '', $firstname));
  1348. } else {
  1349. $username = self::create_username($firstname, $lastname);
  1350. }
  1351. if (!self::is_username_available($username)) {
  1352. $i = 2;
  1353. $temp_username = substr($username, 0, USERNAME_MAX_LENGTH - strlen((string) $i)).$i;
  1354. while (!self::is_username_available($temp_username)) {
  1355. $i++;
  1356. $temp_username = substr($username, 0, USERNAME_MAX_LENGTH - strlen((string) $i)).$i;
  1357. }
  1358. $username = $temp_username;
  1359. }
  1360. $username = URLify::transliterate($username);
  1361. return $username;
  1362. }
  1363. /**
  1364. * Modifies a given username accordingly to the specification for valid characters and length.
  1365. *
  1366. * @param $username string The input username
  1367. * @param bool $strict (optional) When this flag is TRUE, the result is guaranteed for full compliance,
  1368. * otherwise compliance may be partial. The default value is FALSE.
  1369. *
  1370. * @return string the resulting purified username
  1371. */
  1372. public static function purify_username($username, $strict = false)
  1373. {
  1374. if ($strict) {
  1375. // 1. Conversion of unacceptable letters (latinian letters with accents for example)
  1376. // into ASCII letters in order they not to be totally removed.
  1377. // 2. Applying the strict purifier.
  1378. // 3. Length limitation.
  1379. $return = api_get_setting('login_is_email') === 'true' ? substr(preg_replace(USERNAME_PURIFIER_MAIL, '', $username), 0, USERNAME_MAX_LENGTH) : substr(preg_replace(USERNAME_PURIFIER, '', $username), 0, USERNAME_MAX_LENGTH);
  1380. $return = URLify::transliterate($return);
  1381. return $return;
  1382. }
  1383. // 1. Applying the shallow purifier.
  1384. // 2. Length limitation.
  1385. return substr(
  1386. preg_replace(USERNAME_PURIFIER_SHALLOW, '', $username),
  1387. 0,
  1388. USERNAME_MAX_LENGTH
  1389. );
  1390. }
  1391. /**
  1392. * Checks whether the user id exists in the database.
  1393. *
  1394. * @param int $userId User id
  1395. *
  1396. * @return bool True if user id was found, false otherwise
  1397. */
  1398. public static function is_user_id_valid($userId)
  1399. {
  1400. $resultData = Database::select(
  1401. 'COUNT(1) AS count',
  1402. Database::get_main_table(TABLE_MAIN_USER),
  1403. [
  1404. 'where' => ['id = ?' => (int) $userId],
  1405. ],
  1406. 'first'
  1407. );
  1408. if ($resultData === false) {
  1409. return false;
  1410. }
  1411. return $resultData['count'] > 0;
  1412. }
  1413. /**
  1414. * Checks whether a given username matches to the specification strictly.
  1415. * The empty username is assumed here as invalid.
  1416. * Mostly this function is to be used in the user interface built-in validation routines
  1417. * for providing feedback while usernames are enterd manually.
  1418. *
  1419. * @param string $username the input username
  1420. *
  1421. * @return bool returns TRUE if the username is valid, FALSE otherwise
  1422. */
  1423. public static function is_username_valid($username)
  1424. {
  1425. return !empty($username) && $username == self::purify_username($username, true);
  1426. }
  1427. /**
  1428. * Checks whether a username is empty. If the username contains whitespace characters,
  1429. * such as spaces, tabulators, newlines, etc.,
  1430. * it is assumed as empty too. This function is safe for validation unpurified data (during importing).
  1431. *
  1432. * @param string $username the given username
  1433. *
  1434. * @return bool returns TRUE if length of the username exceeds the limit, FALSE otherwise
  1435. */
  1436. public static function is_username_empty($username)
  1437. {
  1438. return strlen(self::purify_username($username, false)) == 0;
  1439. }
  1440. /**
  1441. * Checks whether a username is too long or not.
  1442. *
  1443. * @param string $username the given username, it should contain only ASCII-letters and digits
  1444. *
  1445. * @return bool returns TRUE if length of the username exceeds the limit, FALSE otherwise
  1446. */
  1447. public static function is_username_too_long($username)
  1448. {
  1449. return strlen($username) > USERNAME_MAX_LENGTH;
  1450. }
  1451. /**
  1452. * Get the users by ID.
  1453. *
  1454. * @param array $ids student ids
  1455. * @param string $active
  1456. * @param string $order
  1457. * @param string $limit
  1458. *
  1459. * @return array $result student information
  1460. */
  1461. public static function get_user_list_by_ids($ids = [], $active = null, $order = null, $limit = null)
  1462. {
  1463. if (empty($ids)) {
  1464. return [];
  1465. }
  1466. $ids = is_array($ids) ? $ids : [$ids];
  1467. $ids = array_map('intval', $ids);
  1468. $ids = implode(',', $ids);
  1469. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1470. $sql = "SELECT * FROM $tbl_user WHERE id IN ($ids)";
  1471. if (!is_null($active)) {
  1472. $sql .= ' AND active='.($active ? '1' : '0');
  1473. }
  1474. if (!is_null($order)) {
  1475. $order = Database::escape_string($order);
  1476. $sql .= ' ORDER BY '.$order;
  1477. }
  1478. if (!is_null($limit)) {
  1479. $limit = Database::escape_string($limit);
  1480. $sql .= ' LIMIT '.$limit;
  1481. }
  1482. $rs = Database::query($sql);
  1483. $result = [];
  1484. while ($row = Database::fetch_array($rs)) {
  1485. $result[] = $row;
  1486. }
  1487. return $result;
  1488. }
  1489. /**
  1490. * Get a list of users of which the given conditions match with an = 'cond'.
  1491. *
  1492. * @param array $conditions a list of condition (example : status=>STUDENT)
  1493. * @param array $order_by a list of fields on which sort
  1494. *
  1495. * @return array an array with all users of the platform
  1496. *
  1497. * @todo security filter order by
  1498. */
  1499. public static function get_user_list(
  1500. $conditions = [],
  1501. $order_by = [],
  1502. $limit_from = false,
  1503. $limit_to = false,
  1504. $idCampus = null
  1505. ) {
  1506. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1507. $userUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  1508. $return_array = [];
  1509. $sql = "SELECT user.* FROM $user_table user ";
  1510. if (api_is_multiple_url_enabled()) {
  1511. if ($idCampus) {
  1512. $urlId = $idCampus;
  1513. } else {
  1514. $urlId = api_get_current_access_url_id();
  1515. }
  1516. $sql .= " INNER JOIN $userUrlTable url_user
  1517. ON (user.user_id = url_user.user_id)
  1518. WHERE url_user.access_url_id = $urlId";
  1519. } else {
  1520. $sql .= " WHERE 1=1 ";
  1521. }
  1522. if (count($conditions) > 0) {
  1523. foreach ($conditions as $field => $value) {
  1524. $field = Database::escape_string($field);
  1525. $value = Database::escape_string($value);
  1526. $sql .= " AND $field = '$value'";
  1527. }
  1528. }
  1529. if (count($order_by) > 0) {
  1530. $sql .= ' ORDER BY '.Database::escape_string(implode(',', $order_by));
  1531. }
  1532. if (is_numeric($limit_from) && is_numeric($limit_from)) {
  1533. $limit_from = (int) $limit_from;
  1534. $limit_to = (int) $limit_to;
  1535. $sql .= " LIMIT $limit_from, $limit_to";
  1536. }
  1537. $sql_result = Database::query($sql);
  1538. while ($result = Database::fetch_array($sql_result)) {
  1539. $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
  1540. $return_array[] = $result;
  1541. }
  1542. return $return_array;
  1543. }
  1544. /**
  1545. * Get a list of users of which the given conditions match with a LIKE '%cond%'.
  1546. *
  1547. * @param array $conditions a list of condition (exemple : status=>STUDENT)
  1548. * @param array $order_by a list of fields on which sort
  1549. * @param bool $simple_like Whether we want a simple LIKE 'abc' or a LIKE '%abc%'
  1550. * @param string $condition Whether we want the filters to be combined by AND or OR
  1551. * @param array $onlyThisUserList
  1552. *
  1553. * @return array an array with all users of the platform
  1554. *
  1555. * @todo optional course code parameter, optional sorting parameters...
  1556. * @todo security filter order_by
  1557. */
  1558. public static function getUserListLike(
  1559. $conditions = [],
  1560. $order_by = [],
  1561. $simple_like = false,
  1562. $condition = 'AND',
  1563. $onlyThisUserList = []
  1564. ) {
  1565. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1566. $tblAccessUrlRelUser = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  1567. $return_array = [];
  1568. $sql_query = "SELECT user.id FROM $user_table user ";
  1569. if (api_is_multiple_url_enabled()) {
  1570. $sql_query .= " INNER JOIN $tblAccessUrlRelUser auru ON auru.user_id = user.id ";
  1571. }
  1572. $sql_query .= ' WHERE 1 = 1 ';
  1573. if (count($conditions) > 0) {
  1574. $temp_conditions = [];
  1575. foreach ($conditions as $field => $value) {
  1576. $field = Database::escape_string($field);
  1577. $value = Database::escape_string($value);
  1578. if ($simple_like) {
  1579. $temp_conditions[] = $field." LIKE '$value%'";
  1580. } else {
  1581. $temp_conditions[] = $field.' LIKE \'%'.$value.'%\'';
  1582. }
  1583. }
  1584. if (!empty($temp_conditions)) {
  1585. $sql_query .= ' AND '.implode(' '.$condition.' ', $temp_conditions);
  1586. }
  1587. if (api_is_multiple_url_enabled()) {
  1588. $sql_query .= ' AND auru.access_url_id = '.api_get_current_access_url_id();
  1589. }
  1590. } else {
  1591. if (api_is_multiple_url_enabled()) {
  1592. $sql_query .= ' AND auru.access_url_id = '.api_get_current_access_url_id();
  1593. }
  1594. }
  1595. if (!empty($onlyThisUserList)) {
  1596. $onlyThisUserListToString = implode("','", $onlyThisUserList);
  1597. $sql_query .= " AND user.id IN ('$onlyThisUserListToString') ";
  1598. }
  1599. if (count($order_by) > 0) {
  1600. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',', $order_by));
  1601. }
  1602. $sql_result = Database::query($sql_query);
  1603. while ($result = Database::fetch_array($sql_result)) {
  1604. $userInfo = api_get_user_info($result['id']);
  1605. $return_array[] = $userInfo;
  1606. }
  1607. return $return_array;
  1608. }
  1609. /**
  1610. * Get user picture URL or path from user ID (returns an array).
  1611. * The return format is a complete path, enabling recovery of the directory
  1612. * with dirname() or the file with basename(). This also works for the
  1613. * functions dealing with the user's productions, as they are located in
  1614. * the same directory.
  1615. *
  1616. * @param int $id User ID
  1617. * @param string $type Type of path to return (can be 'system', 'web')
  1618. * @param array $userInfo user information to avoid query the DB
  1619. * returns the /main/img/unknown.jpg image set it at true
  1620. *
  1621. * @return array Array of 2 elements: 'dir' and 'file' which contain
  1622. * the dir and file as the name implies if image does not exist it will
  1623. * return the unknow image if anonymous parameter is true if not it returns an empty array
  1624. */
  1625. public static function get_user_picture_path_by_id(
  1626. $id,
  1627. $type = 'web',
  1628. $userInfo = []
  1629. ) {
  1630. switch ($type) {
  1631. case 'system': // Base: absolute system path.
  1632. $base = api_get_path(SYS_CODE_PATH);
  1633. break;
  1634. case 'web': // Base: absolute web path.
  1635. default:
  1636. $base = api_get_path(WEB_CODE_PATH);
  1637. break;
  1638. }
  1639. $anonymousPath = [
  1640. 'dir' => $base.'img/',
  1641. 'file' => 'unknown.jpg',
  1642. 'email' => '',
  1643. ];
  1644. if (empty($id) || empty($type)) {
  1645. return $anonymousPath;
  1646. }
  1647. $id = (int) $id;
  1648. if (empty($userInfo)) {
  1649. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1650. $sql = "SELECT email, picture_uri FROM $user_table
  1651. WHERE id = ".$id;
  1652. $res = Database::query($sql);
  1653. if (!Database::num_rows($res)) {
  1654. return $anonymousPath;
  1655. }
  1656. $user = Database::fetch_array($res);
  1657. if (empty($user['picture_uri'])) {
  1658. return $anonymousPath;
  1659. }
  1660. } else {
  1661. $user = $userInfo;
  1662. }
  1663. $pictureFilename = trim($user['picture_uri']);
  1664. $dir = self::getUserPathById($id, $type);
  1665. return [
  1666. 'dir' => $dir,
  1667. 'file' => $pictureFilename,
  1668. 'email' => $user['email'],
  1669. ];
  1670. }
  1671. /**
  1672. * *** READ BEFORE REVIEW THIS FUNCTION ***
  1673. * This function is a exact copy from get_user_picture_path_by_id() and it was create it to avoid
  1674. * a recursive calls for get_user_picture_path_by_id() in another functions when you update a user picture
  1675. * in same script, so you can find this function usage in update_user_picture() function.
  1676. *
  1677. * @param int $id User ID
  1678. * @param string $type Type of path to return (can be 'system', 'web')
  1679. * @param array $userInfo user information to avoid query the DB
  1680. * returns the /main/img/unknown.jpg image set it at true
  1681. *
  1682. * @return array Array of 2 elements: 'dir' and 'file' which contain
  1683. * the dir and file as the name implies if image does not exist it will
  1684. * return the unknown image if anonymous parameter is true if not it returns an empty array
  1685. */
  1686. public static function getUserPicturePathById($id, $type = 'web', $userInfo = [])
  1687. {
  1688. switch ($type) {
  1689. case 'system': // Base: absolute system path.
  1690. $base = api_get_path(SYS_CODE_PATH);
  1691. break;
  1692. case 'web': // Base: absolute web path.
  1693. default:
  1694. $base = api_get_path(WEB_CODE_PATH);
  1695. break;
  1696. }
  1697. $anonymousPath = [
  1698. 'dir' => $base.'img/',
  1699. 'file' => 'unknown.jpg',
  1700. 'email' => '',
  1701. ];
  1702. if (empty($id) || empty($type)) {
  1703. return $anonymousPath;
  1704. }
  1705. $id = (int) $id;
  1706. if (empty($userInfo)) {
  1707. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1708. $sql = "SELECT email, picture_uri FROM $user_table WHERE id = $id";
  1709. $res = Database::query($sql);
  1710. if (!Database::num_rows($res)) {
  1711. return $anonymousPath;
  1712. }
  1713. $user = Database::fetch_array($res);
  1714. if (empty($user['picture_uri'])) {
  1715. return $anonymousPath;
  1716. }
  1717. } else {
  1718. $user = $userInfo;
  1719. }
  1720. $pictureFilename = trim($user['picture_uri']);
  1721. $dir = self::getUserPathById($id, $type);
  1722. return [
  1723. 'dir' => $dir,
  1724. 'file' => $pictureFilename,
  1725. 'email' => $user['email'],
  1726. ];
  1727. }
  1728. /**
  1729. * Get user path from user ID (returns an array).
  1730. * The return format is a complete path to a folder ending with "/"
  1731. * In case the first level of subdirectory of users/ does not exist, the
  1732. * function will attempt to create it. Probably not the right place to do it
  1733. * but at least it avoids headaches in many other places.
  1734. *
  1735. * @param int $id User ID
  1736. * @param string $type Type of path to return (can be 'system', 'web', 'last')
  1737. *
  1738. * @return string User folder path (i.e. /var/www/chamilo/app/upload/users/1/1/)
  1739. */
  1740. public static function getUserPathById($id, $type)
  1741. {
  1742. $id = (int) $id;
  1743. if (!$id) {
  1744. return null;
  1745. }
  1746. $userPath = "users/$id/";
  1747. if (api_get_setting('split_users_upload_directory') === 'true') {
  1748. $userPath = 'users/'.substr((string) $id, 0, 1).'/'.$id.'/';
  1749. // In exceptional cases, on some portals, the intermediate base user
  1750. // directory might not have been created. Make sure it is before
  1751. // going further.
  1752. $rootPath = api_get_path(SYS_UPLOAD_PATH).'users/'.substr((string) $id, 0, 1);
  1753. if (!is_dir($rootPath)) {
  1754. $perm = api_get_permissions_for_new_directories();
  1755. try {
  1756. mkdir($rootPath, $perm);
  1757. } catch (Exception $e) {
  1758. error_log($e->getMessage());
  1759. }
  1760. }
  1761. }
  1762. switch ($type) {
  1763. case 'system': // Base: absolute system path.
  1764. $userPath = api_get_path(SYS_UPLOAD_PATH).$userPath;
  1765. break;
  1766. case 'web': // Base: absolute web path.
  1767. $userPath = api_get_path(WEB_UPLOAD_PATH).$userPath;
  1768. break;
  1769. case 'last': // Only the last part starting with users/
  1770. break;
  1771. }
  1772. return $userPath;
  1773. }
  1774. /**
  1775. * Gets the current user image.
  1776. *
  1777. * @param string $user_id
  1778. * @param int $size it can be USER_IMAGE_SIZE_SMALL,
  1779. * USER_IMAGE_SIZE_MEDIUM, USER_IMAGE_SIZE_BIG or USER_IMAGE_SIZE_ORIGINAL
  1780. * @param bool $addRandomId
  1781. * @param array $userInfo to avoid query the DB
  1782. *
  1783. * @return string
  1784. */
  1785. public static function getUserPicture(
  1786. $user_id,
  1787. $size = USER_IMAGE_SIZE_MEDIUM,
  1788. $addRandomId = true,
  1789. $userInfo = []
  1790. ) {
  1791. // Make sure userInfo is defined. Otherwise, define it!
  1792. if (empty($userInfo) || !is_array($userInfo) || count($userInfo) == 0) {
  1793. if (empty($user_id)) {
  1794. return '';
  1795. } else {
  1796. $userInfo = api_get_user_info($user_id);
  1797. }
  1798. }
  1799. $imageWebPath = self::get_user_picture_path_by_id(
  1800. $user_id,
  1801. 'web',
  1802. $userInfo
  1803. );
  1804. $pictureWebFile = $imageWebPath['file'];
  1805. $pictureWebDir = $imageWebPath['dir'];
  1806. $pictureAnonymousSize = '128';
  1807. $gravatarSize = 22;
  1808. $realSizeName = 'small_';
  1809. switch ($size) {
  1810. case USER_IMAGE_SIZE_SMALL:
  1811. $pictureAnonymousSize = '32';
  1812. $realSizeName = 'small_';
  1813. $gravatarSize = 32;
  1814. break;
  1815. case USER_IMAGE_SIZE_MEDIUM:
  1816. $pictureAnonymousSize = '64';
  1817. $realSizeName = 'medium_';
  1818. $gravatarSize = 64;
  1819. break;
  1820. case USER_IMAGE_SIZE_ORIGINAL:
  1821. $pictureAnonymousSize = '128';
  1822. $realSizeName = '';
  1823. $gravatarSize = 128;
  1824. break;
  1825. case USER_IMAGE_SIZE_BIG:
  1826. $pictureAnonymousSize = '128';
  1827. $realSizeName = 'big_';
  1828. $gravatarSize = 128;
  1829. break;
  1830. }
  1831. $gravatarEnabled = api_get_setting('gravatar_enabled');
  1832. $anonymousPath = Display::returnIconPath('unknown.png', $pictureAnonymousSize);
  1833. if ($pictureWebFile == 'unknown.jpg' || empty($pictureWebFile)) {
  1834. if ($gravatarEnabled === 'true') {
  1835. $file = self::getGravatar(
  1836. $imageWebPath['email'],
  1837. $gravatarSize,
  1838. api_get_setting('gravatar_type')
  1839. );
  1840. if ($addRandomId) {
  1841. $file .= '&rand='.uniqid();
  1842. }
  1843. return $file;
  1844. }
  1845. return $anonymousPath;
  1846. }
  1847. $pictureSysPath = self::get_user_picture_path_by_id($user_id, 'system');
  1848. $file = $pictureSysPath['dir'].$realSizeName.$pictureWebFile;
  1849. $picture = '';
  1850. if (file_exists($file)) {
  1851. $picture = $pictureWebDir.$realSizeName.$pictureWebFile;
  1852. } else {
  1853. $file = $pictureSysPath['dir'].$pictureWebFile;
  1854. if (file_exists($file) && !is_dir($file)) {
  1855. $picture = $pictureWebFile['dir'].$pictureWebFile;
  1856. }
  1857. }
  1858. if (empty($picture)) {
  1859. return $anonymousPath;
  1860. }
  1861. if ($addRandomId) {
  1862. $picture .= '?rand='.uniqid();
  1863. }
  1864. return $picture;
  1865. }
  1866. /**
  1867. * Creates new user photos in various sizes of a user, or deletes user photos.
  1868. * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php.
  1869. *
  1870. * @param int $user_id the user internal identification number
  1871. * @param string $file The common file name for the newly created photos.
  1872. * It will be checked and modified for compatibility with the file system.
  1873. * If full name is provided, path component is ignored.
  1874. * If an empty name is provided, then old user photos are deleted only,
  1875. *
  1876. * @see UserManager::delete_user_picture() as the prefered way for deletion.
  1877. *
  1878. * @param string $source_file the full system name of the image from which user photos will be created
  1879. * @param string $cropParameters Optional string that contents "x,y,width,height" of a cropped image format
  1880. *
  1881. * @return bool Returns the resulting common file name of created images which usually should be stored in database.
  1882. * When deletion is requested returns empty string.
  1883. * In case of internal error or negative validation returns FALSE.
  1884. */
  1885. public static function update_user_picture(
  1886. $user_id,
  1887. $file = null,
  1888. $source_file = null,
  1889. $cropParameters = ''
  1890. ) {
  1891. if (empty($user_id)) {
  1892. return false;
  1893. }
  1894. $delete = empty($file);
  1895. if (empty($source_file)) {
  1896. $source_file = $file;
  1897. }
  1898. // User-reserved directory where photos have to be placed.
  1899. $path_info = self::getUserPicturePathById($user_id, 'system');
  1900. $path = $path_info['dir'];
  1901. // If this directory does not exist - we create it.
  1902. if (!file_exists($path)) {
  1903. mkdir($path, api_get_permissions_for_new_directories(), true);
  1904. }
  1905. // The old photos (if any).
  1906. $old_file = $path_info['file'];
  1907. // Let us delete them.
  1908. if ($old_file != 'unknown.jpg') {
  1909. if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
  1910. $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_';
  1911. @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file);
  1912. @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file);
  1913. @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file);
  1914. @rename($path.$old_file, $path.$prefix.$old_file);
  1915. } else {
  1916. @unlink($path.'small_'.$old_file);
  1917. @unlink($path.'medium_'.$old_file);
  1918. @unlink($path.'big_'.$old_file);
  1919. @unlink($path.$old_file);
  1920. }
  1921. }
  1922. // Exit if only deletion has been requested. Return an empty picture name.
  1923. if ($delete) {
  1924. return '';
  1925. }
  1926. // Validation 2.
  1927. $allowed_types = api_get_supported_image_extensions();
  1928. $file = str_replace('\\', '/', $file);
  1929. $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
  1930. $extension = strtolower(substr(strrchr($filename, '.'), 1));
  1931. if (!in_array($extension, $allowed_types)) {
  1932. return false;
  1933. }
  1934. // This is the common name for the new photos.
  1935. if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && $old_file != 'unknown.jpg') {
  1936. $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
  1937. $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
  1938. $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension;
  1939. } else {
  1940. $filename = api_replace_dangerous_char($filename);
  1941. if (PREFIX_IMAGE_FILENAME_WITH_UID) {
  1942. $filename = uniqid('').'_'.$filename;
  1943. }
  1944. // We always prefix user photos with user ids, so on setting
  1945. // api_get_setting('split_users_upload_directory') === 'true'
  1946. // the correspondent directories to be found successfully.
  1947. $filename = $user_id.'_'.$filename;
  1948. }
  1949. //Crop the image to adjust 1:1 ratio
  1950. $image = new Image($source_file);
  1951. $image->crop($cropParameters);
  1952. // Storing the new photos in 4 versions with various sizes.
  1953. $userPath = self::getUserPathById($user_id, 'system');
  1954. // If this path does not exist - we create it.
  1955. if (!file_exists($userPath)) {
  1956. mkdir($userPath, api_get_permissions_for_new_directories(), true);
  1957. }
  1958. $small = new Image($source_file);
  1959. $small->resize(32);
  1960. $small->send_image($userPath.'small_'.$filename);
  1961. $medium = new Image($source_file);
  1962. $medium->resize(85);
  1963. $medium->send_image($userPath.'medium_'.$filename);
  1964. $normal = new Image($source_file);
  1965. $normal->resize(200);
  1966. $normal->send_image($userPath.$filename);
  1967. $big = new Image($source_file); // This is the original picture.
  1968. $big->send_image($userPath.'big_'.$filename);
  1969. $result = $small && $medium && $normal && $big;
  1970. return $result ? $filename : false;
  1971. }
  1972. /**
  1973. * Update User extra field file type into {user_folder}/{$extra_field}.
  1974. *
  1975. * @param int $user_id The user internal identification number
  1976. * @param string $extra_field The $extra_field The extra field name
  1977. * @param null $file The filename
  1978. * @param null $source_file The temporal filename
  1979. *
  1980. * @return bool|null return filename if success, but false
  1981. */
  1982. public static function update_user_extra_file(
  1983. $user_id,
  1984. $extra_field = '',
  1985. $file = null,
  1986. $source_file = null
  1987. ) {
  1988. // Add Filter
  1989. $source_file = Security::filter_filename($source_file);
  1990. $file = Security::filter_filename($file);
  1991. if (empty($user_id)) {
  1992. return false;
  1993. }
  1994. if (empty($source_file)) {
  1995. $source_file = $file;
  1996. }
  1997. // User-reserved directory where extra file have to be placed.
  1998. $path_info = self::get_user_picture_path_by_id($user_id, 'system');
  1999. $path = $path_info['dir'];
  2000. if (!empty($extra_field)) {
  2001. $path .= $extra_field.'/';
  2002. }
  2003. // If this directory does not exist - we create it.
  2004. if (!file_exists($path)) {
  2005. @mkdir($path, api_get_permissions_for_new_directories(), true);
  2006. }
  2007. if (filter_extension($file)) {
  2008. if (@move_uploaded_file($source_file, $path.$file)) {
  2009. if ($extra_field) {
  2010. return $extra_field.'/'.$file;
  2011. } else {
  2012. return $file;
  2013. }
  2014. }
  2015. }
  2016. return false; // this should be returned if anything went wrong with the upload
  2017. }
  2018. /**
  2019. * Deletes user photos.
  2020. * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php.
  2021. *
  2022. * @param int $userId the user internal identification number
  2023. *
  2024. * @return mixed returns empty string on success, FALSE on error
  2025. */
  2026. public static function deleteUserPicture($userId)
  2027. {
  2028. return self::update_user_picture($userId);
  2029. }
  2030. /**
  2031. * Returns an XHTML formatted list of productions for a user, or FALSE if he
  2032. * doesn't have any.
  2033. *
  2034. * If there has been a request to remove a production, the function will return
  2035. * without building the list unless forced to do so by the optional second
  2036. * parameter. This increases performance by avoiding to read through the
  2037. * productions on the filesystem before the removal request has been carried
  2038. * out because they'll have to be re-read afterwards anyway.
  2039. *
  2040. * @param int $user_id User id
  2041. * @param bool $force Optional parameter to force building after a removal request
  2042. * @param bool $showDelete
  2043. *
  2044. * @return string A string containing the XHTML code to display the production list, or FALSE
  2045. */
  2046. public static function build_production_list($user_id, $force = false, $showDelete = false)
  2047. {
  2048. if (!$force && !empty($_POST['remove_production'])) {
  2049. return true; // postpone reading from the filesystem
  2050. }
  2051. $productions = self::get_user_productions($user_id);
  2052. if (empty($productions)) {
  2053. return false;
  2054. }
  2055. $production_dir = self::getUserPathById($user_id, 'web');
  2056. $del_image = Display::returnIconPath('delete.png');
  2057. $add_image = Display::returnIconPath('archive.png');
  2058. $del_text = get_lang('Delete');
  2059. $production_list = '';
  2060. if (count($productions) > 0) {
  2061. $production_list = '<div class="files-production"><ul id="productions">';
  2062. foreach ($productions as $file) {
  2063. $production_list .= '<li>
  2064. <img src="'.$add_image.'" />
  2065. <a href="'.$production_dir.urlencode($file).'" target="_blank">
  2066. '.htmlentities($file).'
  2067. </a>';
  2068. if ($showDelete) {
  2069. $production_list .= '&nbsp;&nbsp;
  2070. <input
  2071. style="width:16px;"
  2072. type="image"
  2073. name="remove_production['.urlencode($file).']"
  2074. src="'.$del_image.'"
  2075. alt="'.$del_text.'"
  2076. title="'.$del_text.' '.htmlentities($file).'"
  2077. onclick="javascript: return confirmation(\''.htmlentities($file).'\');" /></li>';
  2078. }
  2079. }
  2080. $production_list .= '</ul></div>';
  2081. }
  2082. return $production_list;
  2083. }
  2084. /**
  2085. * Returns an array with the user's productions.
  2086. *
  2087. * @param int $user_id User id
  2088. *
  2089. * @return array An array containing the user's productions
  2090. */
  2091. public static function get_user_productions($user_id)
  2092. {
  2093. $production_repository = self::getUserPathById($user_id, 'system');
  2094. $productions = [];
  2095. if (is_dir($production_repository)) {
  2096. $handle = opendir($production_repository);
  2097. while ($file = readdir($handle)) {
  2098. if ($file == '.' ||
  2099. $file == '..' ||
  2100. $file == '.htaccess' ||
  2101. is_dir($production_repository.$file)
  2102. ) {
  2103. // skip current/parent directory and .htaccess
  2104. continue;
  2105. }
  2106. if (preg_match('/('.$user_id.'|[0-9a-f]{13}|saved)_.+\.(png|jpg|jpeg|gif)$/i', $file)) {
  2107. // User's photos should not be listed as productions.
  2108. continue;
  2109. }
  2110. $productions[] = $file;
  2111. }
  2112. }
  2113. return $productions;
  2114. }
  2115. /**
  2116. * Remove a user production.
  2117. *
  2118. * @param int $user_id User id
  2119. * @param string $production The production to remove
  2120. *
  2121. * @return bool
  2122. */
  2123. public static function remove_user_production($user_id, $production)
  2124. {
  2125. $production_path = self::get_user_picture_path_by_id($user_id, 'system');
  2126. $production_file = $production_path['dir'].$production;
  2127. if (is_file($production_file)) {
  2128. unlink($production_file);
  2129. return true;
  2130. }
  2131. return false;
  2132. }
  2133. /**
  2134. * Update an extra field value for a given user.
  2135. *
  2136. * @param int $userId User ID
  2137. * @param string $variable Field variable name
  2138. * @param string $value Field value
  2139. *
  2140. * @return bool true if field updated, false otherwise
  2141. */
  2142. public static function update_extra_field_value($userId, $variable, $value = '')
  2143. {
  2144. $extraFieldValue = new ExtraFieldValue('user');
  2145. $params = [
  2146. 'item_id' => $userId,
  2147. 'variable' => $variable,
  2148. 'value' => $value,
  2149. ];
  2150. return $extraFieldValue->save($params);
  2151. }
  2152. /**
  2153. * Get an array of extra fields with field details (type, default value and options).
  2154. *
  2155. * @param int Offset (from which row)
  2156. * @param int Number of items
  2157. * @param int Column on which sorting is made
  2158. * @param string Sorting direction
  2159. * @param bool Optional. Whether we get all the fields or just the visible ones
  2160. * @param int Optional. Whether we get all the fields with field_filter 1 or 0 or everything
  2161. *
  2162. * @return array Extra fields details (e.g. $list[2]['type'], $list[4]['options'][2]['title']
  2163. */
  2164. public static function get_extra_fields(
  2165. $from = 0,
  2166. $number_of_items = 0,
  2167. $column = 5,
  2168. $direction = 'ASC',
  2169. $all_visibility = true,
  2170. $field_filter = null
  2171. ) {
  2172. $fields = [];
  2173. $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
  2174. $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  2175. $columns = [
  2176. 'id',
  2177. 'variable',
  2178. 'field_type',
  2179. 'display_text',
  2180. 'default_value',
  2181. 'field_order',
  2182. 'filter',
  2183. ];
  2184. $column = (int) $column;
  2185. $sort_direction = '';
  2186. if (in_array(strtoupper($direction), ['ASC', 'DESC'])) {
  2187. $sort_direction = strtoupper($direction);
  2188. }
  2189. $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
  2190. $sqlf = "SELECT * FROM $t_uf WHERE extra_field_type = $extraFieldType ";
  2191. if (!$all_visibility) {
  2192. $sqlf .= " AND visible_to_self = 1 ";
  2193. }
  2194. if (!is_null($field_filter)) {
  2195. $field_filter = (int) $field_filter;
  2196. $sqlf .= " AND filter = $field_filter ";
  2197. }
  2198. $sqlf .= " ORDER BY ".$columns[$column]." $sort_direction ";
  2199. if ($number_of_items != 0) {
  2200. $sqlf .= " LIMIT ".intval($from).','.intval($number_of_items);
  2201. }
  2202. $resf = Database::query($sqlf);
  2203. if (Database::num_rows($resf) > 0) {
  2204. while ($rowf = Database::fetch_array($resf)) {
  2205. $fields[$rowf['id']] = [
  2206. 0 => $rowf['id'],
  2207. 1 => $rowf['variable'],
  2208. 2 => $rowf['field_type'],
  2209. 3 => empty($rowf['display_text']) ? '' : $rowf['display_text'],
  2210. 4 => $rowf['default_value'],
  2211. 5 => $rowf['field_order'],
  2212. 6 => $rowf['visible_to_self'],
  2213. 7 => $rowf['changeable'],
  2214. 8 => $rowf['filter'],
  2215. 9 => [],
  2216. 10 => '<a name="'.$rowf['id'].'"></a>',
  2217. ];
  2218. $sqlo = "SELECT * FROM $t_ufo
  2219. WHERE field_id = ".$rowf['id']."
  2220. ORDER BY option_order ASC";
  2221. $reso = Database::query($sqlo);
  2222. if (Database::num_rows($reso) > 0) {
  2223. while ($rowo = Database::fetch_array($reso)) {
  2224. $fields[$rowf['id']][9][$rowo['id']] = [
  2225. 0 => $rowo['id'],
  2226. 1 => $rowo['option_value'],
  2227. 2 => empty($rowo['display_text']) ? '' : $rowo['display_text'],
  2228. 3 => $rowo['option_order'],
  2229. ];
  2230. }
  2231. }
  2232. }
  2233. }
  2234. return $fields;
  2235. }
  2236. /**
  2237. * Get valid filenames in $user_folder/{$extra_field}/.
  2238. *
  2239. * @param $user_id
  2240. * @param $extra_field
  2241. * @param bool $full_path
  2242. *
  2243. * @return array
  2244. */
  2245. public static function get_user_extra_files($user_id, $extra_field, $full_path = false)
  2246. {
  2247. if (!$full_path) {
  2248. // Nothing to do
  2249. } else {
  2250. $path_info = self::get_user_picture_path_by_id($user_id, 'system');
  2251. $path = $path_info['dir'];
  2252. }
  2253. $extra_data = self::get_extra_user_data_by_field($user_id, $extra_field);
  2254. $extra_files = $extra_data[$extra_field];
  2255. $files = [];
  2256. if (is_array($extra_files)) {
  2257. foreach ($extra_files as $key => $value) {
  2258. if (!$full_path) {
  2259. // Relative path from user folder
  2260. $files[] = $value;
  2261. } else {
  2262. $files[] = $path.$value;
  2263. }
  2264. }
  2265. } elseif (!empty($extra_files)) {
  2266. if (!$full_path) {
  2267. // Relative path from user folder
  2268. $files[] = $extra_files;
  2269. } else {
  2270. $files[] = $path.$extra_files;
  2271. }
  2272. }
  2273. return $files; // can be an empty array
  2274. }
  2275. /**
  2276. * Creates a new extra field.
  2277. *
  2278. * @param string $variable Field's internal variable name
  2279. * @param int $fieldType Field's type
  2280. * @param string $displayText Field's language var name
  2281. * @param string $default Field's default value
  2282. *
  2283. * @return int
  2284. */
  2285. public static function create_extra_field(
  2286. $variable,
  2287. $fieldType,
  2288. $displayText,
  2289. $default
  2290. ) {
  2291. $extraField = new ExtraField('user');
  2292. $params = [
  2293. 'variable' => $variable,
  2294. 'field_type' => $fieldType,
  2295. 'display_text' => $displayText,
  2296. 'default_value' => $default,
  2297. ];
  2298. return $extraField->save($params);
  2299. }
  2300. /**
  2301. * Check if a field is available.
  2302. *
  2303. * @param string $variable
  2304. *
  2305. * @return bool
  2306. */
  2307. public static function is_extra_field_available($variable)
  2308. {
  2309. $extraField = new ExtraField('user');
  2310. $data = $extraField->get_handler_field_info_by_field_variable($variable);
  2311. return !empty($data) ? true : false;
  2312. }
  2313. /**
  2314. * Gets user extra fields data.
  2315. *
  2316. * @param int User ID
  2317. * @param bool Whether to prefix the fields indexes with "extra_" (might be used by formvalidator)
  2318. * @param bool Whether to return invisible fields as well
  2319. * @param bool Whether to split multiple-selection fields or not
  2320. *
  2321. * @return array Array of fields => value for the given user
  2322. */
  2323. public static function get_extra_user_data(
  2324. $user_id,
  2325. $prefix = false,
  2326. $allVisibility = true,
  2327. $splitMultiple = false,
  2328. $fieldFilter = null
  2329. ) {
  2330. $user_id = (int) $user_id;
  2331. if (empty($user_id)) {
  2332. return [];
  2333. }
  2334. $extra_data = [];
  2335. $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
  2336. $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2337. $user_id = (int) $user_id;
  2338. $sql = "SELECT f.id as id, f.variable as fvar, f.field_type as type
  2339. FROM $t_uf f
  2340. WHERE
  2341. extra_field_type = ".EntityExtraField::USER_FIELD_TYPE."
  2342. ";
  2343. $filter_cond = '';
  2344. if (!$allVisibility) {
  2345. if (isset($fieldFilter)) {
  2346. $fieldFilter = (int) $fieldFilter;
  2347. $filter_cond .= " AND filter = $fieldFilter ";
  2348. }
  2349. $sql .= " AND f.visible_to_self = 1 $filter_cond ";
  2350. } else {
  2351. if (isset($fieldFilter)) {
  2352. $fieldFilter = (int) $fieldFilter;
  2353. $sql .= " AND filter = $fieldFilter ";
  2354. }
  2355. }
  2356. $sql .= ' ORDER BY f.field_order';
  2357. $res = Database::query($sql);
  2358. if (Database::num_rows($res) > 0) {
  2359. while ($row = Database::fetch_array($res)) {
  2360. if ($row['type'] == self::USER_FIELD_TYPE_TAG) {
  2361. $tags = self::get_user_tags_to_string($user_id, $row['id'], false);
  2362. $extra_data['extra_'.$row['fvar']] = $tags;
  2363. } else {
  2364. $sqlu = "SELECT value as fval
  2365. FROM $t_ufv
  2366. WHERE field_id=".$row['id']." AND item_id = ".$user_id;
  2367. $resu = Database::query($sqlu);
  2368. // get default value
  2369. $sql_df = "SELECT default_value as fval_df FROM $t_uf
  2370. WHERE id=".$row['id'];
  2371. $res_df = Database::query($sql_df);
  2372. if (Database::num_rows($resu) > 0) {
  2373. $rowu = Database::fetch_array($resu);
  2374. $fval = $rowu['fval'];
  2375. if ($row['type'] == self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
  2376. $fval = explode(';', $rowu['fval']);
  2377. }
  2378. } else {
  2379. $row_df = Database::fetch_array($res_df);
  2380. $fval = $row_df['fval_df'];
  2381. }
  2382. // We get here (and fill the $extra_data array) even if there
  2383. // is no user with data (we fill it with default values)
  2384. if ($prefix) {
  2385. if ($row['type'] == self::USER_FIELD_TYPE_RADIO) {
  2386. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  2387. } else {
  2388. $extra_data['extra_'.$row['fvar']] = $fval;
  2389. }
  2390. } else {
  2391. if ($row['type'] == self::USER_FIELD_TYPE_RADIO) {
  2392. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  2393. } else {
  2394. $extra_data[$row['fvar']] = $fval;
  2395. }
  2396. }
  2397. }
  2398. }
  2399. }
  2400. return $extra_data;
  2401. }
  2402. /** Get extra user data by field
  2403. * @param int user ID
  2404. * @param string the internal variable name of the field
  2405. *
  2406. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  2407. */
  2408. public static function get_extra_user_data_by_field(
  2409. $user_id,
  2410. $field_variable,
  2411. $prefix = false,
  2412. $all_visibility = true,
  2413. $splitmultiple = false
  2414. ) {
  2415. $user_id = (int) $user_id;
  2416. if (empty($user_id)) {
  2417. return [];
  2418. }
  2419. $extra_data = [];
  2420. $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
  2421. $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2422. $sql = "SELECT f.id as id, f.variable as fvar, f.field_type as type
  2423. FROM $t_uf f
  2424. WHERE f.variable = '$field_variable' ";
  2425. if (!$all_visibility) {
  2426. $sql .= " AND f.visible_to_self = 1 ";
  2427. }
  2428. $sql .= " AND extra_field_type = ".EntityExtraField::USER_FIELD_TYPE;
  2429. $sql .= " ORDER BY f.field_order ";
  2430. $res = Database::query($sql);
  2431. if (Database::num_rows($res) > 0) {
  2432. while ($row = Database::fetch_array($res)) {
  2433. $sqlu = "SELECT value as fval FROM $t_ufv v
  2434. INNER JOIN $t_uf f
  2435. ON (v.field_id = f.id)
  2436. WHERE
  2437. extra_field_type = ".EntityExtraField::USER_FIELD_TYPE." AND
  2438. field_id = ".$row['id']." AND
  2439. item_id = ".$user_id;
  2440. $resu = Database::query($sqlu);
  2441. $fval = '';
  2442. if (Database::num_rows($resu) > 0) {
  2443. $rowu = Database::fetch_array($resu);
  2444. $fval = $rowu['fval'];
  2445. if ($row['type'] == self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
  2446. $fval = explode(';', $rowu['fval']);
  2447. }
  2448. }
  2449. if ($prefix) {
  2450. $extra_data['extra_'.$row['fvar']] = $fval;
  2451. } else {
  2452. $extra_data[$row['fvar']] = $fval;
  2453. }
  2454. }
  2455. }
  2456. return $extra_data;
  2457. }
  2458. /**
  2459. * Get the extra field information for a certain field (the options as well).
  2460. *
  2461. * @param int $variable The name of the field we want to know everything about
  2462. *
  2463. * @return array Array containing all the information about the extra profile field
  2464. * (first level of array contains field details, then 'options' sub-array contains options details,
  2465. * as returned by the database)
  2466. *
  2467. * @author Julio Montoya
  2468. *
  2469. * @since v1.8.6
  2470. */
  2471. public static function get_extra_field_information_by_name($variable)
  2472. {
  2473. $extraField = new ExtraField('user');
  2474. return $extraField->get_handler_field_info_by_field_variable($variable);
  2475. }
  2476. /**
  2477. * Get the extra field information for user tag (the options as well).
  2478. *
  2479. * @param int $variable The name of the field we want to know everything about
  2480. *
  2481. * @return array Array containing all the information about the extra profile field
  2482. * (first level of array contains field details, then 'options' sub-array contains options details,
  2483. * as returned by the database)
  2484. *
  2485. * @author José Loguercio
  2486. *
  2487. * @since v1.11.0
  2488. */
  2489. public static function get_extra_field_tags_information_by_name($variable)
  2490. {
  2491. $extraField = new ExtraField('user');
  2492. return $extraField->get_handler_field_info_by_tags($variable);
  2493. }
  2494. /**
  2495. * Get all the extra field information of a certain field (also the options).
  2496. *
  2497. * @param int $fieldId the ID of the field we want to know everything of
  2498. *
  2499. * @return array $return containing all th information about the extra profile field
  2500. *
  2501. * @author Julio Montoya
  2502. *
  2503. * @deprecated
  2504. * @since v1.8.6
  2505. */
  2506. public static function get_extra_field_information($fieldId)
  2507. {
  2508. $extraField = new ExtraField('user');
  2509. return $extraField->getFieldInfoByFieldId($fieldId);
  2510. }
  2511. /**
  2512. * Get extra user data by value.
  2513. *
  2514. * @param string $variable the internal variable name of the field
  2515. * @param string $value the internal value of the field
  2516. * @param bool $all_visibility
  2517. *
  2518. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  2519. */
  2520. public static function get_extra_user_data_by_value($variable, $value, $all_visibility = true)
  2521. {
  2522. $extraFieldValue = new ExtraFieldValue('user');
  2523. $extraField = new ExtraField('user');
  2524. $info = $extraField->get_handler_field_info_by_field_variable($variable);
  2525. if (false === $info) {
  2526. return [];
  2527. }
  2528. $data = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  2529. $variable,
  2530. $value,
  2531. false,
  2532. false,
  2533. true
  2534. );
  2535. $result = [];
  2536. if (!empty($data)) {
  2537. foreach ($data as $item) {
  2538. $result[] = $item['item_id'];
  2539. }
  2540. }
  2541. return $result;
  2542. }
  2543. /**
  2544. * Get extra user data by tags value.
  2545. *
  2546. * @param int $fieldId the ID of the field we want to know everything of
  2547. * @param string $tag the tag name for search
  2548. *
  2549. * @return array with extra data info of a user
  2550. *
  2551. * @author José Loguercio
  2552. *
  2553. * @since v1.11.0
  2554. */
  2555. public static function get_extra_user_data_by_tags($fieldId, $tag)
  2556. {
  2557. $extraField = new ExtraField('user');
  2558. $result = $extraField->getAllUserPerTag($fieldId, $tag);
  2559. $array = [];
  2560. foreach ($result as $index => $user) {
  2561. $array[] = $user['user_id'];
  2562. }
  2563. return $array;
  2564. }
  2565. /**
  2566. * Get extra user data by field variable.
  2567. *
  2568. * @param string $variable field variable
  2569. *
  2570. * @return array data
  2571. */
  2572. public static function get_extra_user_data_by_field_variable($variable)
  2573. {
  2574. $extraInfo = self::get_extra_field_information_by_name($variable);
  2575. $field_id = (int) $extraInfo['id'];
  2576. $extraField = new ExtraFieldValue('user');
  2577. $data = $extraField->getValuesByFieldId($field_id);
  2578. if (!empty($data)) {
  2579. foreach ($data as $row) {
  2580. $user_id = $row['item_id'];
  2581. $data[$user_id] = $row;
  2582. }
  2583. }
  2584. return $data;
  2585. }
  2586. /**
  2587. * Get extra user data tags by field variable.
  2588. *
  2589. * @param string $variable field variable
  2590. *
  2591. * @return array
  2592. */
  2593. public static function get_extra_user_data_for_tags($variable)
  2594. {
  2595. $data = self::get_extra_field_tags_information_by_name($variable);
  2596. return $data;
  2597. }
  2598. /**
  2599. * Gives a list of [session_category][session_id] for the current user.
  2600. *
  2601. * @param int $user_id
  2602. * @param bool $is_time_over whether to fill the first element or not
  2603. * (to give space for courses out of categories)
  2604. * @param bool $ignore_visibility_for_admins optional true if limit time from session is over, false otherwise
  2605. * @param bool $ignoreTimeLimit ignore time start/end
  2606. * @param bool $getCount
  2607. *
  2608. * @return array list of statuses [session_category][session_id]
  2609. *
  2610. * @todo ensure multiple access urls are managed correctly
  2611. */
  2612. public static function get_sessions_by_category(
  2613. $user_id,
  2614. $is_time_over = true,
  2615. $ignore_visibility_for_admins = false,
  2616. $ignoreTimeLimit = false,
  2617. $getCount = false
  2618. ) {
  2619. $user_id = (int) $user_id;
  2620. if (empty($user_id)) {
  2621. return [];
  2622. }
  2623. $allowOrder = api_get_configuration_value('session_list_order');
  2624. $position = '';
  2625. if ($allowOrder) {
  2626. $position = ', s.position AS position ';
  2627. }
  2628. // Get the list of sessions per user
  2629. $now = new DateTime('now', new DateTimeZone('UTC'));
  2630. // LEFT JOIN is used for session_rel_course_rel_user because an inner
  2631. // join would not catch session-courses where the user is general
  2632. // session coach but which do not have students nor coaches registered
  2633. $dqlSelect = ' COUNT(DISTINCT s.id) ';
  2634. if (!$getCount) {
  2635. $dqlSelect = " DISTINCT
  2636. s.id,
  2637. s.name,
  2638. s.accessStartDate AS access_start_date,
  2639. s.accessEndDate AS access_end_date,
  2640. s.duration,
  2641. sc.id AS session_category_id,
  2642. sc.name AS session_category_name,
  2643. sc.dateStart AS session_category_date_start,
  2644. sc.dateEnd AS session_category_date_end,
  2645. s.coachAccessStartDate AS coach_access_start_date,
  2646. s.coachAccessEndDate AS coach_access_end_date,
  2647. CASE WHEN s.accessEndDate IS NULL THEN 1 ELSE 0 END HIDDEN _isFieldNull
  2648. $position
  2649. ";
  2650. }
  2651. $dql = "SELECT $dqlSelect
  2652. FROM ChamiloCoreBundle:Session AS s
  2653. LEFT JOIN ChamiloCoreBundle:SessionRelCourseRelUser AS scu WITH scu.session = s
  2654. INNER JOIN ChamiloCoreBundle:AccessUrlRelSession AS url WITH url.sessionId = s.id
  2655. LEFT JOIN ChamiloCoreBundle:SessionCategory AS sc WITH s.category = sc ";
  2656. // A single OR operation on scu.user = :user OR s.generalCoach = :user
  2657. // is awfully inefficient for large sets of data (1m25s for 58K
  2658. // sessions, BT#14115) but executing a similar query twice and grouping
  2659. // the results afterwards in PHP takes about 1/1000th of the time
  2660. // (0.1s + 0.0s) for the same set of data, so we do it this way...
  2661. $dqlStudent = $dql.' WHERE scu.user = :user AND url.accessUrlId = :url ';
  2662. $dqlCoach = $dql.' WHERE s.generalCoach = :user AND url.accessUrlId = :url ';
  2663. // Default order
  2664. $order = 'ORDER BY sc.name, s.name';
  2665. // Order by date if showing all sessions
  2666. $showAllSessions = api_get_configuration_value('show_all_sessions_on_my_course_page') === true;
  2667. if ($showAllSessions) {
  2668. $order = 'ORDER BY s.accessStartDate';
  2669. }
  2670. // Order by position
  2671. if ($allowOrder) {
  2672. $order = 'ORDER BY s.position';
  2673. }
  2674. // Order by dates according to settings
  2675. $orderBySettings = api_get_configuration_value('my_courses_session_order');
  2676. if (!empty($orderBySettings) && isset($orderBySettings['field']) && isset($orderBySettings['order'])) {
  2677. $field = $orderBySettings['field'];
  2678. $orderSetting = $orderBySettings['order'];
  2679. switch ($field) {
  2680. case 'start_date':
  2681. $order = " ORDER BY s.accessStartDate $orderSetting";
  2682. break;
  2683. case 'end_date':
  2684. $order = " ORDER BY s.accessEndDate $orderSetting ";
  2685. if ($orderSetting == 'asc') {
  2686. // Put null values at the end
  2687. // https://stackoverflow.com/questions/12652034/how-can-i-order-by-null-in-dql
  2688. $order = ' ORDER BY _isFieldNull asc, s.accessEndDate asc';
  2689. }
  2690. break;
  2691. case 'name':
  2692. $order = " ORDER BY s.name $orderSetting ";
  2693. break;
  2694. }
  2695. }
  2696. $dqlStudent .= $order;
  2697. $dqlCoach .= $order;
  2698. $accessUrlId = api_get_current_access_url_id();
  2699. $dqlStudent = Database::getManager()
  2700. ->createQuery($dqlStudent)
  2701. ->setParameters(
  2702. ['user' => $user_id, 'url' => $accessUrlId]
  2703. )
  2704. ;
  2705. $dqlCoach = Database::getManager()
  2706. ->createQuery($dqlCoach)
  2707. ->setParameters(
  2708. ['user' => $user_id, 'url' => $accessUrlId]
  2709. )
  2710. ;
  2711. if ($getCount) {
  2712. return $dqlStudent->getSingleScalarResult() + $dqlCoach->getSingleScalarResult();
  2713. }
  2714. $sessionDataStudent = $dqlStudent->getResult();
  2715. $sessionDataCoach = $dqlCoach->getResult();
  2716. $sessionData = [];
  2717. // First fill $sessionData with student sessions
  2718. foreach ($sessionDataStudent as $row) {
  2719. $sessionData[$row['id']] = $row;
  2720. }
  2721. // Overwrite session data of the user as a student with session data
  2722. // of the user as a coach.
  2723. // There shouldn't be such duplicate rows, but just in case...
  2724. foreach ($sessionDataCoach as $row) {
  2725. $sessionData[$row['id']] = $row;
  2726. }
  2727. $collapsable = api_get_configuration_value('allow_user_session_collapsable');
  2728. $extraField = new ExtraFieldValue('session');
  2729. $collapsableLink = api_get_path(WEB_PATH).'user_portal.php?action=collapse_session';
  2730. $categories = [];
  2731. foreach ($sessionData as $row) {
  2732. $session_id = $row['id'];
  2733. $coachList = SessionManager::getCoachesBySession($session_id);
  2734. $categoryStart = $row['session_category_date_start'] ? $row['session_category_date_start']->format('Y-m-d') : '';
  2735. $categoryEnd = $row['session_category_date_end'] ? $row['session_category_date_end']->format('Y-m-d') : '';
  2736. $courseList = self::get_courses_list_by_session(
  2737. $user_id,
  2738. $session_id
  2739. );
  2740. $daysLeft = SessionManager::getDayLeftInSession($row, $user_id);
  2741. // User portal filters:
  2742. if ($ignoreTimeLimit === false) {
  2743. if ($is_time_over) {
  2744. // History
  2745. if ($row['duration']) {
  2746. if ($daysLeft >= 0) {
  2747. continue;
  2748. }
  2749. } else {
  2750. if (empty($row['access_end_date'])) {
  2751. continue;
  2752. } else {
  2753. if ($row['access_end_date'] > $now) {
  2754. continue;
  2755. }
  2756. }
  2757. }
  2758. } else {
  2759. // Current user portal
  2760. $isGeneralCoach = SessionManager::user_is_general_coach($user_id, $row['id']);
  2761. $isCoachOfCourse = in_array($user_id, $coachList);
  2762. if (api_is_platform_admin() || $isGeneralCoach || $isCoachOfCourse) {
  2763. // Teachers can access the session depending in the access_coach date
  2764. } else {
  2765. if ($row['duration']) {
  2766. if ($daysLeft <= 0) {
  2767. continue;
  2768. }
  2769. } else {
  2770. if (isset($row['access_end_date']) &&
  2771. !empty($row['access_end_date'])
  2772. ) {
  2773. if ($row['access_end_date'] <= $now) {
  2774. continue;
  2775. }
  2776. }
  2777. }
  2778. }
  2779. }
  2780. }
  2781. $categories[$row['session_category_id']]['session_category'] = [
  2782. 'id' => $row['session_category_id'],
  2783. 'name' => $row['session_category_name'],
  2784. 'date_start' => $categoryStart,
  2785. 'date_end' => $categoryEnd,
  2786. ];
  2787. $visibility = api_get_session_visibility(
  2788. $session_id,
  2789. null,
  2790. $ignore_visibility_for_admins
  2791. );
  2792. if ($visibility != SESSION_VISIBLE) {
  2793. // Course Coach session visibility.
  2794. $blockedCourseCount = 0;
  2795. $closedVisibilityList = [
  2796. COURSE_VISIBILITY_CLOSED,
  2797. COURSE_VISIBILITY_HIDDEN,
  2798. ];
  2799. foreach ($courseList as $course) {
  2800. // Checking session visibility
  2801. $sessionCourseVisibility = api_get_session_visibility(
  2802. $session_id,
  2803. $course['real_id'],
  2804. $ignore_visibility_for_admins
  2805. );
  2806. $courseIsVisible = !in_array($course['visibility'], $closedVisibilityList);
  2807. if ($courseIsVisible === false || $sessionCourseVisibility == SESSION_INVISIBLE) {
  2808. $blockedCourseCount++;
  2809. }
  2810. }
  2811. // If all courses are blocked then no show in the list.
  2812. if ($blockedCourseCount === count($courseList)) {
  2813. $visibility = SESSION_INVISIBLE;
  2814. } else {
  2815. $visibility = $sessionCourseVisibility;
  2816. }
  2817. }
  2818. switch ($visibility) {
  2819. case SESSION_VISIBLE_READ_ONLY:
  2820. case SESSION_VISIBLE:
  2821. case SESSION_AVAILABLE:
  2822. break;
  2823. case SESSION_INVISIBLE:
  2824. if ($ignore_visibility_for_admins === false) {
  2825. continue 2;
  2826. }
  2827. }
  2828. $collapsed = '';
  2829. $collapsedAction = '';
  2830. if ($collapsable) {
  2831. $collapsableData = SessionManager::getCollapsableData(
  2832. $user_id,
  2833. $session_id,
  2834. $extraField,
  2835. $collapsableLink
  2836. );
  2837. $collapsed = $collapsableData['collapsed'];
  2838. $collapsedAction = $collapsableData['collapsable_link'];
  2839. }
  2840. $categories[$row['session_category_id']]['sessions'][] = [
  2841. 'session_name' => $row['name'],
  2842. 'session_id' => $row['id'],
  2843. 'access_start_date' => $row['access_start_date'] ? $row['access_start_date']->format('Y-m-d H:i:s') : null,
  2844. 'access_end_date' => $row['access_end_date'] ? $row['access_end_date']->format('Y-m-d H:i:s') : null,
  2845. 'coach_access_start_date' => $row['coach_access_start_date'] ? $row['coach_access_start_date']->format('Y-m-d H:i:s') : null,
  2846. 'coach_access_end_date' => $row['coach_access_end_date'] ? $row['coach_access_end_date']->format('Y-m-d H:i:s') : null,
  2847. 'courses' => $courseList,
  2848. 'collapsed' => $collapsed,
  2849. 'collapsable_link' => $collapsedAction,
  2850. 'duration' => $row['duration'],
  2851. ];
  2852. }
  2853. return $categories;
  2854. }
  2855. /**
  2856. * Gives a list of [session_id-course_code] => [status] for the current user.
  2857. *
  2858. * @param int $user_id
  2859. * @param int $sessionLimit
  2860. *
  2861. * @return array list of statuses (session_id-course_code => status)
  2862. */
  2863. public static function get_personal_session_course_list($user_id, $sessionLimit = null)
  2864. {
  2865. // Database Table Definitions
  2866. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2867. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2868. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2869. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2870. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2871. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2872. $user_id = (int) $user_id;
  2873. if (empty($user_id)) {
  2874. return [];
  2875. }
  2876. // We filter the courses from the URL
  2877. $join_access_url = $where_access_url = '';
  2878. if (api_get_multiple_access_url()) {
  2879. $access_url_id = api_get_current_access_url_id();
  2880. if ($access_url_id != -1) {
  2881. $tbl_url_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2882. $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.c_id = course.id";
  2883. $where_access_url = " AND access_url_id = $access_url_id ";
  2884. }
  2885. }
  2886. // Courses in which we subscribed out of any session
  2887. $tbl_user_course_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2888. $sql = "SELECT
  2889. course.code,
  2890. course_rel_user.status course_rel_status,
  2891. course_rel_user.sort sort,
  2892. course_rel_user.user_course_cat user_course_cat
  2893. FROM $tbl_course_user course_rel_user
  2894. LEFT JOIN $tbl_course course
  2895. ON course.id = course_rel_user.c_id
  2896. LEFT JOIN $tbl_user_course_category user_course_category
  2897. ON course_rel_user.user_course_cat = user_course_category.id
  2898. $join_access_url
  2899. WHERE
  2900. course_rel_user.user_id = '".$user_id."' AND
  2901. course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
  2902. $where_access_url
  2903. ORDER BY user_course_category.sort, course_rel_user.sort, course.title ASC";
  2904. $course_list_sql_result = Database::query($sql);
  2905. $personal_course_list = [];
  2906. if (Database::num_rows($course_list_sql_result) > 0) {
  2907. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  2908. $course_info = api_get_course_info($result_row['code']);
  2909. $result_row['course_info'] = $course_info;
  2910. $personal_course_list[] = $result_row;
  2911. }
  2912. }
  2913. $coachCourseConditions = '';
  2914. // Getting sessions that are related to a coach in the session_rel_course_rel_user table
  2915. if (api_is_allowed_to_create_course()) {
  2916. $sessionListFromCourseCoach = [];
  2917. $sql = " SELECT DISTINCT session_id
  2918. FROM $tbl_session_course_user
  2919. WHERE user_id = $user_id AND status = 2 ";
  2920. $result = Database::query($sql);
  2921. if (Database::num_rows($result)) {
  2922. $result = Database::store_result($result);
  2923. foreach ($result as $session) {
  2924. $sessionListFromCourseCoach[] = $session['session_id'];
  2925. }
  2926. }
  2927. if (!empty($sessionListFromCourseCoach)) {
  2928. $condition = implode("','", $sessionListFromCourseCoach);
  2929. $coachCourseConditions = " OR ( s.id IN ('$condition'))";
  2930. }
  2931. }
  2932. // Get the list of sessions where the user is subscribed
  2933. // This is divided into two different queries
  2934. $sessions = [];
  2935. $sessionLimitRestriction = '';
  2936. if (!empty($sessionLimit)) {
  2937. $sessionLimit = (int) $sessionLimit;
  2938. $sessionLimitRestriction = "LIMIT $sessionLimit";
  2939. }
  2940. $sql = "SELECT DISTINCT s.id, name, access_start_date, access_end_date
  2941. FROM $tbl_session_user su INNER JOIN $tbl_session s
  2942. ON (s.id = su.session_id)
  2943. WHERE (
  2944. su.user_id = $user_id AND
  2945. su.relation_type <> ".SESSION_RELATION_TYPE_RRHH."
  2946. )
  2947. $coachCourseConditions
  2948. ORDER BY access_start_date, access_end_date, name
  2949. $sessionLimitRestriction
  2950. ";
  2951. $result = Database::query($sql);
  2952. if (Database::num_rows($result) > 0) {
  2953. while ($row = Database::fetch_assoc($result)) {
  2954. $sessions[$row['id']] = $row;
  2955. }
  2956. }
  2957. $sql = "SELECT DISTINCT
  2958. id, name, access_start_date, access_end_date
  2959. FROM $tbl_session s
  2960. WHERE (
  2961. id_coach = $user_id
  2962. )
  2963. $coachCourseConditions
  2964. ORDER BY access_start_date, access_end_date, name";
  2965. $result = Database::query($sql);
  2966. if (Database::num_rows($result) > 0) {
  2967. while ($row = Database::fetch_assoc($result)) {
  2968. if (empty($sessions[$row['id']])) {
  2969. $sessions[$row['id']] = $row;
  2970. }
  2971. }
  2972. }
  2973. if (api_is_allowed_to_create_course()) {
  2974. foreach ($sessions as $enreg) {
  2975. $session_id = $enreg['id'];
  2976. $session_visibility = api_get_session_visibility($session_id);
  2977. if ($session_visibility == SESSION_INVISIBLE) {
  2978. continue;
  2979. }
  2980. // This query is horribly slow when more than a few thousand
  2981. // users and just a few sessions to which they are subscribed
  2982. $sql = "SELECT DISTINCT
  2983. course.code code,
  2984. course.title i,
  2985. ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t,
  2986. email, course.course_language l,
  2987. 1 sort,
  2988. category_code user_course_cat,
  2989. access_start_date,
  2990. access_end_date,
  2991. session.id as session_id,
  2992. session.name as session_name
  2993. FROM $tbl_session_course_user as session_course_user
  2994. INNER JOIN $tbl_course AS course
  2995. ON course.id = session_course_user.c_id
  2996. INNER JOIN $tbl_session as session
  2997. ON session.id = session_course_user.session_id
  2998. LEFT JOIN $tbl_user as user
  2999. ON user.id = session_course_user.user_id OR session.id_coach = user.id
  3000. WHERE
  3001. session_course_user.session_id = $session_id AND (
  3002. (session_course_user.user_id = $user_id AND session_course_user.status = 2)
  3003. OR session.id_coach = $user_id
  3004. )
  3005. ORDER BY i";
  3006. $course_list_sql_result = Database::query($sql);
  3007. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  3008. $result_row['course_info'] = api_get_course_info($result_row['code']);
  3009. $key = $result_row['session_id'].' - '.$result_row['code'];
  3010. $personal_course_list[$key] = $result_row;
  3011. }
  3012. }
  3013. }
  3014. foreach ($sessions as $enreg) {
  3015. $session_id = $enreg['id'];
  3016. $session_visibility = api_get_session_visibility($session_id);
  3017. if ($session_visibility == SESSION_INVISIBLE) {
  3018. continue;
  3019. }
  3020. /* This query is very similar to the above query,
  3021. but it will check the session_rel_course_user table if there are courses registered to our user or not */
  3022. $sql = "SELECT DISTINCT
  3023. course.code code,
  3024. course.title i, CONCAT(user.lastname,' ',user.firstname) t,
  3025. email,
  3026. course.course_language l,
  3027. 1 sort,
  3028. category_code user_course_cat,
  3029. access_start_date,
  3030. access_end_date,
  3031. session.id as session_id,
  3032. session.name as session_name,
  3033. IF((session_course_user.user_id = 3 AND session_course_user.status=2),'2', '5')
  3034. FROM $tbl_session_course_user as session_course_user
  3035. INNER JOIN $tbl_course AS course
  3036. ON course.id = session_course_user.c_id AND session_course_user.session_id = $session_id
  3037. INNER JOIN $tbl_session as session
  3038. ON session_course_user.session_id = session.id
  3039. LEFT JOIN $tbl_user as user ON user.id = session_course_user.user_id
  3040. WHERE session_course_user.user_id = $user_id
  3041. ORDER BY i";
  3042. $course_list_sql_result = Database::query($sql);
  3043. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  3044. $result_row['course_info'] = api_get_course_info($result_row['code']);
  3045. $key = $result_row['session_id'].' - '.$result_row['code'];
  3046. if (!isset($personal_course_list[$key])) {
  3047. $personal_course_list[$key] = $result_row;
  3048. }
  3049. }
  3050. }
  3051. return $personal_course_list;
  3052. }
  3053. /**
  3054. * Gives a list of courses for the given user in the given session.
  3055. *
  3056. * @param int $user_id
  3057. * @param int $session_id
  3058. *
  3059. * @return array list of statuses (session_id-course_code => status)
  3060. */
  3061. public static function get_courses_list_by_session($user_id, $session_id)
  3062. {
  3063. // Database Table Definitions
  3064. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3065. $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  3066. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3067. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3068. $user_id = (int) $user_id;
  3069. $session_id = (int) $session_id;
  3070. // We filter the courses from the URL
  3071. $join_access_url = $where_access_url = '';
  3072. if (api_get_multiple_access_url()) {
  3073. $urlId = api_get_current_access_url_id();
  3074. if ($urlId != -1) {
  3075. $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3076. $join_access_url = " , $tbl_url_session url_rel_session ";
  3077. $where_access_url = " AND access_url_id = $urlId AND url_rel_session.session_id = $session_id ";
  3078. }
  3079. }
  3080. /* This query is very similar to the query below, but it will check the
  3081. session_rel_course_user table if there are courses registered
  3082. to our user or not */
  3083. $sql = "SELECT DISTINCT
  3084. c.visibility,
  3085. c.id as real_id,
  3086. c.code as course_code,
  3087. sc.position
  3088. FROM $tbl_session_course_user as scu
  3089. INNER JOIN $tbl_session_course sc
  3090. ON (scu.session_id = sc.session_id AND scu.c_id = sc.c_id)
  3091. INNER JOIN $tableCourse as c
  3092. ON (scu.c_id = c.id)
  3093. $join_access_url
  3094. WHERE
  3095. scu.user_id = $user_id AND
  3096. scu.session_id = $session_id
  3097. $where_access_url
  3098. ORDER BY sc.position ASC";
  3099. $myCourseList = [];
  3100. $courses = [];
  3101. $result = Database::query($sql);
  3102. if (Database::num_rows($result) > 0) {
  3103. while ($result_row = Database::fetch_array($result, 'ASSOC')) {
  3104. $result_row['status'] = 5;
  3105. if (!in_array($result_row['real_id'], $courses)) {
  3106. $position = $result_row['position'];
  3107. if (!isset($myCourseList[$position])) {
  3108. $myCourseList[$position] = $result_row;
  3109. } else {
  3110. $myCourseList[] = $result_row;
  3111. }
  3112. $courses[] = $result_row['real_id'];
  3113. }
  3114. }
  3115. }
  3116. if (api_is_allowed_to_create_course()) {
  3117. $sql = "SELECT DISTINCT
  3118. c.visibility,
  3119. c.id as real_id,
  3120. c.code as course_code,
  3121. sc.position
  3122. FROM $tbl_session_course_user as scu
  3123. INNER JOIN $tbl_session as s
  3124. ON (scu.session_id = s.id)
  3125. INNER JOIN $tbl_session_course sc
  3126. ON (scu.session_id = sc.session_id AND scu.c_id = sc.c_id)
  3127. INNER JOIN $tableCourse as c
  3128. ON (scu.c_id = c.id)
  3129. $join_access_url
  3130. WHERE
  3131. s.id = $session_id AND
  3132. (
  3133. (scu.user_id = $user_id AND scu.status = 2) OR
  3134. s.id_coach = $user_id
  3135. )
  3136. $where_access_url
  3137. ORDER BY sc.position ASC";
  3138. $result = Database::query($sql);
  3139. if (Database::num_rows($result) > 0) {
  3140. while ($result_row = Database::fetch_array($result, 'ASSOC')) {
  3141. $result_row['status'] = 2;
  3142. if (!in_array($result_row['real_id'], $courses)) {
  3143. $position = $result_row['position'];
  3144. if (!isset($myCourseList[$position])) {
  3145. $myCourseList[$position] = $result_row;
  3146. } else {
  3147. $myCourseList[] = $result_row;
  3148. }
  3149. $courses[] = $result_row['real_id'];
  3150. }
  3151. }
  3152. }
  3153. }
  3154. if (api_is_drh()) {
  3155. $sessionList = SessionManager::get_sessions_followed_by_drh($user_id);
  3156. $sessionList = array_keys($sessionList);
  3157. if (in_array($session_id, $sessionList)) {
  3158. $courseList = SessionManager::get_course_list_by_session_id($session_id);
  3159. if (!empty($courseList)) {
  3160. foreach ($courseList as $course) {
  3161. if (!in_array($course['id'], $courses)) {
  3162. $position = $course['position'];
  3163. if (!isset($myCourseList[$position])) {
  3164. $myCourseList[$position] = $course;
  3165. } else {
  3166. $myCourseList[] = $course;
  3167. }
  3168. }
  3169. }
  3170. }
  3171. }
  3172. } else {
  3173. //check if user is general coach for this session
  3174. $sessionInfo = api_get_session_info($session_id);
  3175. if ($sessionInfo['id_coach'] == $user_id) {
  3176. $courseList = SessionManager::get_course_list_by_session_id($session_id);
  3177. if (!empty($courseList)) {
  3178. foreach ($courseList as $course) {
  3179. if (!in_array($course['id'], $courses)) {
  3180. $position = $course['position'];
  3181. if (!isset($myCourseList[$position])) {
  3182. $myCourseList[$position] = $course;
  3183. } else {
  3184. $myCourseList[] = $course;
  3185. }
  3186. }
  3187. }
  3188. }
  3189. }
  3190. }
  3191. if (!empty($myCourseList)) {
  3192. ksort($myCourseList);
  3193. $checkPosition = array_filter(array_column($myCourseList, 'position'));
  3194. if (empty($checkPosition)) {
  3195. // The session course list doesn't have any position,
  3196. // then order the course list by course code
  3197. $list = array_column($myCourseList, 'course_code');
  3198. array_multisort($myCourseList, SORT_ASC, $list);
  3199. }
  3200. }
  3201. return $myCourseList;
  3202. }
  3203. /**
  3204. * Get user id from a username.
  3205. *
  3206. * @param string $username
  3207. *
  3208. * @return int User ID (or false if not found)
  3209. */
  3210. public static function get_user_id_from_username($username)
  3211. {
  3212. if (empty($username)) {
  3213. return false;
  3214. }
  3215. $username = trim($username);
  3216. $username = Database::escape_string($username);
  3217. $t_user = Database::get_main_table(TABLE_MAIN_USER);
  3218. $sql = "SELECT id FROM $t_user WHERE username = '$username'";
  3219. $res = Database::query($sql);
  3220. if ($res === false) {
  3221. return false;
  3222. }
  3223. if (Database::num_rows($res) !== 1) {
  3224. return false;
  3225. }
  3226. $row = Database::fetch_array($res);
  3227. return $row['id'];
  3228. }
  3229. /**
  3230. * Get the users files upload from his share_folder.
  3231. *
  3232. * @param string $user_id User ID
  3233. * @param string $course course directory
  3234. * @param string $resourceType resource type: images, all
  3235. *
  3236. * @return string
  3237. */
  3238. public static function get_user_upload_files_by_course(
  3239. $user_id,
  3240. $course,
  3241. $resourceType = 'all'
  3242. ) {
  3243. $return = '';
  3244. $user_id = (int) $user_id;
  3245. if (!empty($user_id) && !empty($course)) {
  3246. $path = api_get_path(SYS_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  3247. $web_path = api_get_path(WEB_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  3248. $file_list = [];
  3249. if (is_dir($path)) {
  3250. $handle = opendir($path);
  3251. while ($file = readdir($handle)) {
  3252. if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($path.$file)) {
  3253. continue; // skip current/parent directory and .htaccess
  3254. }
  3255. $file_list[] = $file;
  3256. }
  3257. if (count($file_list) > 0) {
  3258. $return = "<h4>$course</h4>";
  3259. $return .= '<ul class="thumbnails">';
  3260. }
  3261. $extensionList = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tif'];
  3262. foreach ($file_list as $file) {
  3263. if ($resourceType == 'all') {
  3264. $return .= '<li>
  3265. <a href="'.$web_path.urlencode($file).'" target="_blank">'.htmlentities($file).'</a></li>';
  3266. } elseif ($resourceType == 'images') {
  3267. //get extension
  3268. $ext = explode('.', $file);
  3269. if (isset($ext[1]) && in_array($ext[1], $extensionList)) {
  3270. $return .= '<li class="span2">
  3271. <a class="thumbnail" href="'.$web_path.urlencode($file).'" target="_blank">
  3272. <img src="'.$web_path.urlencode($file).'" >
  3273. </a>
  3274. </li>';
  3275. }
  3276. }
  3277. }
  3278. if (count($file_list) > 0) {
  3279. $return .= '</ul>';
  3280. }
  3281. }
  3282. }
  3283. return $return;
  3284. }
  3285. /**
  3286. * Gets the API key (or keys) and return them into an array.
  3287. *
  3288. * @param int Optional user id (defaults to the result of api_get_user_id())
  3289. * @param string $api_service
  3290. *
  3291. * @return mixed Non-indexed array containing the list of API keys for this user, or FALSE on error
  3292. */
  3293. public static function get_api_keys($user_id = null, $api_service = 'dokeos')
  3294. {
  3295. if ($user_id != strval(intval($user_id))) {
  3296. return false;
  3297. }
  3298. if (empty($user_id)) {
  3299. $user_id = api_get_user_id();
  3300. }
  3301. if ($user_id === false) {
  3302. return false;
  3303. }
  3304. $service_name = Database::escape_string($api_service);
  3305. if (is_string($service_name) === false) {
  3306. return false;
  3307. }
  3308. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3309. $sql = "SELECT * FROM $t_api WHERE user_id = $user_id AND api_service='$api_service';";
  3310. $res = Database::query($sql);
  3311. if ($res === false) {
  3312. return false;
  3313. } //error during query
  3314. $num = Database::num_rows($res);
  3315. if ($num == 0) {
  3316. return false;
  3317. }
  3318. $list = [];
  3319. while ($row = Database::fetch_array($res)) {
  3320. $list[$row['id']] = $row['api_key'];
  3321. }
  3322. return $list;
  3323. }
  3324. /**
  3325. * Adds a new API key to the users' account.
  3326. *
  3327. * @param int Optional user ID (defaults to the results of api_get_user_id())
  3328. * @param string $api_service
  3329. *
  3330. * @return bool True on success, false on failure
  3331. */
  3332. public static function add_api_key($user_id = null, $api_service = 'dokeos')
  3333. {
  3334. if ($user_id != strval(intval($user_id))) {
  3335. return false;
  3336. }
  3337. if (empty($user_id)) {
  3338. $user_id = api_get_user_id();
  3339. }
  3340. if ($user_id === false) {
  3341. return false;
  3342. }
  3343. $service_name = Database::escape_string($api_service);
  3344. if (is_string($service_name) === false) {
  3345. return false;
  3346. }
  3347. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3348. $md5 = md5((time() + ($user_id * 5)) - rand(10000, 10000)); //generate some kind of random key
  3349. $sql = "INSERT INTO $t_api (user_id, api_key,api_service) VALUES ($user_id,'$md5','$service_name')";
  3350. $res = Database::query($sql);
  3351. if ($res === false) {
  3352. return false;
  3353. } //error during query
  3354. $num = Database::insert_id();
  3355. return $num == 0 ? false : $num;
  3356. }
  3357. /**
  3358. * Deletes an API key from the user's account.
  3359. *
  3360. * @param int API key's internal ID
  3361. *
  3362. * @return bool True on success, false on failure
  3363. */
  3364. public static function delete_api_key($key_id)
  3365. {
  3366. if ($key_id != strval(intval($key_id))) {
  3367. return false;
  3368. }
  3369. if ($key_id === false) {
  3370. return false;
  3371. }
  3372. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3373. $sql = "SELECT * FROM $t_api WHERE id = ".$key_id;
  3374. $res = Database::query($sql);
  3375. if ($res === false) {
  3376. return false;
  3377. } //error during query
  3378. $num = Database::num_rows($res);
  3379. if ($num !== 1) {
  3380. return false;
  3381. }
  3382. $sql = "DELETE FROM $t_api WHERE id = ".$key_id;
  3383. $res = Database::query($sql);
  3384. if ($res === false) {
  3385. return false;
  3386. } //error during query
  3387. return true;
  3388. }
  3389. /**
  3390. * Regenerate an API key from the user's account.
  3391. *
  3392. * @param int user ID (defaults to the results of api_get_user_id())
  3393. * @param string API key's internal ID
  3394. *
  3395. * @return int num
  3396. */
  3397. public static function update_api_key($user_id, $api_service)
  3398. {
  3399. if ($user_id != strval(intval($user_id))) {
  3400. return false;
  3401. }
  3402. if ($user_id === false) {
  3403. return false;
  3404. }
  3405. $service_name = Database::escape_string($api_service);
  3406. if (is_string($service_name) === false) {
  3407. return false;
  3408. }
  3409. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3410. $sql = "SELECT id FROM $t_api
  3411. WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  3412. $res = Database::query($sql);
  3413. $num = Database::num_rows($res);
  3414. if ($num == 1) {
  3415. $id_key = Database::fetch_array($res, 'ASSOC');
  3416. self::delete_api_key($id_key['id']);
  3417. $num = self::add_api_key($user_id, $api_service);
  3418. } elseif ($num == 0) {
  3419. $num = self::add_api_key($user_id, $api_service);
  3420. }
  3421. return $num;
  3422. }
  3423. /**
  3424. * @param int user ID (defaults to the results of api_get_user_id())
  3425. * @param string API key's internal ID
  3426. *
  3427. * @return int row ID, or return false if not found
  3428. */
  3429. public static function get_api_key_id($user_id, $api_service)
  3430. {
  3431. if ($user_id != strval(intval($user_id))) {
  3432. return false;
  3433. }
  3434. if ($user_id === false) {
  3435. return false;
  3436. }
  3437. if (empty($api_service)) {
  3438. return false;
  3439. }
  3440. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3441. $api_service = Database::escape_string($api_service);
  3442. $sql = "SELECT id FROM $t_api
  3443. WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  3444. $res = Database::query($sql);
  3445. if (Database::num_rows($res) < 1) {
  3446. return false;
  3447. }
  3448. $row = Database::fetch_array($res, 'ASSOC');
  3449. return $row['id'];
  3450. }
  3451. /**
  3452. * Checks if a user_id is platform admin.
  3453. *
  3454. * @param int user ID
  3455. *
  3456. * @return bool True if is admin, false otherwise
  3457. *
  3458. * @see main_api.lib.php::api_is_platform_admin() for a context-based check
  3459. */
  3460. public static function is_admin($user_id)
  3461. {
  3462. $user_id = (int) $user_id;
  3463. if (empty($user_id)) {
  3464. return false;
  3465. }
  3466. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  3467. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  3468. $res = Database::query($sql);
  3469. return Database::num_rows($res) === 1;
  3470. }
  3471. /**
  3472. * Get the total count of users.
  3473. *
  3474. * @param int Status of users to be counted
  3475. * @param int Access URL ID (optional)
  3476. *
  3477. * @return mixed Number of users or false on error
  3478. */
  3479. public static function get_number_of_users($status = 0, $access_url_id = 1)
  3480. {
  3481. $t_u = Database::get_main_table(TABLE_MAIN_USER);
  3482. $t_a = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3483. if (api_is_multiple_url_enabled()) {
  3484. $sql = "SELECT count(u.id)
  3485. FROM $t_u u
  3486. INNER JOIN $t_a url_user
  3487. ON (u.id = url_user.user_id)
  3488. WHERE url_user.access_url_id = $access_url_id
  3489. ";
  3490. } else {
  3491. $sql = "SELECT count(u.id)
  3492. FROM $t_u u
  3493. WHERE 1 = 1 ";
  3494. }
  3495. if (is_int($status) && $status > 0) {
  3496. $sql .= " AND u.status = $status ";
  3497. }
  3498. $res = Database::query($sql);
  3499. if (Database::num_rows($res) === 1) {
  3500. return (int) Database::result($res, 0, 0);
  3501. }
  3502. return false;
  3503. }
  3504. /**
  3505. * Gets the tags of a specific field_id
  3506. * USER TAGS.
  3507. *
  3508. * Instructions to create a new user tag by Julio Montoya <gugli100@gmail.com>
  3509. *
  3510. * 1. Create a new extra field in main/admin/user_fields.php with the "TAG" field type make it available and visible.
  3511. * Called it "books" for example.
  3512. * 2. Go to profile main/auth/profile.php There you will see a special input (facebook style) that will show suggestions of tags.
  3513. * 3. All the tags are registered in the user_tag table and the relationship between user and tags is in the user_rel_tag table
  3514. * 4. Tags are independent this means that tags can't be shared between tags + book + hobbies.
  3515. * 5. Test and enjoy.
  3516. *
  3517. * @param string $tag
  3518. * @param int $field_id field_id
  3519. * @param string $return_format how we are going to result value in array or in a string (json)
  3520. * @param $limit
  3521. *
  3522. * @return mixed
  3523. */
  3524. public static function get_tags($tag, $field_id, $return_format = 'json', $limit = 10)
  3525. {
  3526. // database table definition
  3527. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3528. $field_id = (int) $field_id;
  3529. $limit = (int) $limit;
  3530. $tag = trim(Database::escape_string($tag));
  3531. // all the information of the field
  3532. $sql = "SELECT DISTINCT id, tag from $table_user_tag
  3533. WHERE field_id = $field_id AND tag LIKE '$tag%' ORDER BY tag LIMIT $limit";
  3534. $result = Database::query($sql);
  3535. $return = [];
  3536. if (Database::num_rows($result) > 0) {
  3537. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3538. $return[] = ['id' => $row['tag'], 'text' => $row['tag']];
  3539. }
  3540. }
  3541. if ($return_format === 'json') {
  3542. $return = json_encode($return);
  3543. }
  3544. return $return;
  3545. }
  3546. /**
  3547. * @param int $field_id
  3548. * @param int $limit
  3549. *
  3550. * @return array
  3551. */
  3552. public static function get_top_tags($field_id, $limit = 100)
  3553. {
  3554. // database table definition
  3555. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3556. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3557. $field_id = (int) $field_id;
  3558. $limit = (int) $limit;
  3559. // all the information of the field
  3560. $sql = "SELECT count(*) count, tag FROM $table_user_tag_values uv
  3561. INNER JOIN $table_user_tag ut
  3562. ON (ut.id = uv.tag_id)
  3563. WHERE field_id = $field_id
  3564. GROUP BY tag_id
  3565. ORDER BY count DESC
  3566. LIMIT $limit";
  3567. $result = Database::query($sql);
  3568. $return = [];
  3569. if (Database::num_rows($result) > 0) {
  3570. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3571. $return[] = $row;
  3572. }
  3573. }
  3574. return $return;
  3575. }
  3576. /**
  3577. * Get user's tags.
  3578. *
  3579. * @param int $user_id
  3580. * @param int $field_id
  3581. *
  3582. * @return array
  3583. */
  3584. public static function get_user_tags($user_id, $field_id)
  3585. {
  3586. // database table definition
  3587. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3588. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3589. $field_id = (int) $field_id;
  3590. $user_id = (int) $user_id;
  3591. // all the information of the field
  3592. $sql = "SELECT ut.id, tag, count
  3593. FROM $table_user_tag ut
  3594. INNER JOIN $table_user_tag_values uv
  3595. ON (uv.tag_id=ut.ID)
  3596. WHERE field_id = $field_id AND user_id = $user_id
  3597. ORDER BY tag";
  3598. $result = Database::query($sql);
  3599. $return = [];
  3600. if (Database::num_rows($result) > 0) {
  3601. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3602. $return[$row['id']] = ['tag' => $row['tag'], 'count' => $row['count']];
  3603. }
  3604. }
  3605. return $return;
  3606. }
  3607. /**
  3608. * Get user's tags.
  3609. *
  3610. * @param int $user_id
  3611. * @param int $field_id
  3612. * @param bool $show_links show links or not
  3613. *
  3614. * @return string
  3615. */
  3616. public static function get_user_tags_to_string($user_id, $field_id, $show_links = true)
  3617. {
  3618. // database table definition
  3619. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3620. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3621. $field_id = (int) $field_id;
  3622. $user_id = (int) $user_id;
  3623. // all the information of the field
  3624. $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut
  3625. INNER JOIN $table_user_tag_values uv
  3626. ON (uv.tag_id = ut.id)
  3627. WHERE field_id = $field_id AND user_id = $user_id
  3628. ORDER BY tag";
  3629. $result = Database::query($sql);
  3630. $return = [];
  3631. if (Database::num_rows($result) > 0) {
  3632. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3633. $return[$row['id']] = ['tag' => $row['tag'], 'count' => $row['count']];
  3634. }
  3635. }
  3636. $user_tags = $return;
  3637. $tag_tmp = [];
  3638. foreach ($user_tags as $tag) {
  3639. if ($show_links) {
  3640. $tag_tmp[] = '<a href="'.api_get_path(WEB_PATH).'main/search/index.php?q='.$tag['tag'].'">'.
  3641. $tag['tag'].
  3642. '</a>';
  3643. } else {
  3644. $tag_tmp[] = $tag['tag'];
  3645. }
  3646. }
  3647. if (is_array($user_tags) && count($user_tags) > 0) {
  3648. return implode(', ', $tag_tmp);
  3649. } else {
  3650. return '';
  3651. }
  3652. }
  3653. /**
  3654. * Get the tag id.
  3655. *
  3656. * @param int $tag
  3657. * @param int $field_id
  3658. *
  3659. * @return int returns 0 if fails otherwise the tag id
  3660. */
  3661. public static function get_tag_id($tag, $field_id)
  3662. {
  3663. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3664. $tag = Database::escape_string($tag);
  3665. $field_id = (int) $field_id;
  3666. //with COLLATE latin1_bin to select query in a case sensitive mode
  3667. $sql = "SELECT id FROM $table_user_tag
  3668. WHERE tag LIKE '$tag' AND field_id = $field_id";
  3669. $result = Database::query($sql);
  3670. if (Database::num_rows($result) > 0) {
  3671. $row = Database::fetch_array($result, 'ASSOC');
  3672. return $row['id'];
  3673. } else {
  3674. return 0;
  3675. }
  3676. }
  3677. /**
  3678. * Get the tag id.
  3679. *
  3680. * @param int $tag_id
  3681. * @param int $field_id
  3682. *
  3683. * @return int 0 if fails otherwise the tag id
  3684. */
  3685. public static function get_tag_id_from_id($tag_id, $field_id)
  3686. {
  3687. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3688. $tag_id = (int) $tag_id;
  3689. $field_id = (int) $field_id;
  3690. $sql = "SELECT id FROM $table_user_tag
  3691. WHERE id = '$tag_id' AND field_id = $field_id";
  3692. $result = Database::query($sql);
  3693. if (Database::num_rows($result) > 0) {
  3694. $row = Database::fetch_array($result, 'ASSOC');
  3695. return $row['id'];
  3696. } else {
  3697. return false;
  3698. }
  3699. }
  3700. /**
  3701. * Adds a user-tag value.
  3702. *
  3703. * @param mixed $tag
  3704. * @param int $user_id
  3705. * @param int $field_id field id of the tag
  3706. *
  3707. * @return bool True if the tag was inserted or updated. False otherwise.
  3708. * The return value doesn't take into account *values* added to the tag.
  3709. * Only the creation/update of the tag field itself.
  3710. */
  3711. public static function add_tag($tag, $user_id, $field_id)
  3712. {
  3713. // database table definition
  3714. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3715. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3716. $tag = trim(Database::escape_string($tag));
  3717. $user_id = (int) $user_id;
  3718. $field_id = (int) $field_id;
  3719. $tag_id = self::get_tag_id($tag, $field_id);
  3720. /* IMPORTANT
  3721. * @todo we don't create tags with numbers
  3722. *
  3723. */
  3724. if (is_numeric($tag)) {
  3725. //the form is sending an id this means that the user select it from the list so it MUST exists
  3726. /* $new_tag_id = self::get_tag_id_from_id($tag,$field_id);
  3727. if ($new_tag_id !== false) {
  3728. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $new_tag_id";
  3729. $result = Database::query($sql);
  3730. $last_insert_id = $new_tag_id;
  3731. } else {
  3732. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  3733. $result = Database::query($sql);
  3734. $last_insert_id = Database::insert_id();
  3735. } */
  3736. }
  3737. //this is a new tag
  3738. if ($tag_id == 0) {
  3739. //the tag doesn't exist
  3740. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  3741. Database::query($sql);
  3742. $last_insert_id = Database::insert_id();
  3743. } else {
  3744. //the tag exists we update it
  3745. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $tag_id";
  3746. Database::query($sql);
  3747. $last_insert_id = $tag_id;
  3748. }
  3749. if (!empty($last_insert_id) && ($last_insert_id != 0)) {
  3750. //we insert the relationship user-tag
  3751. $sql = "SELECT tag_id FROM $table_user_tag_values
  3752. WHERE user_id = $user_id AND tag_id = $last_insert_id ";
  3753. $result = Database::query($sql);
  3754. //if the relationship does not exist we create it
  3755. if (Database::num_rows($result) == 0) {
  3756. $sql = "INSERT INTO $table_user_tag_values SET user_id = $user_id, tag_id = $last_insert_id";
  3757. Database::query($sql);
  3758. }
  3759. return true;
  3760. }
  3761. return false;
  3762. }
  3763. /**
  3764. * Deletes an user tag.
  3765. *
  3766. * @param int $user_id
  3767. * @param int $field_id
  3768. */
  3769. public static function delete_user_tags($user_id, $field_id)
  3770. {
  3771. // database table definition
  3772. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3773. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3774. $user_id = (int) $user_id;
  3775. $tags = self::get_user_tags($user_id, $field_id);
  3776. if (is_array($tags) && count($tags) > 0) {
  3777. foreach ($tags as $key => $tag) {
  3778. if ($tag['count'] > '0') {
  3779. $sql = "UPDATE $table_user_tag SET count = count - 1 WHERE id = $key ";
  3780. Database::query($sql);
  3781. }
  3782. $sql = "DELETE FROM $table_user_tag_values
  3783. WHERE user_id = $user_id AND tag_id = $key";
  3784. Database::query($sql);
  3785. }
  3786. }
  3787. }
  3788. /**
  3789. * Process the tag list comes from the UserManager::update_extra_field_value() function.
  3790. *
  3791. * @param array $tags the tag list that will be added
  3792. * @param int $user_id
  3793. * @param int $field_id
  3794. *
  3795. * @return bool
  3796. */
  3797. public static function process_tags($tags, $user_id, $field_id)
  3798. {
  3799. // We loop the tags and add it to the DB
  3800. if (is_array($tags)) {
  3801. foreach ($tags as $tag) {
  3802. self::add_tag($tag, $user_id, $field_id);
  3803. }
  3804. } else {
  3805. self::add_tag($tags, $user_id, $field_id);
  3806. }
  3807. return true;
  3808. }
  3809. /**
  3810. * Returns a list of all administrators.
  3811. *
  3812. * @return array
  3813. */
  3814. public static function get_all_administrators()
  3815. {
  3816. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  3817. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  3818. $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3819. $access_url_id = api_get_current_access_url_id();
  3820. if (api_get_multiple_access_url()) {
  3821. $sql = "SELECT admin.user_id, username, firstname, lastname, email, active
  3822. FROM $tbl_url_rel_user as url
  3823. INNER JOIN $table_admin as admin
  3824. ON (admin.user_id=url.user_id)
  3825. INNER JOIN $table_user u
  3826. ON (u.id=admin.user_id)
  3827. WHERE access_url_id ='".$access_url_id."'";
  3828. } else {
  3829. $sql = "SELECT admin.user_id, username, firstname, lastname, email, active
  3830. FROM $table_admin as admin
  3831. INNER JOIN $table_user u
  3832. ON (u.id=admin.user_id)";
  3833. }
  3834. $result = Database::query($sql);
  3835. $return = [];
  3836. if (Database::num_rows($result) > 0) {
  3837. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3838. $return[$row['user_id']] = $row;
  3839. }
  3840. }
  3841. return $return;
  3842. }
  3843. /**
  3844. * Search an user (tags, first name, last name and email ).
  3845. *
  3846. * @param string $tag
  3847. * @param int $field_id field id of the tag
  3848. * @param int $from where to start in the query
  3849. * @param int $number_of_items
  3850. * @param bool $getCount get count or not
  3851. *
  3852. * @return array
  3853. */
  3854. public static function get_all_user_tags(
  3855. $tag,
  3856. $field_id = 0,
  3857. $from = 0,
  3858. $number_of_items = 10,
  3859. $getCount = false
  3860. ) {
  3861. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  3862. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3863. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3864. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3865. $field_id = intval($field_id);
  3866. $from = intval($from);
  3867. $number_of_items = intval($number_of_items);
  3868. $where_field = "";
  3869. $where_extra_fields = self::get_search_form_where_extra_fields();
  3870. if ($field_id != 0) {
  3871. $where_field = " field_id = $field_id AND ";
  3872. }
  3873. // all the information of the field
  3874. if ($getCount) {
  3875. $select = "SELECT count(DISTINCT u.id) count";
  3876. } else {
  3877. $select = "SELECT DISTINCT u.id, u.username, firstname, lastname, email, tag, picture_uri";
  3878. }
  3879. $sql = " $select
  3880. FROM $user_table u
  3881. INNER JOIN $access_url_rel_user_table url_rel_user
  3882. ON (u.id = url_rel_user.user_id)
  3883. LEFT JOIN $table_user_tag_values uv
  3884. ON (u.id AND uv.user_id AND uv.user_id = url_rel_user.user_id)
  3885. LEFT JOIN $table_user_tag ut ON (uv.tag_id = ut.id)
  3886. WHERE
  3887. ($where_field tag LIKE '".Database::escape_string($tag."%")."') OR
  3888. (
  3889. u.firstname LIKE '".Database::escape_string("%".$tag."%")."' OR
  3890. u.lastname LIKE '".Database::escape_string("%".$tag."%")."' OR
  3891. u.username LIKE '".Database::escape_string("%".$tag."%")."' OR
  3892. concat(u.firstname, ' ', u.lastname) LIKE '".Database::escape_string("%".$tag."%")."' OR
  3893. concat(u.lastname, ' ', u.firstname) LIKE '".Database::escape_string("%".$tag."%")."'
  3894. )
  3895. ".(!empty($where_extra_fields) ? $where_extra_fields : '')."
  3896. AND url_rel_user.access_url_id=".api_get_current_access_url_id();
  3897. $keyword_active = true;
  3898. // only active users
  3899. if ($keyword_active) {
  3900. $sql .= " AND u.active='1'";
  3901. }
  3902. // avoid anonymous
  3903. $sql .= " AND u.status <> 6 ";
  3904. $sql .= " ORDER BY username";
  3905. $sql .= " LIMIT $from , $number_of_items";
  3906. $result = Database::query($sql);
  3907. $return = [];
  3908. if (Database::num_rows($result) > 0) {
  3909. if ($getCount) {
  3910. $row = Database::fetch_array($result, 'ASSOC');
  3911. return $row['count'];
  3912. }
  3913. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3914. if (isset($return[$row['id']]) &&
  3915. !empty($return[$row['id']]['tag'])
  3916. ) {
  3917. $url = Display::url(
  3918. $row['tag'],
  3919. api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'],
  3920. ['class' => 'tag']
  3921. );
  3922. $row['tag'] = $url;
  3923. }
  3924. $return[$row['id']] = $row;
  3925. }
  3926. }
  3927. return $return;
  3928. }
  3929. /**
  3930. * Get extra filterable user fields (only type select).
  3931. *
  3932. * @return array Array of extra fields as [int => ['name' => ..., 'variable' => ..., 'data' => ...]] (
  3933. * or empty array if no extra field)
  3934. */
  3935. public static function getExtraFilterableFields()
  3936. {
  3937. $extraFieldList = self::get_extra_fields();
  3938. $fields = [];
  3939. if (is_array($extraFieldList)) {
  3940. foreach ($extraFieldList as $extraField) {
  3941. // If is enabled to filter and is a "<select>" field type
  3942. if ($extraField[8] == 1 && $extraField[2] == 4) {
  3943. $fields[] = [
  3944. 'name' => $extraField[3],
  3945. 'variable' => $extraField[1],
  3946. 'data' => $extraField[9],
  3947. ];
  3948. }
  3949. }
  3950. }
  3951. return $fields;
  3952. }
  3953. /**
  3954. * Get extra where clauses for finding users based on extra filterable user fields (type select).
  3955. *
  3956. * @return string With AND clauses based on user's ID which have the values to search in extra user fields
  3957. * (or empty if no extra field exists)
  3958. */
  3959. public static function get_search_form_where_extra_fields()
  3960. {
  3961. $useExtraFields = false;
  3962. $extraFields = self::getExtraFilterableFields();
  3963. $extraFieldResult = [];
  3964. if (is_array($extraFields) && count($extraFields) > 0) {
  3965. foreach ($extraFields as $extraField) {
  3966. $varName = 'field_'.$extraField['variable'];
  3967. if (self::is_extra_field_available($extraField['variable'])) {
  3968. if (isset($_GET[$varName]) && $_GET[$varName] != '0') {
  3969. $useExtraFields = true;
  3970. $extraFieldResult[] = self::get_extra_user_data_by_value(
  3971. $extraField['variable'],
  3972. $_GET[$varName]
  3973. );
  3974. }
  3975. }
  3976. }
  3977. }
  3978. if ($useExtraFields) {
  3979. $finalResult = [];
  3980. if (count($extraFieldResult) > 1) {
  3981. for ($i = 0; $i < count($extraFieldResult) - 1; $i++) {
  3982. if (is_array($extraFieldResult[$i]) && is_array($extraFieldResult[$i + 1])) {
  3983. $finalResult = array_intersect($extraFieldResult[$i], $extraFieldResult[$i + 1]);
  3984. }
  3985. }
  3986. } else {
  3987. $finalResult = $extraFieldResult[0];
  3988. }
  3989. if (is_array($finalResult) && count($finalResult) > 0) {
  3990. $whereFilter = " AND u.id IN ('".implode("','", $finalResult)."') ";
  3991. } else {
  3992. //no results
  3993. $whereFilter = " AND u.id = -1 ";
  3994. }
  3995. return $whereFilter;
  3996. }
  3997. return '';
  3998. }
  3999. /**
  4000. * Show the search form.
  4001. *
  4002. * @param string $query the value of the search box
  4003. *
  4004. * @throws Exception
  4005. *
  4006. * @return string HTML form
  4007. */
  4008. public static function get_search_form($query, $defaultParams = [])
  4009. {
  4010. $searchType = isset($_GET['search_type']) ? $_GET['search_type'] : null;
  4011. $form = new FormValidator(
  4012. 'search_user',
  4013. 'get',
  4014. api_get_path(WEB_PATH).'main/social/search.php',
  4015. '',
  4016. [],
  4017. FormValidator::LAYOUT_HORIZONTAL
  4018. );
  4019. $query = Security::remove_XSS($query);
  4020. if (!empty($query)) {
  4021. $form->addHeader(get_lang('Results').' "'.$query.'"');
  4022. }
  4023. $form->addText(
  4024. 'q',
  4025. get_lang('UsersGroups'),
  4026. false,
  4027. [
  4028. 'id' => 'q',
  4029. ]
  4030. );
  4031. $options = [
  4032. 0 => get_lang('Select'),
  4033. 1 => get_lang('User'),
  4034. 2 => get_lang('Group'),
  4035. ];
  4036. $form->addSelect(
  4037. 'search_type',
  4038. get_lang('Type'),
  4039. $options,
  4040. ['onchange' => 'javascript: extra_field_toogle();', 'id' => 'search_type']
  4041. );
  4042. // Extra fields
  4043. $extraFields = self::getExtraFilterableFields();
  4044. $defaults = [];
  4045. if (is_array($extraFields) && count($extraFields) > 0) {
  4046. foreach ($extraFields as $extraField) {
  4047. $varName = 'field_'.$extraField['variable'];
  4048. $options = [
  4049. 0 => get_lang('Select'),
  4050. ];
  4051. foreach ($extraField['data'] as $option) {
  4052. if (isset($_GET[$varName])) {
  4053. if ($_GET[$varName] == $option[1]) {
  4054. $defaults[$option[1]] = true;
  4055. }
  4056. }
  4057. $options[$option[1]] = $option[1];
  4058. }
  4059. $form->addSelect($varName, $extraField['name'], $options);
  4060. }
  4061. }
  4062. $defaults['search_type'] = (int) $searchType;
  4063. $defaults['q'] = $query;
  4064. if (!empty($defaultParams)) {
  4065. $defaults = array_merge($defaults, $defaultParams);
  4066. }
  4067. $form->setDefaults($defaults);
  4068. $form->addButtonSearch(get_lang('Search'));
  4069. $js = '<script>
  4070. extra_field_toogle();
  4071. function extra_field_toogle() {
  4072. if (jQuery("select[name=search_type]").val() != "1") {
  4073. jQuery(".extra_field").hide();
  4074. } else {
  4075. jQuery(".extra_field").show();
  4076. }
  4077. }
  4078. </script>';
  4079. return $js.$form->returnForm();
  4080. }
  4081. /**
  4082. * Shows the user menu.
  4083. */
  4084. public static function show_menu()
  4085. {
  4086. echo '<div class="actions">';
  4087. echo '<a href="/main/auth/profile.php">'.
  4088. Display::return_icon('profile.png').' '.get_lang('PersonalData').'</a>';
  4089. echo '<a href="/main/messages/inbox.php">'.
  4090. Display::return_icon('inbox.png').' '.get_lang('Inbox').'</a>';
  4091. echo '<a href="/main/messages/outbox.php">'.
  4092. Display::return_icon('outbox.png').' '.get_lang('Outbox').'</a>';
  4093. echo '<span style="float:right; padding-top:7px;">'.
  4094. '<a href="/main/auth/profile.php?show=1">'.
  4095. Display::return_icon('edit.gif').' '.get_lang('Configuration').'</a>';
  4096. echo '</span>';
  4097. echo '</div>';
  4098. }
  4099. /**
  4100. * Allow to register contact to social network.
  4101. *
  4102. * @param int $friend_id user friend id
  4103. * @param int $my_user_id user id
  4104. * @param int $relation_type relation between users see constants definition
  4105. *
  4106. * @return bool
  4107. */
  4108. public static function relate_users($friend_id, $my_user_id, $relation_type)
  4109. {
  4110. $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4111. $friend_id = (int) $friend_id;
  4112. $my_user_id = (int) $my_user_id;
  4113. $relation_type = (int) $relation_type;
  4114. $sql = 'SELECT COUNT(*) as count FROM '.$tbl_my_friend.'
  4115. WHERE
  4116. friend_user_id='.$friend_id.' AND
  4117. user_id='.$my_user_id.' AND
  4118. relation_type NOT IN('.USER_RELATION_TYPE_RRHH.', '.USER_RELATION_TYPE_BOSS.') ';
  4119. $result = Database::query($sql);
  4120. $row = Database::fetch_array($result, 'ASSOC');
  4121. $current_date = api_get_utc_datetime();
  4122. if ($row['count'] == 0) {
  4123. $sql = 'INSERT INTO '.$tbl_my_friend.'(friend_user_id,user_id,relation_type,last_edit)
  4124. VALUES ('.$friend_id.','.$my_user_id.','.$relation_type.',"'.$current_date.'")';
  4125. Database::query($sql);
  4126. return true;
  4127. }
  4128. $sql = 'SELECT COUNT(*) as count, relation_type FROM '.$tbl_my_friend.'
  4129. WHERE
  4130. friend_user_id='.$friend_id.' AND
  4131. user_id='.$my_user_id.' AND
  4132. relation_type NOT IN('.USER_RELATION_TYPE_RRHH.', '.USER_RELATION_TYPE_BOSS.') ';
  4133. $result = Database::query($sql);
  4134. $row = Database::fetch_array($result, 'ASSOC');
  4135. if ($row['count'] == 1) {
  4136. //only for the case of a RRHH or a Student BOSS
  4137. if ($row['relation_type'] != $relation_type &&
  4138. ($relation_type == USER_RELATION_TYPE_RRHH || $relation_type == USER_RELATION_TYPE_BOSS)
  4139. ) {
  4140. $sql = 'INSERT INTO '.$tbl_my_friend.'(friend_user_id,user_id,relation_type,last_edit)
  4141. VALUES ('.$friend_id.','.$my_user_id.','.$relation_type.',"'.$current_date.'")';
  4142. } else {
  4143. $sql = 'UPDATE '.$tbl_my_friend.' SET relation_type='.$relation_type.'
  4144. WHERE friend_user_id='.$friend_id.' AND user_id='.$my_user_id;
  4145. }
  4146. Database::query($sql);
  4147. return true;
  4148. }
  4149. return false;
  4150. }
  4151. /**
  4152. * Deletes a contact.
  4153. *
  4154. * @param bool $friend_id
  4155. * @param bool $real_removed true will delete ALL friends relationship
  4156. * @param string $with_status_condition
  4157. *
  4158. * @author isaac flores paz <isaac.flores@dokeos.com>
  4159. * @author Julio Montoya <gugli100@gmail.com> Cleaning code
  4160. */
  4161. public static function remove_user_rel_user(
  4162. $friend_id,
  4163. $real_removed = false,
  4164. $with_status_condition = ''
  4165. ) {
  4166. $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4167. $tbl_my_message = Database::get_main_table(TABLE_MESSAGE);
  4168. $friend_id = (int) $friend_id;
  4169. $user_id = api_get_user_id();
  4170. if ($real_removed) {
  4171. $extra_condition = '';
  4172. if ($with_status_condition != '') {
  4173. $extra_condition = ' AND relation_type = '.intval($with_status_condition);
  4174. }
  4175. $sql = 'DELETE FROM '.$tbl_my_friend.'
  4176. WHERE
  4177. relation_type <> '.USER_RELATION_TYPE_RRHH.' AND
  4178. friend_user_id='.$friend_id.' '.$extra_condition;
  4179. Database::query($sql);
  4180. $sql = 'DELETE FROM '.$tbl_my_friend.'
  4181. WHERE
  4182. relation_type <> '.USER_RELATION_TYPE_RRHH.' AND
  4183. user_id='.$friend_id.' '.$extra_condition;
  4184. Database::query($sql);
  4185. } else {
  4186. $sql = 'SELECT COUNT(*) as count FROM '.$tbl_my_friend.'
  4187. WHERE
  4188. user_id='.$user_id.' AND
  4189. relation_type NOT IN('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
  4190. friend_user_id='.$friend_id;
  4191. $result = Database::query($sql);
  4192. $row = Database::fetch_array($result, 'ASSOC');
  4193. if ($row['count'] == 1) {
  4194. //Delete user rel user
  4195. $sql_i = 'UPDATE '.$tbl_my_friend.' SET relation_type='.USER_RELATION_TYPE_DELETED.'
  4196. WHERE user_id='.$user_id.' AND friend_user_id='.$friend_id;
  4197. $sql_j = 'UPDATE '.$tbl_my_message.' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.'
  4198. WHERE
  4199. user_receiver_id='.$user_id.' AND
  4200. user_sender_id='.$friend_id.' AND update_date="0000-00-00 00:00:00" ';
  4201. // Delete user
  4202. $sql_ij = 'UPDATE '.$tbl_my_friend.' SET relation_type='.USER_RELATION_TYPE_DELETED.'
  4203. WHERE user_id='.$friend_id.' AND friend_user_id='.$user_id;
  4204. $sql_ji = 'UPDATE '.$tbl_my_message.' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.'
  4205. WHERE
  4206. user_receiver_id='.$friend_id.' AND
  4207. user_sender_id='.$user_id.' AND
  4208. update_date="0000-00-00 00:00:00" ';
  4209. Database::query($sql_i);
  4210. Database::query($sql_j);
  4211. Database::query($sql_ij);
  4212. Database::query($sql_ji);
  4213. }
  4214. }
  4215. // Delete accepted invitations
  4216. $sql = "DELETE FROM $tbl_my_message
  4217. WHERE
  4218. msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED." AND
  4219. (
  4220. user_receiver_id = $user_id AND
  4221. user_sender_id = $friend_id
  4222. ) OR
  4223. (
  4224. user_sender_id = $user_id AND
  4225. user_receiver_id = $friend_id
  4226. )
  4227. ";
  4228. Database::query($sql);
  4229. }
  4230. /**
  4231. * @param int $userId
  4232. *
  4233. * @return array
  4234. */
  4235. public static function getDrhListFromUser($userId)
  4236. {
  4237. $tblUser = Database::get_main_table(TABLE_MAIN_USER);
  4238. $tblUserRelUser = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4239. $tblUserRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  4240. $userId = (int) $userId;
  4241. $orderBy = null;
  4242. if (api_is_western_name_order()) {
  4243. $orderBy .= ' ORDER BY firstname, lastname ';
  4244. } else {
  4245. $orderBy .= ' ORDER BY lastname, firstname ';
  4246. }
  4247. $sql = "SELECT u.id, username, u.firstname, u.lastname
  4248. FROM $tblUser u
  4249. INNER JOIN $tblUserRelUser uru ON (uru.friend_user_id = u.id)
  4250. INNER JOIN $tblUserRelAccessUrl a ON (a.user_id = u.id)
  4251. WHERE
  4252. access_url_id = ".api_get_current_access_url_id()." AND
  4253. uru.user_id = '$userId' AND
  4254. relation_type = '".USER_RELATION_TYPE_RRHH."'
  4255. $orderBy
  4256. ";
  4257. $result = Database::query($sql);
  4258. return Database::store_result($result);
  4259. }
  4260. /**
  4261. * get users followed by human resource manager.
  4262. *
  4263. * @param int $userId
  4264. * @param int $userStatus (STUDENT, COURSEMANAGER, etc)
  4265. * @param bool $getOnlyUserId
  4266. * @param bool $getSql
  4267. * @param bool $getCount
  4268. * @param int $from
  4269. * @param int $numberItems
  4270. * @param int $column
  4271. * @param string $direction
  4272. * @param int $active
  4273. * @param string $lastConnectionDate
  4274. *
  4275. * @return array users
  4276. */
  4277. public static function get_users_followed_by_drh(
  4278. $userId,
  4279. $userStatus = 0,
  4280. $getOnlyUserId = false,
  4281. $getSql = false,
  4282. $getCount = false,
  4283. $from = null,
  4284. $numberItems = null,
  4285. $column = null,
  4286. $direction = null,
  4287. $active = null,
  4288. $lastConnectionDate = null
  4289. ) {
  4290. return self::getUsersFollowedByUser(
  4291. $userId,
  4292. $userStatus,
  4293. $getOnlyUserId,
  4294. $getSql,
  4295. $getCount,
  4296. $from,
  4297. $numberItems,
  4298. $column,
  4299. $direction,
  4300. $active,
  4301. $lastConnectionDate,
  4302. DRH
  4303. );
  4304. }
  4305. /**
  4306. * Get users followed by human resource manager.
  4307. *
  4308. * @param int $userId
  4309. * @param int $userStatus Filter users by status (STUDENT, COURSEMANAGER, etc)
  4310. * @param bool $getOnlyUserId
  4311. * @param bool $getSql
  4312. * @param bool $getCount
  4313. * @param int $from
  4314. * @param int $numberItems
  4315. * @param int $column
  4316. * @param string $direction
  4317. * @param int $active
  4318. * @param string $lastConnectionDate
  4319. * @param int $status the function is called by who? COURSEMANAGER, DRH?
  4320. * @param string $keyword
  4321. *
  4322. * @return mixed Users list (array) or the SQL query if $getSQL was set to true
  4323. */
  4324. public static function getUsersFollowedByUser(
  4325. $userId,
  4326. $userStatus = null,
  4327. $getOnlyUserId = false,
  4328. $getSql = false,
  4329. $getCount = false,
  4330. $from = null,
  4331. $numberItems = null,
  4332. $column = null,
  4333. $direction = null,
  4334. $active = null,
  4335. $lastConnectionDate = null,
  4336. $status = null,
  4337. $keyword = null
  4338. ) {
  4339. // Database Table Definitions
  4340. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  4341. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4342. $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  4343. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  4344. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4345. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4346. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  4347. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  4348. $userId = (int) $userId;
  4349. $limitCondition = '';
  4350. if (isset($from) && isset($numberItems)) {
  4351. $from = (int) $from;
  4352. $numberItems = (int) $numberItems;
  4353. $limitCondition = "LIMIT $from, $numberItems";
  4354. }
  4355. $column = Database::escape_string($column);
  4356. $direction = in_array(strtolower($direction), ['asc', 'desc']) ? $direction : null;
  4357. $userConditions = '';
  4358. if (!empty($userStatus)) {
  4359. $userConditions .= ' AND u.status = '.intval($userStatus);
  4360. }
  4361. $select = " SELECT DISTINCT u.id user_id, u.username, u.lastname, u.firstname, u.email ";
  4362. if ($getOnlyUserId) {
  4363. $select = " SELECT DISTINCT u.id user_id";
  4364. }
  4365. $masterSelect = "SELECT DISTINCT * FROM ";
  4366. if ($getCount) {
  4367. $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
  4368. $select = " SELECT DISTINCT(u.id) user_id";
  4369. }
  4370. if (!is_null($active)) {
  4371. $active = intval($active);
  4372. $userConditions .= " AND u.active = $active ";
  4373. }
  4374. if (!empty($keyword)) {
  4375. $keyword = Database::escape_string($keyword);
  4376. $userConditions .= " AND (
  4377. u.username LIKE '%$keyword%' OR
  4378. u.firstname LIKE '%$keyword%' OR
  4379. u.lastname LIKE '%$keyword%' OR
  4380. u.official_code LIKE '%$keyword%' OR
  4381. u.email LIKE '%$keyword%'
  4382. )";
  4383. }
  4384. if (!empty($lastConnectionDate)) {
  4385. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  4386. $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
  4387. }
  4388. $sessionConditionsCoach = null;
  4389. $sessionConditionsTeacher = null;
  4390. $drhConditions = null;
  4391. $teacherSelect = null;
  4392. switch ($status) {
  4393. case DRH:
  4394. $drhConditions .= " AND
  4395. friend_user_id = '$userId' AND
  4396. relation_type = '".USER_RELATION_TYPE_RRHH."'
  4397. ";
  4398. break;
  4399. case COURSEMANAGER:
  4400. $drhConditions .= " AND
  4401. friend_user_id = '$userId' AND
  4402. relation_type = '".USER_RELATION_TYPE_RRHH."'
  4403. ";
  4404. $sessionConditionsCoach .= " AND
  4405. (s.id_coach = '$userId')
  4406. ";
  4407. $sessionConditionsTeacher .= " AND
  4408. (scu.status = 2 AND scu.user_id = '$userId')
  4409. ";
  4410. $teacherSelect =
  4411. "UNION ALL (
  4412. $select
  4413. FROM $tbl_user u
  4414. INNER JOIN $tbl_session_rel_user sru ON (sru.user_id = u.id)
  4415. WHERE
  4416. (
  4417. sru.session_id IN (
  4418. SELECT DISTINCT(s.id) FROM $tbl_session s INNER JOIN
  4419. $tbl_session_rel_access_url session_rel_access_rel_user
  4420. ON session_rel_access_rel_user.session_id = s.id
  4421. WHERE access_url_id = ".api_get_current_access_url_id()."
  4422. $sessionConditionsCoach
  4423. ) OR sru.session_id IN (
  4424. SELECT DISTINCT(s.id) FROM $tbl_session s
  4425. INNER JOIN $tbl_session_rel_access_url url
  4426. ON (url.session_id = s.id)
  4427. INNER JOIN $tbl_session_rel_course_rel_user scu
  4428. ON (scu.session_id = s.id)
  4429. WHERE access_url_id = ".api_get_current_access_url_id()."
  4430. $sessionConditionsTeacher
  4431. )
  4432. )
  4433. $userConditions
  4434. )
  4435. UNION ALL(
  4436. $select
  4437. FROM $tbl_user u
  4438. INNER JOIN $tbl_course_user cu ON (cu.user_id = u.id)
  4439. WHERE cu.c_id IN (
  4440. SELECT DISTINCT(c_id) FROM $tbl_course_user
  4441. WHERE user_id = $userId AND status = ".COURSEMANAGER."
  4442. )
  4443. $userConditions
  4444. )"
  4445. ;
  4446. break;
  4447. case STUDENT_BOSS:
  4448. $drhConditions = " AND friend_user_id = $userId AND relation_type = ".USER_RELATION_TYPE_BOSS;
  4449. break;
  4450. case HRM_REQUEST:
  4451. $drhConditions .= " AND
  4452. friend_user_id = '$userId' AND
  4453. relation_type = '".USER_RELATION_TYPE_HRM_REQUEST."'
  4454. ";
  4455. break;
  4456. }
  4457. $join = null;
  4458. $sql = " $masterSelect
  4459. (
  4460. (
  4461. $select
  4462. FROM $tbl_user u
  4463. INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.id)
  4464. LEFT JOIN $tbl_user_rel_access_url a ON (a.user_id = u.id)
  4465. $join
  4466. WHERE
  4467. access_url_id = ".api_get_current_access_url_id()."
  4468. $drhConditions
  4469. $userConditions
  4470. )
  4471. $teacherSelect
  4472. ) as t1";
  4473. if ($getSql) {
  4474. return $sql;
  4475. }
  4476. if ($getCount) {
  4477. $result = Database::query($sql);
  4478. $row = Database::fetch_array($result);
  4479. return $row['count'];
  4480. }
  4481. $orderBy = null;
  4482. if ($getOnlyUserId == false) {
  4483. if (api_is_western_name_order()) {
  4484. $orderBy .= " ORDER BY firstname, lastname ";
  4485. } else {
  4486. $orderBy .= " ORDER BY lastname, firstname ";
  4487. }
  4488. if (!empty($column) && !empty($direction)) {
  4489. // Fixing order due the UNIONs
  4490. $column = str_replace('u.', '', $column);
  4491. $orderBy = " ORDER BY $column $direction ";
  4492. }
  4493. }
  4494. $sql .= $orderBy;
  4495. $sql .= $limitCondition;
  4496. $result = Database::query($sql);
  4497. $users = [];
  4498. if (Database::num_rows($result) > 0) {
  4499. while ($row = Database::fetch_array($result)) {
  4500. $users[$row['user_id']] = $row;
  4501. }
  4502. }
  4503. return $users;
  4504. }
  4505. /**
  4506. * Subscribes users to human resource manager (Dashboard feature).
  4507. *
  4508. * @param int $hr_dept_id
  4509. * @param array $users_id
  4510. * @param bool $deleteOtherAssignedUsers
  4511. *
  4512. * @return int
  4513. */
  4514. public static function subscribeUsersToHRManager(
  4515. $hr_dept_id,
  4516. $users_id,
  4517. $deleteOtherAssignedUsers = true
  4518. ) {
  4519. return self::subscribeUsersToUser(
  4520. $hr_dept_id,
  4521. $users_id,
  4522. USER_RELATION_TYPE_RRHH,
  4523. false,
  4524. $deleteOtherAssignedUsers
  4525. );
  4526. }
  4527. /**
  4528. * Register request to assign users to HRM.
  4529. *
  4530. * @param int $hrmId The HRM ID
  4531. * @param array $usersId The users IDs
  4532. *
  4533. * @return int
  4534. */
  4535. public static function requestUsersToHRManager($hrmId, $usersId)
  4536. {
  4537. return self::subscribeUsersToUser(
  4538. $hrmId,
  4539. $usersId,
  4540. USER_RELATION_TYPE_HRM_REQUEST,
  4541. false,
  4542. false
  4543. );
  4544. }
  4545. /**
  4546. * Remove the requests for assign a user to a HRM.
  4547. *
  4548. * @param User $hrmId
  4549. * @param array $usersId List of user IDs from whom to remove all relations requests with HRM
  4550. */
  4551. public static function clearHrmRequestsForUser(User $hrmId, $usersId)
  4552. {
  4553. $users = implode(', ', $usersId);
  4554. Database::getManager()
  4555. ->createQuery('
  4556. DELETE FROM ChamiloCoreBundle:UserRelUser uru
  4557. WHERE uru.friendUserId = :hrm_id AND uru.relationType = :relation_type AND uru.userId IN (:users_ids)
  4558. ')
  4559. ->execute(['hrm_id' => $hrmId, 'relation_type' => USER_RELATION_TYPE_HRM_REQUEST, 'users_ids' => $users]);
  4560. }
  4561. /**
  4562. * Add subscribed users to a user by relation type.
  4563. *
  4564. * @param int $userId The user id
  4565. * @param array $subscribedUsersId The id of subscribed users
  4566. * @param string $relationType The relation type
  4567. * @param bool $deleteUsersBeforeInsert
  4568. * @param bool $deleteOtherAssignedUsers
  4569. *
  4570. * @return int
  4571. */
  4572. public static function subscribeUsersToUser(
  4573. $userId,
  4574. $subscribedUsersId,
  4575. $relationType,
  4576. $deleteUsersBeforeInsert = false,
  4577. $deleteOtherAssignedUsers = true
  4578. ) {
  4579. $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4580. $userRelAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  4581. $userId = (int) $userId;
  4582. $relationType = (int) $relationType;
  4583. $affectedRows = 0;
  4584. if ($deleteOtherAssignedUsers) {
  4585. if (api_get_multiple_access_url()) {
  4586. // Deleting assigned users to hrm_id
  4587. $sql = "SELECT s.user_id
  4588. FROM $userRelUserTable s
  4589. INNER JOIN $userRelAccessUrlTable a
  4590. ON (a.user_id = s.user_id)
  4591. WHERE
  4592. friend_user_id = $userId AND
  4593. relation_type = $relationType AND
  4594. access_url_id = ".api_get_current_access_url_id();
  4595. } else {
  4596. $sql = "SELECT user_id
  4597. FROM $userRelUserTable
  4598. WHERE
  4599. friend_user_id = $userId AND
  4600. relation_type = $relationType";
  4601. }
  4602. $result = Database::query($sql);
  4603. if (Database::num_rows($result) > 0) {
  4604. while ($row = Database::fetch_array($result)) {
  4605. $sql = "DELETE FROM $userRelUserTable
  4606. WHERE
  4607. user_id = {$row['user_id']} AND
  4608. friend_user_id = $userId AND
  4609. relation_type = $relationType";
  4610. Database::query($sql);
  4611. }
  4612. }
  4613. }
  4614. if ($deleteUsersBeforeInsert) {
  4615. $sql = "DELETE FROM $userRelUserTable
  4616. WHERE
  4617. user_id = $userId AND
  4618. relation_type = $relationType";
  4619. Database::query($sql);
  4620. }
  4621. // Inserting new user list
  4622. if (is_array($subscribedUsersId)) {
  4623. foreach ($subscribedUsersId as $subscribedUserId) {
  4624. $subscribedUserId = (int) $subscribedUserId;
  4625. $sql = "SELECT id
  4626. FROM $userRelUserTable
  4627. WHERE
  4628. user_id = $subscribedUserId AND
  4629. friend_user_id = $userId AND
  4630. relation_type = $relationType";
  4631. $result = Database::query($sql);
  4632. $num = Database::num_rows($result);
  4633. if ($num === 0) {
  4634. $date = api_get_utc_datetime();
  4635. $sql = "INSERT INTO $userRelUserTable (user_id, friend_user_id, relation_type, last_edit)
  4636. VALUES ($subscribedUserId, $userId, $relationType, '$date')";
  4637. $result = Database::query($sql);
  4638. $affectedRows += Database::affected_rows($result);
  4639. }
  4640. }
  4641. }
  4642. return $affectedRows;
  4643. }
  4644. /**
  4645. * This function check if an user is followed by human resources manager.
  4646. *
  4647. * @param int $user_id
  4648. * @param int $hr_dept_id Human resources manager
  4649. *
  4650. * @return bool
  4651. */
  4652. public static function is_user_followed_by_drh($user_id, $hr_dept_id)
  4653. {
  4654. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4655. $user_id = (int) $user_id;
  4656. $hr_dept_id = (int) $hr_dept_id;
  4657. $result = false;
  4658. $sql = "SELECT user_id FROM $tbl_user_rel_user
  4659. WHERE
  4660. user_id = $user_id AND
  4661. friend_user_id = $hr_dept_id AND
  4662. relation_type = ".USER_RELATION_TYPE_RRHH;
  4663. $rs = Database::query($sql);
  4664. if (Database::num_rows($rs) > 0) {
  4665. $result = true;
  4666. }
  4667. return $result;
  4668. }
  4669. /**
  4670. * Return the user id of teacher or session administrator.
  4671. *
  4672. * @param array $courseInfo
  4673. *
  4674. * @return mixed The user id, or false if the session ID was negative
  4675. */
  4676. public static function get_user_id_of_course_admin_or_session_admin($courseInfo)
  4677. {
  4678. $session = api_get_session_id();
  4679. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  4680. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4681. $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4682. if (empty($courseInfo)) {
  4683. return false;
  4684. }
  4685. $courseId = $courseInfo['real_id'];
  4686. if ($session == 0 || is_null($session)) {
  4687. $sql = 'SELECT u.id uid FROM '.$table_user.' u
  4688. INNER JOIN '.$table_course_user.' ru
  4689. ON ru.user_id = u.id
  4690. WHERE
  4691. ru.status = 1 AND
  4692. ru.c_id = "'.$courseId.'" ';
  4693. $rs = Database::query($sql);
  4694. $num_rows = Database::num_rows($rs);
  4695. if ($num_rows == 1) {
  4696. $row = Database::fetch_array($rs);
  4697. return $row['uid'];
  4698. } else {
  4699. $my_num_rows = $num_rows;
  4700. $my_user_id = Database::result($rs, $my_num_rows - 1, 'uid');
  4701. return $my_user_id;
  4702. }
  4703. } elseif ($session > 0) {
  4704. $sql = 'SELECT u.id uid FROM '.$table_user.' u
  4705. INNER JOIN '.$table_session_course_user.' sru
  4706. ON sru.user_id=u.id
  4707. WHERE
  4708. sru.c_id="'.$courseId.'" AND
  4709. sru.status=2';
  4710. $rs = Database::query($sql);
  4711. $row = Database::fetch_array($rs);
  4712. return $row['uid'];
  4713. }
  4714. return false;
  4715. }
  4716. /**
  4717. * Determines if a user is a gradebook certified.
  4718. *
  4719. * @param int $cat_id The category id of gradebook
  4720. * @param int $user_id The user id
  4721. *
  4722. * @return bool
  4723. */
  4724. public static function is_user_certified($cat_id, $user_id)
  4725. {
  4726. $cat_id = (int) $cat_id;
  4727. $user_id = (int) $user_id;
  4728. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  4729. $sql = 'SELECT path_certificate
  4730. FROM '.$table.'
  4731. WHERE
  4732. cat_id = "'.$cat_id.'" AND
  4733. user_id = "'.$user_id.'"';
  4734. $rs = Database::query($sql);
  4735. $row = Database::fetch_array($rs);
  4736. if ($row['path_certificate'] == '' || is_null($row['path_certificate'])) {
  4737. return false;
  4738. }
  4739. return true;
  4740. }
  4741. /**
  4742. * Gets the info about a gradebook certificate for a user by course.
  4743. *
  4744. * @param string $course_code The course code
  4745. * @param int $user_id The user id
  4746. *
  4747. * @return array if there is not information return false
  4748. */
  4749. public static function get_info_gradebook_certificate($course_code, $user_id)
  4750. {
  4751. $tbl_grade_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  4752. $tbl_grade_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  4753. $session_id = api_get_session_id();
  4754. if (empty($session_id)) {
  4755. $session_condition = ' AND (session_id = "" OR session_id = 0 OR session_id IS NULL )';
  4756. } else {
  4757. $session_condition = " AND session_id = $session_id";
  4758. }
  4759. $sql = 'SELECT * FROM '.$tbl_grade_certificate.'
  4760. WHERE cat_id = (
  4761. SELECT id FROM '.$tbl_grade_category.'
  4762. WHERE
  4763. course_code = "'.Database::escape_string($course_code).'" '.$session_condition.'
  4764. LIMIT 1
  4765. ) AND user_id='.intval($user_id);
  4766. $rs = Database::query($sql);
  4767. if (Database::num_rows($rs) > 0) {
  4768. $row = Database::fetch_array($rs, 'ASSOC');
  4769. $score = $row['score_certificate'];
  4770. $category_id = $row['cat_id'];
  4771. $cat = Category::load($category_id);
  4772. $displayscore = ScoreDisplay::instance();
  4773. if (isset($cat) && $displayscore->is_custom()) {
  4774. $grade = $displayscore->display_score(
  4775. [$score, $cat[0]->get_weight()],
  4776. SCORE_DIV_PERCENT_WITH_CUSTOM
  4777. );
  4778. } else {
  4779. $grade = $displayscore->display_score(
  4780. [$score, $cat[0]->get_weight()]
  4781. );
  4782. }
  4783. $row['grade'] = $grade;
  4784. return $row;
  4785. }
  4786. return false;
  4787. }
  4788. /**
  4789. * This function check if the user is a coach inside session course.
  4790. *
  4791. * @param int $user_id User id
  4792. * @param int $courseId
  4793. * @param int $session_id
  4794. *
  4795. * @return bool True if the user is a coach
  4796. */
  4797. public static function is_session_course_coach($user_id, $courseId, $session_id)
  4798. {
  4799. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4800. // Protect data
  4801. $user_id = intval($user_id);
  4802. $courseId = intval($courseId);
  4803. $session_id = intval($session_id);
  4804. $result = false;
  4805. $sql = "SELECT session_id FROM $table
  4806. WHERE
  4807. session_id = $session_id AND
  4808. c_id = $courseId AND
  4809. user_id = $user_id AND
  4810. status = 2 ";
  4811. $res = Database::query($sql);
  4812. if (Database::num_rows($res) > 0) {
  4813. $result = true;
  4814. }
  4815. return $result;
  4816. }
  4817. /**
  4818. * This function returns an icon path that represents the favicon of the website of which the url given.
  4819. * Defaults to the current Chamilo favicon.
  4820. *
  4821. * @param string $url1 URL of website where to look for favicon.ico
  4822. * @param string $url2 Optional second URL of website where to look for favicon.ico
  4823. *
  4824. * @return string Path of icon to load
  4825. */
  4826. public static function get_favicon_from_url($url1, $url2 = null)
  4827. {
  4828. $icon_link = '';
  4829. $url = $url1;
  4830. if (empty($url1)) {
  4831. $url = $url2;
  4832. if (empty($url)) {
  4833. $url = api_get_access_url(api_get_current_access_url_id());
  4834. $url = $url[0];
  4835. }
  4836. }
  4837. if (!empty($url)) {
  4838. $pieces = parse_url($url);
  4839. $icon_link = $pieces['scheme'].'://'.$pieces['host'].'/favicon.ico';
  4840. }
  4841. return $icon_link;
  4842. }
  4843. /**
  4844. * @param User $user
  4845. */
  4846. public static function add_user_as_admin(User $user)
  4847. {
  4848. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  4849. if ($user) {
  4850. $userId = $user->getId();
  4851. if (!self::is_admin($userId)) {
  4852. $sql = "INSERT INTO $table_admin SET user_id = $userId";
  4853. Database::query($sql);
  4854. }
  4855. $user->addRole('ROLE_SUPER_ADMIN');
  4856. self::getManager()->updateUser($user, true);
  4857. }
  4858. }
  4859. /**
  4860. * @param int $userId
  4861. */
  4862. public static function remove_user_admin($userId)
  4863. {
  4864. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  4865. $userId = (int) $userId;
  4866. if (self::is_admin($userId)) {
  4867. $sql = "DELETE FROM $table_admin WHERE user_id = $userId";
  4868. Database::query($sql);
  4869. }
  4870. }
  4871. /**
  4872. * @param string $from
  4873. * @param string $to
  4874. */
  4875. public static function update_all_user_languages($from, $to)
  4876. {
  4877. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  4878. $from = Database::escape_string($from);
  4879. $to = Database::escape_string($to);
  4880. if (!empty($to) && !empty($from)) {
  4881. $sql = "UPDATE $table_user SET language = '$to'
  4882. WHERE language = '$from'";
  4883. Database::query($sql);
  4884. }
  4885. }
  4886. /**
  4887. * Subscribe boss to students.
  4888. *
  4889. * @param int $bossId The boss id
  4890. * @param array $usersId The users array
  4891. *
  4892. * @return int Affected rows
  4893. */
  4894. public static function subscribeBossToUsers($bossId, $usersId)
  4895. {
  4896. return self::subscribeUsersToUser(
  4897. $bossId,
  4898. $usersId,
  4899. USER_RELATION_TYPE_BOSS
  4900. );
  4901. }
  4902. /**
  4903. * @param int $userId
  4904. *
  4905. * @return bool
  4906. */
  4907. public static function removeAllBossFromStudent($userId)
  4908. {
  4909. $userId = (int) $userId;
  4910. if (empty($userId)) {
  4911. return false;
  4912. }
  4913. $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4914. $sql = "DELETE FROM $userRelUserTable
  4915. WHERE user_id = $userId AND relation_type = ".USER_RELATION_TYPE_BOSS;
  4916. Database::query($sql);
  4917. return true;
  4918. }
  4919. /**
  4920. * Subscribe boss to students, if $bossList is empty then the boss list will be empty too.
  4921. *
  4922. * @param int $studentId
  4923. * @param array $bossList
  4924. * @param bool $sendNotification
  4925. *
  4926. * @return mixed Affected rows or false on failure
  4927. */
  4928. public static function subscribeUserToBossList(
  4929. $studentId,
  4930. $bossList,
  4931. $sendNotification = false
  4932. ) {
  4933. $inserted = 0;
  4934. if (!empty($bossList)) {
  4935. sort($bossList);
  4936. $studentId = (int) $studentId;
  4937. $studentInfo = api_get_user_info($studentId);
  4938. if (empty($studentInfo)) {
  4939. return false;
  4940. }
  4941. $previousBossList = self::getStudentBossList($studentId);
  4942. $previousBossList = !empty($previousBossList) ? array_column($previousBossList, 'boss_id') : [];
  4943. sort($previousBossList);
  4944. // Boss list is the same, nothing changed.
  4945. if ($bossList == $previousBossList) {
  4946. return false;
  4947. }
  4948. $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4949. self::removeAllBossFromStudent($studentId);
  4950. foreach ($bossList as $bossId) {
  4951. $bossId = (int) $bossId;
  4952. $sql = "INSERT IGNORE INTO $userRelUserTable (user_id, friend_user_id, relation_type)
  4953. VALUES ($studentId, $bossId, ".USER_RELATION_TYPE_BOSS.")";
  4954. $insertId = Database::query($sql);
  4955. if ($insertId) {
  4956. if ($sendNotification) {
  4957. $name = $studentInfo['complete_name'];
  4958. $url = api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$studentId;
  4959. $url = Display::url($url, $url);
  4960. $subject = sprintf(get_lang('UserXHasBeenAssignedToBoss'), $name);
  4961. $message = sprintf(get_lang('UserXHasBeenAssignedToBossWithUrlX'), $name, $url);
  4962. MessageManager::send_message_simple(
  4963. $bossId,
  4964. $subject,
  4965. $message
  4966. );
  4967. }
  4968. $inserted++;
  4969. }
  4970. }
  4971. } else {
  4972. self::removeAllBossFromStudent($studentId);
  4973. }
  4974. return $inserted;
  4975. }
  4976. /**
  4977. * Get users followed by student boss.
  4978. *
  4979. * @param int $userId
  4980. * @param int $userStatus (STUDENT, COURSEMANAGER, etc)
  4981. * @param bool $getOnlyUserId
  4982. * @param bool $getSql
  4983. * @param bool $getCount
  4984. * @param int $from
  4985. * @param int $numberItems
  4986. * @param int $column
  4987. * @param string $direction
  4988. * @param int $active
  4989. * @param string $lastConnectionDate
  4990. *
  4991. * @return array users
  4992. */
  4993. public static function getUsersFollowedByStudentBoss(
  4994. $userId,
  4995. $userStatus = 0,
  4996. $getOnlyUserId = false,
  4997. $getSql = false,
  4998. $getCount = false,
  4999. $from = null,
  5000. $numberItems = null,
  5001. $column = null,
  5002. $direction = null,
  5003. $active = null,
  5004. $lastConnectionDate = null
  5005. ) {
  5006. return self::getUsersFollowedByUser(
  5007. $userId,
  5008. $userStatus,
  5009. $getOnlyUserId,
  5010. $getSql,
  5011. $getCount,
  5012. $from,
  5013. $numberItems,
  5014. $column,
  5015. $direction,
  5016. $active,
  5017. $lastConnectionDate,
  5018. STUDENT_BOSS
  5019. );
  5020. }
  5021. /**
  5022. * @return array
  5023. */
  5024. public static function getOfficialCodeGrouped()
  5025. {
  5026. $user = Database::get_main_table(TABLE_MAIN_USER);
  5027. $sql = "SELECT DISTINCT official_code
  5028. FROM $user
  5029. GROUP BY official_code";
  5030. $result = Database::query($sql);
  5031. $values = Database::store_result($result, 'ASSOC');
  5032. $result = [];
  5033. foreach ($values as $value) {
  5034. $result[$value['official_code']] = $value['official_code'];
  5035. }
  5036. return $result;
  5037. }
  5038. /**
  5039. * @param string $officialCode
  5040. *
  5041. * @return array
  5042. */
  5043. public static function getUsersByOfficialCode($officialCode)
  5044. {
  5045. $user = Database::get_main_table(TABLE_MAIN_USER);
  5046. $officialCode = Database::escape_string($officialCode);
  5047. $sql = "SELECT DISTINCT id
  5048. FROM $user
  5049. WHERE official_code = '$officialCode'
  5050. ";
  5051. $result = Database::query($sql);
  5052. $users = [];
  5053. while ($row = Database::fetch_array($result)) {
  5054. $users[] = $row['id'];
  5055. }
  5056. return $users;
  5057. }
  5058. /**
  5059. * Calc the expended time (in seconds) by a user in a course.
  5060. *
  5061. * @param int $userId The user id
  5062. * @param int $courseId The course id
  5063. * @param int $sessionId Optional. The session id
  5064. * @param string $from Optional. From date
  5065. * @param string $until Optional. Until date
  5066. *
  5067. * @return int The time
  5068. */
  5069. public static function getTimeSpentInCourses(
  5070. $userId,
  5071. $courseId,
  5072. $sessionId = 0,
  5073. $from = '',
  5074. $until = ''
  5075. ) {
  5076. $userId = (int) $userId;
  5077. $sessionId = (int) $sessionId;
  5078. $trackCourseAccessTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  5079. $whereConditions = [
  5080. 'user_id = ? ' => $userId,
  5081. 'AND c_id = ? ' => $courseId,
  5082. 'AND session_id = ? ' => $sessionId,
  5083. ];
  5084. if (!empty($from) && !empty($until)) {
  5085. $whereConditions["AND (login_course_date >= '?' "] = $from;
  5086. $whereConditions["AND logout_course_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
  5087. }
  5088. $trackResult = Database::select(
  5089. 'SUM(UNIX_TIMESTAMP(logout_course_date) - UNIX_TIMESTAMP(login_course_date)) as total_time',
  5090. $trackCourseAccessTable,
  5091. [
  5092. 'where' => $whereConditions,
  5093. ],
  5094. 'first'
  5095. );
  5096. if ($trackResult != false) {
  5097. return $trackResult['total_time'] ? $trackResult['total_time'] : 0;
  5098. }
  5099. return 0;
  5100. }
  5101. /**
  5102. * Get the boss user ID from a followed user id.
  5103. *
  5104. * @param $userId
  5105. *
  5106. * @return bool
  5107. */
  5108. public static function getFirstStudentBoss($userId)
  5109. {
  5110. $userId = (int) $userId;
  5111. if ($userId > 0) {
  5112. $userRelTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  5113. $row = Database::select(
  5114. 'DISTINCT friend_user_id AS boss_id',
  5115. $userRelTable,
  5116. [
  5117. 'where' => [
  5118. 'user_id = ? AND relation_type = ? LIMIT 1' => [
  5119. $userId,
  5120. USER_RELATION_TYPE_BOSS,
  5121. ],
  5122. ],
  5123. ]
  5124. );
  5125. if (!empty($row)) {
  5126. return $row[0]['boss_id'];
  5127. }
  5128. }
  5129. return false;
  5130. }
  5131. /**
  5132. * Get the boss user ID from a followed user id.
  5133. *
  5134. * @param int $userId student id
  5135. *
  5136. * @return array
  5137. */
  5138. public static function getStudentBossList($userId)
  5139. {
  5140. $userId = (int) $userId;
  5141. if ($userId > 0) {
  5142. $userRelTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  5143. $result = Database::select(
  5144. 'DISTINCT friend_user_id AS boss_id',
  5145. $userRelTable,
  5146. [
  5147. 'where' => [
  5148. 'user_id = ? AND relation_type = ? ' => [
  5149. $userId,
  5150. USER_RELATION_TYPE_BOSS,
  5151. ],
  5152. ],
  5153. ]
  5154. );
  5155. return $result;
  5156. }
  5157. return [];
  5158. }
  5159. /**
  5160. * @param int $bossId
  5161. * @param int $studentId
  5162. *
  5163. * @return bool
  5164. */
  5165. public static function userIsBossOfStudent($bossId, $studentId)
  5166. {
  5167. $result = false;
  5168. $bossList = self::getStudentBossList($studentId);
  5169. if (!empty($bossList)) {
  5170. $bossList = array_column($bossList, 'boss_id');
  5171. if (in_array($bossId, $bossList)) {
  5172. $result = true;
  5173. }
  5174. }
  5175. return $result;
  5176. }
  5177. /**
  5178. * Displays the name of the user and makes the link to the user profile.
  5179. *
  5180. * @param array $userInfo
  5181. *
  5182. * @return string
  5183. */
  5184. public static function getUserProfileLink($userInfo)
  5185. {
  5186. if (isset($userInfo) && isset($userInfo['user_id'])) {
  5187. return Display::url(
  5188. $userInfo['complete_name_with_username'],
  5189. $userInfo['profile_url']
  5190. );
  5191. }
  5192. return get_lang('Anonymous');
  5193. }
  5194. /**
  5195. * Get users whose name matches $firstname and $lastname.
  5196. *
  5197. * @param string $firstname Firstname to search
  5198. * @param string $lastname Lastname to search
  5199. *
  5200. * @return array The user list
  5201. */
  5202. public static function getUsersByName($firstname, $lastname)
  5203. {
  5204. $firstname = Database::escape_string($firstname);
  5205. $lastname = Database::escape_string($lastname);
  5206. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  5207. $sql = <<<SQL
  5208. SELECT id, username, lastname, firstname
  5209. FROM $userTable
  5210. WHERE
  5211. firstname LIKE '$firstname%' AND
  5212. lastname LIKE '$lastname%'
  5213. SQL;
  5214. $result = Database::query($sql);
  5215. $users = [];
  5216. while ($resultData = Database::fetch_object($result)) {
  5217. $users[] = $resultData;
  5218. }
  5219. return $users;
  5220. }
  5221. /**
  5222. * @param int $optionSelected
  5223. *
  5224. * @return string
  5225. */
  5226. public static function getUserSubscriptionTab($optionSelected = 1)
  5227. {
  5228. $allowAdmin = api_get_setting('allow_user_course_subscription_by_course_admin');
  5229. if (($allowAdmin === 'true' && api_is_allowed_to_edit()) ||
  5230. api_is_platform_admin()
  5231. ) {
  5232. $userPath = api_get_path(WEB_CODE_PATH).'user/';
  5233. $headers = [
  5234. [
  5235. 'url' => $userPath.'user.php?'.api_get_cidreq().'&type='.STUDENT,
  5236. 'content' => get_lang('Students'),
  5237. ],
  5238. [
  5239. 'url' => $userPath.'user.php?'.api_get_cidreq().'&type='.COURSEMANAGER,
  5240. 'content' => get_lang('Teachers'),
  5241. ],
  5242. /*[
  5243. 'url' => $userPath.'subscribe_user.php?'.api_get_cidreq(),
  5244. 'content' => get_lang('Students'),
  5245. ],
  5246. [
  5247. 'url' => $userPath.'subscribe_user.php?type=teacher&'.api_get_cidreq(),
  5248. 'content' => get_lang('Teachers'),
  5249. ],*/
  5250. [
  5251. 'url' => api_get_path(WEB_CODE_PATH).'group/group.php?'.api_get_cidreq(),
  5252. 'content' => get_lang('Groups'),
  5253. ],
  5254. [
  5255. 'url' => $userPath.'class.php?'.api_get_cidreq(),
  5256. 'content' => get_lang('Classes'),
  5257. ],
  5258. ];
  5259. return Display::tabsOnlyLink($headers, $optionSelected);
  5260. }
  5261. return '';
  5262. }
  5263. /**
  5264. * Make sure this function is protected because it does NOT check password!
  5265. *
  5266. * This function defines globals.
  5267. *
  5268. * @param int $userId
  5269. * @param bool $checkIfUserCanLoginAs
  5270. *
  5271. * @return bool
  5272. *
  5273. * @author Evie Embrechts
  5274. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  5275. */
  5276. public static function loginAsUser($userId, $checkIfUserCanLoginAs = true)
  5277. {
  5278. $userId = (int) $userId;
  5279. $userInfo = api_get_user_info($userId);
  5280. // Check if the user is allowed to 'login_as'
  5281. $canLoginAs = true;
  5282. if ($checkIfUserCanLoginAs) {
  5283. $canLoginAs = api_can_login_as($userId);
  5284. }
  5285. if (!$canLoginAs || empty($userInfo)) {
  5286. return false;
  5287. }
  5288. if ($userId) {
  5289. $logInfo = [
  5290. 'tool' => 'logout',
  5291. 'tool_id' => 0,
  5292. 'tool_id_detail' => 0,
  5293. 'action' => '',
  5294. 'info' => 'Change user (login as)',
  5295. ];
  5296. Event::registerLog($logInfo);
  5297. // Logout the current user
  5298. self::loginDelete(api_get_user_id());
  5299. Session::erase('_user');
  5300. Session::erase('is_platformAdmin');
  5301. Session::erase('is_allowedCreateCourse');
  5302. Session::erase('_uid');
  5303. // Cleaning session variables
  5304. $_user['firstName'] = $userInfo['firstname'];
  5305. $_user['lastName'] = $userInfo['lastname'];
  5306. $_user['mail'] = $userInfo['email'];
  5307. $_user['official_code'] = $userInfo['official_code'];
  5308. $_user['picture_uri'] = $userInfo['picture_uri'];
  5309. $_user['user_id'] = $userId;
  5310. $_user['id'] = $userId;
  5311. $_user['status'] = $userInfo['status'];
  5312. // Filling session variables with new data
  5313. Session::write('_uid', $userId);
  5314. Session::write('_user', $userInfo);
  5315. Session::write('is_platformAdmin', (bool) self::is_admin($userId));
  5316. Session::write('is_allowedCreateCourse', $userInfo['status'] == 1);
  5317. // will be useful later to know if the user is actually an admin or not (example reporting)
  5318. Session::write('login_as', true);
  5319. $logInfo = [
  5320. 'tool' => 'login',
  5321. 'tool_id' => 0,
  5322. 'tool_id_detail' => 0,
  5323. 'info' => $userId,
  5324. ];
  5325. Event::registerLog($logInfo);
  5326. return true;
  5327. }
  5328. return false;
  5329. }
  5330. /**
  5331. * Remove all login records from the track_e_online stats table,
  5332. * for the given user ID.
  5333. *
  5334. * @param int $userId User ID
  5335. */
  5336. public static function loginDelete($userId)
  5337. {
  5338. $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
  5339. $userId = (int) $userId;
  5340. $query = "DELETE FROM $online_table WHERE login_user_id = $userId";
  5341. Database::query($query);
  5342. }
  5343. /**
  5344. * Login as first admin user registered in the platform.
  5345. *
  5346. * @return array
  5347. */
  5348. public static function logInAsFirstAdmin()
  5349. {
  5350. $adminList = self::get_all_administrators();
  5351. if (!empty($adminList)) {
  5352. $userInfo = current($adminList);
  5353. if (!empty($userInfo)) {
  5354. $result = self::loginAsUser($userInfo['user_id'], false);
  5355. if ($result && api_is_platform_admin()) {
  5356. return api_get_user_info();
  5357. }
  5358. }
  5359. }
  5360. return [];
  5361. }
  5362. /**
  5363. * Check if user is teacher of a student based in their courses.
  5364. *
  5365. * @param $teacherId
  5366. * @param $studentId
  5367. *
  5368. * @return array
  5369. */
  5370. public static function getCommonCoursesBetweenTeacherAndStudent($teacherId, $studentId)
  5371. {
  5372. $courses = CourseManager::getCoursesFollowedByUser(
  5373. $teacherId,
  5374. COURSEMANAGER
  5375. );
  5376. if (empty($courses)) {
  5377. return false;
  5378. }
  5379. $coursesFromUser = CourseManager::get_courses_list_by_user_id($studentId);
  5380. if (empty($coursesFromUser)) {
  5381. return false;
  5382. }
  5383. $coursesCodeList = array_column($courses, 'code');
  5384. $coursesCodeFromUserList = array_column($coursesFromUser, 'code');
  5385. $commonCourses = array_intersect($coursesCodeList, $coursesCodeFromUserList);
  5386. $commonCourses = array_filter($commonCourses);
  5387. if (!empty($commonCourses)) {
  5388. return $commonCourses;
  5389. }
  5390. return [];
  5391. }
  5392. /**
  5393. * @param int $teacherId
  5394. * @param int $studentId
  5395. *
  5396. * @return bool
  5397. */
  5398. public static function isTeacherOfStudent($teacherId, $studentId)
  5399. {
  5400. $courses = self::getCommonCoursesBetweenTeacherAndStudent(
  5401. $teacherId,
  5402. $studentId
  5403. );
  5404. if (!empty($courses)) {
  5405. return true;
  5406. }
  5407. return false;
  5408. }
  5409. /**
  5410. * Send user confirmation mail.
  5411. *
  5412. * @param User $user
  5413. *
  5414. * @throws Exception
  5415. */
  5416. public static function sendUserConfirmationMail(User $user)
  5417. {
  5418. $uniqueId = api_get_unique_id();
  5419. $user->setConfirmationToken($uniqueId);
  5420. Database::getManager()->persist($user);
  5421. Database::getManager()->flush();
  5422. $url = api_get_path(WEB_CODE_PATH).'auth/user_mail_confirmation.php?token='.$uniqueId;
  5423. // Check if the user was originally set for an automated subscription to a course or session
  5424. $courseCodeToRedirect = Session::read('course_redirect');
  5425. $sessionToRedirect = Session::read('session_redirect');
  5426. if (!empty($courseCodeToRedirect)) {
  5427. $url .= '&c='.$courseCodeToRedirect;
  5428. }
  5429. if (!empty($sessionToRedirect)) {
  5430. $url .= '&s='.$sessionToRedirect;
  5431. }
  5432. $mailSubject = get_lang('RegistrationConfirmation');
  5433. $mailBody = get_lang('RegistrationConfirmationEmailMessage')
  5434. .PHP_EOL
  5435. .Display::url($url, $url);
  5436. api_mail_html(
  5437. self::formatUserFullName($user),
  5438. $user->getEmail(),
  5439. $mailSubject,
  5440. $mailBody
  5441. );
  5442. Display::addFlash(Display::return_message(get_lang('CheckYourEmailAndFollowInstructions')));
  5443. }
  5444. /**
  5445. * Anonymize a user. Replace personal info by anonymous info.
  5446. *
  5447. * @param int $userId User id
  5448. * @param bool $deleteIP Whether to replace the IP address in logs tables by 127.0.0.1 or to leave as is
  5449. *
  5450. * @throws \Exception
  5451. *
  5452. * @return bool
  5453. * @assert (0) === false
  5454. */
  5455. public static function anonymize($userId, $deleteIP = true)
  5456. {
  5457. global $debug;
  5458. $userId = (int) $userId;
  5459. if (empty($userId)) {
  5460. return false;
  5461. }
  5462. $em = Database::getManager();
  5463. $user = api_get_user_entity($userId);
  5464. $uniqueId = uniqid('anon', true);
  5465. $user
  5466. ->setFirstname($uniqueId)
  5467. ->setLastname($uniqueId)
  5468. ->setBiography('')
  5469. ->setAddress('')
  5470. ->setCurriculumItems(null)
  5471. ->setDateOfBirth(null)
  5472. ->setCompetences('')
  5473. ->setDiplomas('')
  5474. ->setOpenarea('')
  5475. ->setTeach('')
  5476. ->setProductions(null)
  5477. ->setOpenid('')
  5478. ->setEmailCanonical($uniqueId.'@example.com')
  5479. ->setEmail($uniqueId.'@example.com')
  5480. ->setUsername($uniqueId)
  5481. ->setUsernameCanonical($uniqueId)
  5482. ->setPhone('')
  5483. ->setOfficialCode('')
  5484. ;
  5485. self::deleteUserPicture($userId);
  5486. self::cleanUserRequestsOfRemoval($userId);
  5487. // The IP address is a border-case personal data, as it does
  5488. // not directly allow for personal identification (it is not
  5489. // a completely safe value in most countries - the IP could
  5490. // be used by neighbours and crackers)
  5491. if ($deleteIP) {
  5492. $substitute = '127.0.0.1';
  5493. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  5494. $sql = "UPDATE $table set user_ip = '$substitute' WHERE access_user_id = $userId";
  5495. $res = Database::query($sql);
  5496. if ($res === false && $debug > 0) {
  5497. error_log("Could not anonymize IP address for user $userId ($sql)");
  5498. }
  5499. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  5500. $sql = "UPDATE $table set user_ip = '$substitute' WHERE user_id = $userId";
  5501. $res = Database::query($sql);
  5502. if ($res === false && $debug > 0) {
  5503. error_log("Could not anonymize IP address for user $userId ($sql)");
  5504. }
  5505. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  5506. $sql = "UPDATE $table set user_ip = '$substitute' WHERE exe_user_id = $userId";
  5507. $res = Database::query($sql);
  5508. if ($res === false && $debug > 0) {
  5509. error_log("Could not anonymize IP address for user $userId ($sql)");
  5510. }
  5511. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  5512. $sql = "UPDATE $table set user_ip = '$substitute' WHERE login_user_id = $userId";
  5513. $res = Database::query($sql);
  5514. if ($res === false && $debug > 0) {
  5515. error_log("Could not anonymize IP address for user $userId ($sql)");
  5516. }
  5517. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
  5518. $sql = "UPDATE $table set user_ip = '$substitute' WHERE login_user_id = $userId";
  5519. $res = Database::query($sql);
  5520. if ($res === false && $debug > 0) {
  5521. error_log("Could not anonymize IP address for user $userId ($sql)");
  5522. }
  5523. $table = Database::get_course_table(TABLE_WIKI);
  5524. $sql = "UPDATE $table set user_ip = '$substitute' WHERE user_id = $userId";
  5525. $res = Database::query($sql);
  5526. if ($res === false && $debug > 0) {
  5527. error_log("Could not anonymize IP address for user $userId ($sql)");
  5528. }
  5529. $table = Database::get_main_table(TABLE_TICKET_MESSAGE);
  5530. $sql = "UPDATE $table set ip_address = '$substitute' WHERE sys_insert_user_id = $userId";
  5531. $res = Database::query($sql);
  5532. if ($res === false && $debug > 0) {
  5533. error_log("Could not anonymize IP address for user $userId ($sql)");
  5534. }
  5535. $table = Database::get_course_table(TABLE_WIKI);
  5536. $sql = "UPDATE $table set user_ip = '$substitute' WHERE user_id = $userId";
  5537. $res = Database::query($sql);
  5538. if ($res === false && $debug > 0) {
  5539. error_log("Could not anonymize IP address for user $userId ($sql)");
  5540. }
  5541. }
  5542. $em->persist($user);
  5543. $em->flush($user);
  5544. Event::addEvent(LOG_USER_ANONYMIZE, LOG_USER_ID, $userId);
  5545. return true;
  5546. }
  5547. /**
  5548. * @param int $userId
  5549. *
  5550. * @throws Exception
  5551. *
  5552. * @return string
  5553. */
  5554. public static function anonymizeUserWithVerification($userId)
  5555. {
  5556. $allowDelete = api_get_configuration_value('allow_delete_user_for_session_admin');
  5557. $message = '';
  5558. if (api_is_platform_admin() ||
  5559. ($allowDelete && api_is_session_admin())
  5560. ) {
  5561. $userToUpdateInfo = api_get_user_info($userId);
  5562. $currentUserId = api_get_user_id();
  5563. if ($userToUpdateInfo &&
  5564. api_global_admin_can_edit_admin($userId, null, $allowDelete)
  5565. ) {
  5566. if ($userId != $currentUserId &&
  5567. self::anonymize($userId)
  5568. ) {
  5569. $message = Display::return_message(
  5570. sprintf(get_lang('UserXAnonymized'), $userToUpdateInfo['complete_name_with_username']),
  5571. 'confirmation'
  5572. );
  5573. } else {
  5574. $message = Display::return_message(
  5575. sprintf(get_lang('CannotAnonymizeUserX'), $userToUpdateInfo['complete_name_with_username']),
  5576. 'error'
  5577. );
  5578. }
  5579. } else {
  5580. $message = Display::return_message(
  5581. sprintf(get_lang('NoPermissionToAnonymizeUserX'), $userToUpdateInfo['complete_name_with_username']),
  5582. 'error'
  5583. );
  5584. }
  5585. }
  5586. return $message;
  5587. }
  5588. /**
  5589. * @param int $userId
  5590. *
  5591. * @throws Exception
  5592. *
  5593. * @return string
  5594. */
  5595. public static function deleteUserWithVerification($userId)
  5596. {
  5597. $allowDelete = api_get_configuration_value('allow_delete_user_for_session_admin');
  5598. $message = Display::return_message(get_lang('CannotDeleteUser'), 'error');
  5599. $userToUpdateInfo = api_get_user_info($userId);
  5600. // User must exist.
  5601. if (empty($userToUpdateInfo)) {
  5602. return $message;
  5603. }
  5604. $currentUserId = api_get_user_id();
  5605. // Cannot delete myself.
  5606. if ($userId == $currentUserId) {
  5607. return $message;
  5608. }
  5609. if (api_is_platform_admin() ||
  5610. ($allowDelete && api_is_session_admin())
  5611. ) {
  5612. if (api_global_admin_can_edit_admin($userId, null, $allowDelete)) {
  5613. if (self::delete_user($userId)) {
  5614. $message = Display::return_message(
  5615. get_lang('UserDeleted').': '.$userToUpdateInfo['complete_name_with_username'],
  5616. 'confirmation'
  5617. );
  5618. } else {
  5619. $message = Display::return_message(get_lang('CannotDeleteUserBecauseOwnsCourse'), 'error');
  5620. }
  5621. }
  5622. }
  5623. return $message;
  5624. }
  5625. /**
  5626. * @return array
  5627. */
  5628. public static function createDataPrivacyExtraFields()
  5629. {
  5630. self::create_extra_field(
  5631. 'request_for_legal_agreement_consent_removal_justification',
  5632. 1, //text
  5633. 'Request for legal agreement consent removal justification ',
  5634. ''
  5635. );
  5636. self::create_extra_field(
  5637. 'request_for_delete_account_justification',
  5638. 1, //text
  5639. 'Request for delete account justification',
  5640. ''
  5641. );
  5642. $extraFieldId = self::create_extra_field(
  5643. 'request_for_legal_agreement_consent_removal',
  5644. 1, //text
  5645. 'Request for legal agreement consent removal',
  5646. ''
  5647. );
  5648. $extraFieldIdDeleteAccount = self::create_extra_field(
  5649. 'request_for_delete_account',
  5650. 1, //text
  5651. 'Request for delete user account',
  5652. ''
  5653. );
  5654. return [
  5655. 'delete_account_extra_field' => $extraFieldIdDeleteAccount,
  5656. 'delete_legal' => $extraFieldId,
  5657. ];
  5658. }
  5659. /**
  5660. * @param int $userId
  5661. */
  5662. public static function cleanUserRequestsOfRemoval($userId)
  5663. {
  5664. $userId = (int) $userId;
  5665. $extraFieldValue = new ExtraFieldValue('user');
  5666. $extraFieldsToDelete = [
  5667. 'legal_accept',
  5668. 'request_for_legal_agreement_consent_removal',
  5669. 'request_for_legal_agreement_consent_removal_justification',
  5670. 'request_for_delete_account_justification', // just in case delete also this
  5671. 'request_for_delete_account',
  5672. ];
  5673. foreach ($extraFieldsToDelete as $variable) {
  5674. $value = $extraFieldValue->get_values_by_handler_and_field_variable(
  5675. $userId,
  5676. $variable
  5677. );
  5678. if ($value && isset($value['id'])) {
  5679. $extraFieldValue->delete($value['id']);
  5680. }
  5681. }
  5682. }
  5683. /**
  5684. * @param array $userInfo
  5685. * @param int $searchYear
  5686. *
  5687. * @throws Exception
  5688. *
  5689. * @return array
  5690. */
  5691. public static function getSubscribedSessionsByYear(array $userInfo, $searchYear)
  5692. {
  5693. $timezone = new DateTimeZone(api_get_timezone());
  5694. $sessions = [];
  5695. if (DRH == $userInfo['status']) {
  5696. $sessions = SessionManager::get_sessions_followed_by_drh($userInfo['id']);
  5697. } elseif (api_is_platform_admin(true)) {
  5698. $sessions = SessionManager::getSessionsForAdmin($userInfo['id']);
  5699. } else {
  5700. $sessionsByCategory = self::get_sessions_by_category($userInfo['id'], false, true, true);
  5701. $sessionsByCategory = array_column($sessionsByCategory, 'sessions');
  5702. foreach ($sessionsByCategory as $sessionsInCategory) {
  5703. $sessions = array_merge($sessions, $sessionsInCategory);
  5704. }
  5705. }
  5706. $sessions = array_map(
  5707. function ($sessionInfo) {
  5708. if (!isset($sessionInfo['session_id'])) {
  5709. $sessionInfo['session_id'] = $sessionInfo['id'];
  5710. }
  5711. if (!isset($sessionInfo['session_name'])) {
  5712. $sessionInfo['session_name'] = $sessionInfo['name'];
  5713. }
  5714. return $sessionInfo;
  5715. },
  5716. $sessions
  5717. );
  5718. $calendarSessions = [];
  5719. foreach ($sessions as $sessionInfo) {
  5720. if (!empty($sessionInfo['duration'])) {
  5721. $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
  5722. $sessionInfo['session_id'],
  5723. $userInfo['id']
  5724. );
  5725. if (empty($courseAccess)) {
  5726. continue;
  5727. }
  5728. $firstAcessDate = new DateTime(api_get_local_time($courseAccess['login_course_date']), $timezone);
  5729. $lastAccessDate = clone $firstAcessDate;
  5730. $lastAccessDate->modify("+{$sessionInfo['duration']} days");
  5731. $firstAccessYear = (int) $firstAcessDate->format('Y');
  5732. $lastAccessYear = (int) $lastAccessDate->format('Y');
  5733. if ($firstAccessYear <= $searchYear && $lastAccessYear >= $searchYear) {
  5734. $calendarSessions[$sessionInfo['session_id']] = [
  5735. 'name' => $sessionInfo['session_name'],
  5736. 'access_start_date' => $firstAcessDate->format('Y-m-d h:i:s'),
  5737. 'access_end_date' => $lastAccessDate->format('Y-m-d h:i:s'),
  5738. ];
  5739. }
  5740. continue;
  5741. }
  5742. $accessStartDate = !empty($sessionInfo['access_start_date'])
  5743. ? new DateTime(api_get_local_time($sessionInfo['access_start_date']), $timezone)
  5744. : null;
  5745. $accessEndDate = !empty($sessionInfo['access_end_date'])
  5746. ? new DateTime(api_get_local_time($sessionInfo['access_end_date']), $timezone)
  5747. : null;
  5748. $accessStartYear = $accessStartDate ? (int) $accessStartDate->format('Y') : 0;
  5749. $accessEndYear = $accessEndDate ? (int) $accessEndDate->format('Y') : 0;
  5750. $isValid = false;
  5751. if ($accessStartYear && $accessEndYear) {
  5752. if ($accessStartYear <= $searchYear && $accessEndYear >= $searchYear) {
  5753. $isValid = true;
  5754. }
  5755. }
  5756. if ($accessStartYear && !$accessEndYear) {
  5757. if ($accessStartYear == $searchYear) {
  5758. $isValid = true;
  5759. }
  5760. }
  5761. if (!$accessStartYear && $accessEndYear) {
  5762. if ($accessEndYear == $searchYear) {
  5763. $isValid = true;
  5764. }
  5765. }
  5766. if ($isValid) {
  5767. $calendarSessions[$sessionInfo['session_id']] = [
  5768. 'name' => $sessionInfo['session_name'],
  5769. 'access_start_date' => $accessStartDate ? $accessStartDate->format('Y-m-d h:i:s') : null,
  5770. 'access_end_date' => $accessEndDate ? $accessEndDate->format('Y-m-d h:i:s') : null,
  5771. ];
  5772. }
  5773. }
  5774. return $calendarSessions;
  5775. }
  5776. /**
  5777. * Get sessions info for planification calendar.
  5778. *
  5779. * @param array $sessionsList Session list from UserManager::getSubscribedSessionsByYear
  5780. * @param int $searchYear
  5781. *
  5782. * @throws Exception
  5783. *
  5784. * @return array
  5785. */
  5786. public static function getSessionsCalendarByYear(array $sessionsList, $searchYear)
  5787. {
  5788. $timezone = new DateTimeZone(api_get_timezone());
  5789. $calendar = [];
  5790. foreach ($sessionsList as $sessionId => $sessionInfo) {
  5791. $startDate = $sessionInfo['access_start_date']
  5792. ? new DateTime(api_get_local_time($sessionInfo['access_start_date']), $timezone)
  5793. : null;
  5794. $endDate = $sessionInfo['access_end_date']
  5795. ? new DateTime(api_get_local_time($sessionInfo['access_end_date']), $timezone)
  5796. : null;
  5797. $startYear = $startDate ? (int) $startDate->format('Y') : 0;
  5798. $startWeekYear = $startDate ? (int) $startDate->format('o') : 0;
  5799. $startWeek = $startDate ? (int) $startDate->format('W') : 0;
  5800. $endYear = $endDate ? (int) $endDate->format('Y') : 0;
  5801. $endWeekYear = $endDate ? (int) $endDate->format('o') : 0;
  5802. $endWeek = $endDate ? (int) $endDate->format('W') : 0;
  5803. $start = $startWeekYear < $searchYear ? 0 : $startWeek - 1;
  5804. $duration = $endWeekYear > $searchYear ? 52 - $start : $endWeek - $start;
  5805. $calendar[] = [
  5806. 'id' => $sessionId,
  5807. 'name' => $sessionInfo['name'],
  5808. 'human_date' => SessionManager::convertSessionDateToString($startDate, $endDate, false, true),
  5809. 'start_in_last_year' => $startYear < $searchYear,
  5810. 'end_in_next_year' => $endYear > $searchYear,
  5811. 'no_start' => !$startWeek,
  5812. 'no_end' => !$endWeek,
  5813. 'start' => $start,
  5814. 'duration' => $duration > 0 ? $duration : 1,
  5815. ];
  5816. }
  5817. usort(
  5818. $calendar,
  5819. function ($sA, $sB) {
  5820. if ($sA['start'] == $sB['start']) {
  5821. return 0;
  5822. }
  5823. if ($sA['start'] < $sB['start']) {
  5824. return -1;
  5825. }
  5826. return 1;
  5827. }
  5828. );
  5829. return $calendar;
  5830. }
  5831. /**
  5832. * Return the user's full name. Optionally with the username.
  5833. *
  5834. * @param User $user
  5835. * @param bool $includeUsername Optional. By default username is not included.
  5836. *
  5837. * @return string
  5838. */
  5839. public static function formatUserFullName(User $user, $includeUsername = false)
  5840. {
  5841. $fullName = api_get_person_name($user->getFirstname(), $user->getLastname());
  5842. if ($includeUsername && api_get_configuration_value('hide_username_with_complete_name') !== true) {
  5843. $username = $user->getUsername();
  5844. return "$fullName ($username)";
  5845. }
  5846. return $fullName;
  5847. }
  5848. /**
  5849. * @return EncoderFactory
  5850. */
  5851. private static function getEncoderFactory()
  5852. {
  5853. $encryption = self::getPasswordEncryption();
  5854. $encoders = [
  5855. 'Chamilo\\UserBundle\\Entity\\User' => new \Chamilo\UserBundle\Security\Encoder($encryption),
  5856. ];
  5857. $encoderFactory = new EncoderFactory($encoders);
  5858. return $encoderFactory;
  5859. }
  5860. /**
  5861. * @param User $user
  5862. *
  5863. * @return \Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface
  5864. */
  5865. private static function getEncoder(User $user)
  5866. {
  5867. $encoderFactory = self::getEncoderFactory();
  5868. return $encoderFactory->getEncoder($user);
  5869. }
  5870. /**
  5871. * Disables or enables a user.
  5872. *
  5873. * @param int $user_id
  5874. * @param int $active Enable or disable
  5875. *
  5876. * @return bool True on success, false on failure
  5877. * @assert (-1,0) === false
  5878. * @assert (1,1) === true
  5879. */
  5880. private static function change_active_state($user_id, $active)
  5881. {
  5882. $user_id = (int) $user_id;
  5883. $active = (int) $active;
  5884. if (empty($user_id)) {
  5885. return false;
  5886. }
  5887. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  5888. $sql = "UPDATE $table_user SET active = '$active' WHERE id = $user_id";
  5889. $r = Database::query($sql);
  5890. $ev = LOG_USER_DISABLE;
  5891. if ($active == 1) {
  5892. $ev = LOG_USER_ENABLE;
  5893. }
  5894. if ($r !== false) {
  5895. Event::addEvent($ev, LOG_USER_ID, $user_id);
  5896. }
  5897. return $r;
  5898. }
  5899. /**
  5900. * Get either a Gravatar URL or complete image tag for a specified email address.
  5901. *
  5902. * @param string $email The email address
  5903. * @param int $s Size in pixels, defaults to 80px [ 1 - 2048 ]
  5904. * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
  5905. * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
  5906. * @param bool $img True to return a complete IMG tag False for just the URL
  5907. * @param array $atts Optional, additional key/value attributes to include in the IMG tag
  5908. *
  5909. * @return string containing either just a URL or a complete image tag
  5910. * @source http://gravatar.com/site/implement/images/php/
  5911. */
  5912. private static function getGravatar(
  5913. $email,
  5914. $s = 80,
  5915. $d = 'mm',
  5916. $r = 'g',
  5917. $img = false,
  5918. $atts = []
  5919. ) {
  5920. $url = 'http://www.gravatar.com/avatar/';
  5921. if (!empty($_SERVER['HTTPS'])) {
  5922. $url = 'https://secure.gravatar.com/avatar/';
  5923. }
  5924. $url .= md5(strtolower(trim($email)));
  5925. $url .= "?s=$s&d=$d&r=$r";
  5926. if ($img) {
  5927. $url = '<img src="'.$url.'"';
  5928. foreach ($atts as $key => $val) {
  5929. $url .= ' '.$key.'="'.$val.'"';
  5930. }
  5931. $url .= ' />';
  5932. }
  5933. return $url;
  5934. }
  5935. }