usermanager.lib.php 238 KB

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