usermanager.lib.php 218 KB

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