usermanager.lib.php 234 KB

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