usermanager.lib.php 199 KB

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