usermanager.lib.php 237 KB

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