usermanager.lib.php 208 KB

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