user.class.php 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945
  1. <?php
  2. /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (c) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (c) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2005 Lionel Cousteix <etm_ltd@tiscali.co.uk>
  9. * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
  10. * Copyright (C) 2013-2019 Philippe Grand <philippe.grand@atoo-net.com>
  11. * Copyright (C) 2013-2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
  12. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  13. * Copyright (C) 2018 charlene Benke <charlie@patas-monkey.com>
  14. * Copyright (C) 2018-2021 Nicolas ZABOURI <info@inovea-conseil.com>
  15. * Copyright (C) 2019-2020 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2019 Abbes Bahfir <dolipar@dolipar.org>
  17. *
  18. * This program is free software; you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation; either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  30. */
  31. /**
  32. * \file htdocs/user/class/user.class.php
  33. * \brief File of class to manage users
  34. * \ingroup core
  35. */
  36. require_once DOL_DOCUMENT_ROOT . '/core/lib/security.lib.php';
  37. require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
  38. require_once DOL_DOCUMENT_ROOT . '/user/class/usergroup.class.php';
  39. /**
  40. * Class to manage Dolibarr users
  41. */
  42. class User extends CommonObject
  43. {
  44. /**
  45. * @var string ID to identify managed object
  46. */
  47. public $element = 'user';
  48. /**
  49. * @var string Name of table without prefix where object is stored
  50. */
  51. public $table_element = 'user';
  52. /**
  53. * @var string Field with ID of parent key if this field has a parent
  54. */
  55. public $fk_element = 'fk_user';
  56. /**
  57. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  58. * @var int
  59. */
  60. public $ismultientitymanaged = 1;
  61. /**
  62. * @var string picto
  63. */
  64. public $picto = 'user';
  65. public $id = 0;
  66. public $statut;
  67. public $ldap_sid;
  68. public $search_sid;
  69. public $employee;
  70. public $civility_code;
  71. /**
  72. * @var string gender
  73. */
  74. public $gender;
  75. public $birth;
  76. /**
  77. * @var string email
  78. */
  79. public $email;
  80. /**
  81. * @var string personal email
  82. */
  83. public $personal_email;
  84. /**
  85. * @var array array of socialnetworks
  86. */
  87. public $socialnetworks;
  88. /**
  89. * @var string skype account
  90. * @deprecated
  91. */
  92. public $skype;
  93. /**
  94. * @var string twitter account
  95. * @deprecated
  96. */
  97. public $twitter;
  98. /**
  99. * @var string facebook account
  100. * @deprecated
  101. */
  102. public $facebook;
  103. /**
  104. * @var string linkedin account
  105. * @deprecated
  106. */
  107. public $linkedin;
  108. /**
  109. * @var string job position
  110. */
  111. public $job;
  112. /**
  113. * @var string user signature
  114. */
  115. public $signature;
  116. /**
  117. * @var string Address
  118. */
  119. public $address;
  120. /**
  121. * @var string zip code
  122. */
  123. public $zip;
  124. /**
  125. * @var string town
  126. */
  127. public $town;
  128. public $state_id; // The state/department
  129. public $state_code;
  130. public $state;
  131. /**
  132. * @var string office phone
  133. */
  134. public $office_phone;
  135. /**
  136. * @var string office fax
  137. */
  138. public $office_fax;
  139. /**
  140. * @var string phone mobile
  141. */
  142. public $user_mobile;
  143. /**
  144. * @var string personal phone mobile
  145. */
  146. public $personal_mobile;
  147. /**
  148. * @var int 1 if admin 0 if standard user
  149. */
  150. public $admin;
  151. /**
  152. * @var string user login
  153. */
  154. public $login;
  155. /**
  156. * @var string user apikey
  157. */
  158. public $api_key;
  159. /**
  160. * @var int Entity
  161. */
  162. public $entity;
  163. /**
  164. * @var string Clear password in memory
  165. */
  166. public $pass;
  167. /**
  168. * @var string Clear password in database (defined if DATABASE_PWD_ENCRYPTED=0)
  169. */
  170. public $pass_indatabase;
  171. /**
  172. * @var string Encrypted password in database (always defined)
  173. */
  174. public $pass_indatabase_crypted;
  175. /**
  176. * @var string Temporary password
  177. */
  178. public $pass_temp;
  179. /**
  180. * Date creation record (datec)
  181. *
  182. * @var integer
  183. */
  184. public $datec;
  185. /**
  186. * Date modification record (tms)
  187. *
  188. * @var integer
  189. */
  190. public $datem;
  191. /**
  192. * @var int If this is defined, it is an external user
  193. */
  194. public $socid;
  195. /**
  196. * @var int If this is defined, it is a user created from a contact
  197. */
  198. public $contact_id;
  199. /**
  200. * @var int ID
  201. */
  202. public $fk_member;
  203. /**
  204. * @var int User ID of supervisor
  205. */
  206. public $fk_user;
  207. /**
  208. * @var int User ID of expense validator
  209. */
  210. public $fk_user_expense_validator;
  211. /**
  212. * @var int User ID of holidays validator
  213. */
  214. public $fk_user_holiday_validator;
  215. /**
  216. * @string clicktodial url
  217. */
  218. public $clicktodial_url;
  219. /**
  220. * @var string clicktodial login
  221. */
  222. public $clicktodial_login;
  223. /**
  224. * @var string clicktodial password
  225. */
  226. public $clicktodial_password;
  227. /**
  228. * @var string clicktodial poste
  229. */
  230. public $clicktodial_poste;
  231. public $datelastlogin;
  232. public $datepreviouslogin;
  233. public $iplastlogin;
  234. public $ippreviouslogin;
  235. public $datestartvalidity;
  236. public $dateendvalidity;
  237. /**
  238. * @var string photo filename
  239. */
  240. public $photo;
  241. public $lang;
  242. /**
  243. * @var stdClass Class of permissions user->rights->permx
  244. */
  245. public $rights;
  246. /**
  247. * @var int All permissions are loaded
  248. */
  249. public $all_permissions_are_loaded;
  250. /**
  251. * @var int Number of rights granted to the user. Value loaded after a getrights().
  252. */
  253. public $nb_rights;
  254. /**
  255. * @var array To store list of groups of user (used by API /info for example)
  256. */
  257. public $user_group_list;
  258. /**
  259. * @var array Cache array of already loaded permissions
  260. */
  261. private $_tab_loaded = array();
  262. /**
  263. * @var stdClass To store personal config
  264. */
  265. public $conf;
  266. public $default_values; // To store default values for user. Loaded by loadDefaultValues().
  267. public $lastsearch_values_tmp; // To store current search criterias for user
  268. public $lastsearch_values; // To store last saved search criterias for user
  269. public $users = array(); // To store all tree of users hierarchy
  270. public $parentof; // To store an array of all parents for all ids.
  271. private $cache_childids; // Cache array of already loaded childs
  272. public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
  273. public $thm; // Average cost of employee - Used for valuation of time spent
  274. public $tjm; // Average cost of employee
  275. public $salary; // Monthly salary - Denormalized value from llx_user_employment
  276. public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment
  277. public $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment
  278. /**
  279. * @var string Define background color for user in agenda
  280. */
  281. public $color;
  282. public $dateemployment; // Define date of employment by company
  283. public $dateemploymentend; // Define date of employment end by company
  284. public $default_c_exp_tax_cat;
  285. /**
  286. * @var string ref for employee
  287. */
  288. public $ref_employee;
  289. /**
  290. * @var string national registration number
  291. */
  292. public $national_registration_number;
  293. public $default_range;
  294. /**
  295. *@var int id of warehouse
  296. */
  297. public $fk_warehouse;
  298. public $fields = array(
  299. 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
  300. 'lastname' => array('type' => 'varchar(50)', 'label' => 'LastName', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 20, 'searchall' => 1),
  301. 'firstname' => array('type' => 'varchar(50)', 'label' => 'FirstName', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1),
  302. 'ref_employee' => array('type' => 'varchar(50)', 'label' => 'RefEmployee', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 30, 'searchall' => 1),
  303. 'national_registration_number' => array('type' => 'varchar(50)', 'label' => 'NationalRegistrationNumber', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 40, 'searchall' => 1)
  304. );
  305. const STATUS_DISABLED = 0;
  306. const STATUS_ENABLED = 1;
  307. /**
  308. * Constructor of the class
  309. *
  310. * @param DoliDb $db Database handler
  311. */
  312. public function __construct($db)
  313. {
  314. $this->db = $db;
  315. // User preference
  316. $this->liste_limit = 0;
  317. $this->clicktodial_loaded = 0;
  318. // For cache usage
  319. $this->all_permissions_are_loaded = 0;
  320. $this->nb_rights = 0;
  321. // Force some default values
  322. $this->admin = 0;
  323. $this->employee = 1;
  324. $this->conf = new stdClass();
  325. $this->rights = new stdClass();
  326. $this->rights->user = new stdClass();
  327. $this->rights->user->user = new stdClass();
  328. $this->rights->user->self = new stdClass();
  329. $this->rights->user->user_advance = new stdClass();
  330. $this->rights->user->self_advance = new stdClass();
  331. $this->rights->user->group_advance = new stdClass();
  332. }
  333. /**
  334. * Load a user from database with its id or ref (login).
  335. * This function does not load permissions, only user properties. Use getrights() for this just after the fetch.
  336. *
  337. * @param int $id If defined, id to used for search
  338. * @param string $login If defined, login to used for search
  339. * @param string $sid If defined, sid to used for search
  340. * @param int $loadpersonalconf 1=also load personal conf of user (in $user->conf->xxx), 0=do not load personal conf.
  341. * @param int $entity If a value is >= 0, we force the search on a specific entity. If -1, means search depens on default setup.
  342. * @param int $email If defined, email to used for search
  343. * @param int $fk_socpeople If defined, id of contact for search
  344. * @return int <0 if KO, 0 not found, >0 if OK
  345. */
  346. public function fetch($id = '', $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1, $email = '', $fk_socpeople = 0)
  347. {
  348. global $conf, $user;
  349. // Clean parameters
  350. $login = trim($login);
  351. // Get user
  352. $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.civility as civility_code, u.birth, u.email, u.personal_email, u.job,";
  353. $sql .= " u.socialnetworks,";
  354. $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile, u.personal_mobile,";
  355. $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
  356. $sql .= " u.admin, u.login, u.note_private, u.note_public,";
  357. $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.api_key,";
  358. $sql .= " u.fk_soc, u.fk_socpeople, u.fk_member, u.fk_user, u.ldap_sid, u.fk_user_expense_validator, u.fk_user_holiday_validator,";
  359. $sql .= " u.statut as status, u.lang, u.entity,";
  360. $sql .= " u.datec as datec,";
  361. $sql .= " u.tms as datem,";
  362. $sql .= " u.datelastlogin as datel,";
  363. $sql .= " u.datepreviouslogin as datep,";
  364. $sql .= " u.iplastlogin,";
  365. $sql .= " u.ippreviouslogin,";
  366. $sql .= " u.datelastpassvalidation,";
  367. $sql .= " u.datestartvalidity,";
  368. $sql .= " u.dateendvalidity,";
  369. $sql .= " u.photo as photo,";
  370. $sql .= " u.openid as openid,";
  371. $sql .= " u.accountancy_code,";
  372. $sql .= " u.thm,";
  373. $sql .= " u.tjm,";
  374. $sql .= " u.salary,";
  375. $sql .= " u.salaryextra,";
  376. $sql .= " u.weeklyhours,";
  377. $sql .= " u.color,";
  378. $sql .= " u.dateemployment, u.dateemploymentend,";
  379. $sql .= " u.fk_warehouse,";
  380. $sql .= " u.ref_ext,";
  381. $sql .= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode
  382. $sql .= " u.national_registration_number,";
  383. $sql .= " u.ref_employee,";
  384. $sql .= " c.code as country_code, c.label as country,";
  385. $sql .= " d.code_departement as state_code, d.nom as state";
  386. $sql .= " FROM " . $this->db->prefix() . "user as u";
  387. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_country as c ON u.fk_country = c.rowid";
  388. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_departements as d ON u.fk_state = d.rowid";
  389. if ($entity < 0) {
  390. if ((!isModEnabled('multicompany') || empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) && (!empty($user->entity))) {
  391. if ($conf->global->PACKAGEHISTORY_FOR_ALL_USERS && $user->array_options['options_user_category'] == 6) {
  392. $sql .= " WHERE u.entity IS NOT NULL";
  393. } else {
  394. $sql .= " WHERE u.entity IN (0, " . ((int) $conf->entity) . ")";
  395. }
  396. } else {
  397. $sql .= " WHERE u.entity IS NOT NULL"; // multicompany is on in transverse mode or user making fetch is on entity 0, so user is allowed to fetch anywhere into database
  398. }
  399. } else {
  400. // The fetch was forced on an entity
  401. if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  402. $sql .= " WHERE u.entity IS NOT NULL"; // multicompany is on in transverse mode or user making fetch is on entity 0, so user is allowed to fetch anywhere into database
  403. } else {
  404. $sql .= " WHERE u.entity IN (0, " . ((int) (($entity != '' && $entity >= 0) ? $entity : $conf->entity)) . ")"; // search in entity provided in parameter
  405. }
  406. }
  407. if ($sid) {
  408. // permet une recherche du user par son SID ActiveDirectory ou Samba
  409. $sql .= " AND (u.ldap_sid = '" . $this->db->escape($sid) . "' OR u.login = '" . $this->db->escape($login) . "')";
  410. } elseif ($login) {
  411. $sql .= " AND u.login = '" . $this->db->escape($login) . "'";
  412. } elseif ($email) {
  413. $sql .= " AND u.email = '" . $this->db->escape($email) . "'";
  414. } elseif ($fk_socpeople > 0) {
  415. $sql .= " AND u.fk_socpeople = " . ((int) $fk_socpeople);
  416. } else {
  417. $sql .= " AND u.rowid = " . ((int) $id);
  418. }
  419. $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
  420. if ($sid) {
  421. // permet une recherche du user par son SID ActiveDirectory ou Samba
  422. $sql .= ' ' . $this->db->plimit(1);
  423. }
  424. $result = $this->db->query($sql);
  425. if ($result) {
  426. $obj = $this->db->fetch_object($result);
  427. if ($obj) {
  428. $this->id = $obj->rowid;
  429. $this->ref = $obj->rowid;
  430. $this->ref_ext = $obj->ref_ext;
  431. $this->ldap_sid = $obj->ldap_sid;
  432. $this->civility_code = $obj->civility_code;
  433. $this->lastname = $obj->lastname;
  434. $this->firstname = $obj->firstname;
  435. $this->ref_employee = $obj->ref_employee;
  436. $this->national_registration_number = $obj->national_registration_number;
  437. $this->employee = $obj->employee;
  438. $this->login = $obj->login;
  439. $this->gender = $obj->gender;
  440. $this->birth = $this->db->jdate($obj->birth);
  441. $this->pass_indatabase = $obj->pass;
  442. $this->pass_indatabase_crypted = $obj->pass_crypted;
  443. $this->pass = $obj->pass;
  444. $this->pass_temp = $obj->pass_temp;
  445. $this->api_key = dolDecrypt($obj->api_key);
  446. $this->address = $obj->address;
  447. $this->zip = $obj->zip;
  448. $this->town = $obj->town;
  449. $this->country_id = $obj->country_id;
  450. $this->country_code = $obj->country_id ? $obj->country_code : '';
  451. //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
  452. $this->state_id = $obj->state_id;
  453. $this->state_code = $obj->state_code;
  454. $this->state = ($obj->state != '-' ? $obj->state : '');
  455. $this->office_phone = $obj->office_phone;
  456. $this->office_fax = $obj->office_fax;
  457. $this->user_mobile = $obj->user_mobile;
  458. $this->personal_mobile = $obj->personal_mobile;
  459. $this->email = $obj->email;
  460. $this->personal_email = $obj->personal_email;
  461. $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
  462. $this->job = $obj->job;
  463. $this->signature = $obj->signature;
  464. $this->admin = $obj->admin;
  465. $this->note_public = $obj->note_public;
  466. $this->note_private = $obj->note_private;
  467. $this->note = $obj->note_private; // deprecated
  468. $this->statut = $obj->status; // deprecated
  469. $this->status = $obj->status;
  470. $this->photo = $obj->photo;
  471. $this->openid = $obj->openid;
  472. $this->lang = $obj->lang;
  473. $this->entity = $obj->entity;
  474. $this->accountancy_code = $obj->accountancy_code;
  475. $this->thm = $obj->thm;
  476. $this->tjm = $obj->tjm;
  477. $this->salary = $obj->salary;
  478. $this->salaryextra = $obj->salaryextra;
  479. $this->weeklyhours = $obj->weeklyhours;
  480. $this->color = $obj->color;
  481. $this->dateemployment = $this->db->jdate($obj->dateemployment);
  482. $this->dateemploymentend = $this->db->jdate($obj->dateemploymentend);
  483. $this->datec = $this->db->jdate($obj->datec);
  484. $this->datem = $this->db->jdate($obj->datem);
  485. $this->datelastlogin = $this->db->jdate($obj->datel);
  486. $this->datepreviouslogin = $this->db->jdate($obj->datep);
  487. $this->iplastlogin = $obj->iplastlogin;
  488. $this->ippreviouslogin = $obj->ippreviouslogin;
  489. $this->datestartvalidity = $this->db->jdate($obj->datestartvalidity);
  490. $this->dateendvalidity = $this->db->jdate($obj->dateendvalidity);
  491. $this->socid = $obj->fk_soc;
  492. $this->contact_id = $obj->fk_socpeople;
  493. $this->fk_member = $obj->fk_member;
  494. $this->fk_user = $obj->fk_user;
  495. $this->fk_user_expense_validator = $obj->fk_user_expense_validator;
  496. $this->fk_user_holiday_validator = $obj->fk_user_holiday_validator;
  497. $this->default_range = $obj->default_range;
  498. $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
  499. $this->fk_warehouse = $obj->fk_warehouse;
  500. // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
  501. // in such case, this admin user must be admin for ALL entities.
  502. if (!isModEnabled('multicompany') && $this->admin && $this->entity == 1) {
  503. $this->entity = 0;
  504. }
  505. // Retrieve all extrafield
  506. // fetch optionals attributes and labels
  507. $this->fetch_optionals();
  508. $this->db->free($result);
  509. } else {
  510. $this->error = "USERNOTFOUND";
  511. dol_syslog(get_class($this) . "::fetch user not found", LOG_DEBUG);
  512. $this->db->free($result);
  513. return 0;
  514. }
  515. } else {
  516. $this->error = $this->db->lasterror();
  517. return -1;
  518. }
  519. // To get back the global configuration unique to the user
  520. if ($loadpersonalconf) {
  521. // Load user->conf for user
  522. $sql = "SELECT param, value FROM " . $this->db->prefix() . "user_param";
  523. $sql .= " WHERE fk_user = " . ((int) $this->id);
  524. $sql .= " AND entity = " . ((int) $conf->entity);
  525. //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
  526. $resql = $this->db->query($sql);
  527. if ($resql) {
  528. $num = $this->db->num_rows($resql);
  529. $i = 0;
  530. while ($i < $num) {
  531. $obj = $this->db->fetch_object($resql);
  532. $p = (!empty($obj->param) ? $obj->param : '');
  533. if (!empty($p)) {
  534. $this->conf->$p = $obj->value;
  535. }
  536. $i++;
  537. }
  538. $this->db->free($resql);
  539. } else {
  540. $this->error = $this->db->lasterror();
  541. return -2;
  542. }
  543. $result = $this->loadDefaultValues();
  544. if ($result < 0) {
  545. $this->error = $this->db->lasterror();
  546. return -3;
  547. }
  548. }
  549. return 1;
  550. }
  551. /**
  552. * Load default values from database table into property ->default_values
  553. *
  554. * @return int > 0 if OK, < 0 if KO
  555. */
  556. public function loadDefaultValues()
  557. {
  558. global $conf;
  559. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  560. // Load user->default_values for user. TODO Save this in memcached ?
  561. require_once DOL_DOCUMENT_ROOT . '/core/class/defaultvalues.class.php';
  562. $defaultValues = new DefaultValues($this->db);
  563. $result = $defaultValues->fetchAll('', '', 0, 0, array('t.user_id' => array(0, $this->id), 'entity' => array((isset($this->entity) ? $this->entity : $conf->entity), $conf->entity))); // User 0 (all) + me (if defined)
  564. if (!is_array($result) && $result < 0) {
  565. setEventMessages($defaultValues->error, $defaultValues->errors, 'errors');
  566. dol_print_error($this->db);
  567. return -1;
  568. } elseif (count($result) > 0) {
  569. foreach ($result as $defval) {
  570. if (!empty($defval->page) && !empty($defval->type) && !empty($defval->param)) {
  571. $pagewithoutquerystring = $defval->page;
  572. $pagequeries = '';
  573. $reg = array();
  574. if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
  575. $pagewithoutquerystring = $reg[1];
  576. $pagequeries = $reg[2];
  577. }
  578. $this->default_values[$pagewithoutquerystring][$defval->type][$pagequeries ? $pagequeries : '_noquery_'][$defval->param] = $defval->value;
  579. }
  580. }
  581. }
  582. if (!empty($this->default_values)) {
  583. foreach ($this->default_values as $a => $b) {
  584. foreach ($b as $c => $d) {
  585. krsort($this->default_values[$a][$c]);
  586. }
  587. }
  588. }
  589. }
  590. return 1;
  591. }
  592. /**
  593. * Return if a user has a permission.
  594. * You can use it like this: if ($user->hasRight('module', 'level11')).
  595. * It replaces old syntax: if ($user->rights->module->level1)
  596. *
  597. * @param int $module Module of permission to check
  598. * @param string $permlevel1 Permission level1 (Example: 'read', 'write', 'delete')
  599. * @param string $permlevel2 Permission level2
  600. * @return int 1 if user has permission, 0 if not.
  601. * @see clearrights(), delrights(), getrights(), hasRight()
  602. */
  603. public function hasRight($module, $permlevel1, $permlevel2 = '')
  604. {
  605. global $conf;
  606. // For compatibility with bad naming permissions on module
  607. $moduletomoduletouse = array(
  608. 'compta' => 'comptabilite',
  609. 'contract' => 'contrat',
  610. 'member' => 'adherent',
  611. 'mo' => 'mrp',
  612. 'order' => 'commande',
  613. 'produit' => 'product',
  614. 'project' => 'projet',
  615. 'propale' => 'propal',
  616. 'shipping' => 'expedition',
  617. 'task' => 'task@projet',
  618. 'fichinter' => 'ficheinter',
  619. 'propale' => 'propal',
  620. 'inventory' => 'stock',
  621. 'invoice' => 'facture',
  622. 'invoice_supplier' => 'fournisseur',
  623. 'order_supplier' => 'fournisseur',
  624. 'knowledgerecord' => 'knowledgerecord@knowledgemanagement',
  625. 'skill@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
  626. 'job@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
  627. 'position@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
  628. 'facturerec' => 'facture',
  629. 'margins' => 'margin',
  630. );
  631. if (!empty($moduletomoduletouse[$module])) {
  632. $module = $moduletomoduletouse[$module];
  633. }
  634. $moduleRightsMapping = array(
  635. 'product' => 'produit', // We must check $user->rights->produit...
  636. 'margin' => 'margins',
  637. 'comptabilite' => 'compta'
  638. );
  639. $rightsPath = $module;
  640. if (!empty($moduleRightsMapping[$rightsPath])) {
  641. $rightsPath = $moduleRightsMapping[$rightsPath];
  642. }
  643. // If module is abc@module, we check permission user->rights->module->abc->permlevel1
  644. $tmp = explode('@', $rightsPath, 2);
  645. if (!empty($tmp[1])) {
  646. if (strpos($module, '@') !== false) {
  647. $module = $tmp[1];
  648. }
  649. $rightsPath = $tmp[1];
  650. $permlevel2 = $permlevel1;
  651. $permlevel1 = $tmp[0];
  652. }
  653. // In $conf->modules, we have 'accounting', 'product', 'facture', ...
  654. // In $user->rights, we have 'accounting', 'produit', 'facture', ...
  655. //var_dump($module);
  656. //var_dump($rightsPath);
  657. //var_dump($this->rights->$rightsPath);
  658. //var_dump($conf->modules);
  659. //var_dump($module.' '.isModEnabled($module).' '.$rightsPath.' '.$permlevel1.' '.$permlevel2);
  660. if (!isModEnabled($module)) {
  661. return 0;
  662. }
  663. // For compatibility with bad naming permissions on permlevel1
  664. if ($permlevel1 == 'propale') {
  665. $permlevel1 = 'propal';
  666. }
  667. if ($permlevel1 == 'member') {
  668. $permlevel1 = 'adherent';
  669. }
  670. if ($permlevel1 == 'recruitmentcandidature') {
  671. $permlevel1 = 'recruitmentjobposition';
  672. }
  673. //var_dump($this->rights);
  674. //var_dump($rightsPath.' '.$permlevel1.' '.$permlevel2);
  675. if (empty($rightsPath) || empty($this->rights) || empty($this->rights->$rightsPath) || empty($permlevel1)) {
  676. return 0;
  677. }
  678. if ($permlevel2) {
  679. if (!empty($this->rights->$rightsPath->$permlevel1)) {
  680. if (!empty($this->rights->$rightsPath->$permlevel1->$permlevel2)) {
  681. return $this->rights->$rightsPath->$permlevel1->$permlevel2;
  682. }
  683. // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
  684. // instead of "read", "write", "delete"
  685. if ($permlevel2 == 'read' && !empty($this->rights->$rightsPath->$permlevel1->lire)) {
  686. return $this->rights->$rightsPath->$permlevel1->lire;
  687. }
  688. if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->creer)) {
  689. return $this->rights->$rightsPath->$permlevel1->creer;
  690. }
  691. if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->create)) {
  692. return $this->rights->$rightsPath->$permlevel1->create;
  693. }
  694. if ($permlevel2 == 'delete' && !empty($this->rights->$rightsPath->$permlevel1->supprimer)) {
  695. return $this->rights->$rightsPath->$permlevel1->supprimer;
  696. }
  697. }
  698. } else {
  699. if (!empty($this->rights->$rightsPath->$permlevel1)) {
  700. return $this->rights->$rightsPath->$permlevel1;
  701. }
  702. // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
  703. // instead of "read", "write", "delete"
  704. if ($permlevel1 == 'read' && !empty($this->rights->$rightsPath->lire)) {
  705. return $this->rights->$rightsPath->lire;
  706. }
  707. if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->creer)) {
  708. return $this->rights->$rightsPath->creer;
  709. }
  710. if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->create)) {
  711. return $this->rights->$rightsPath->create;
  712. }
  713. if ($permlevel1 == 'delete' && !empty($this->rights->$rightsPath->supprimer)) {
  714. return $this->rights->$rightsPath->supprimer;
  715. }
  716. }
  717. return 0;
  718. }
  719. /**
  720. * Add a right to the user
  721. *
  722. * @param int $rid Id of permission to add or 0 to add several permissions
  723. * @param string $allmodule Add all permissions of module $allmodule or 'allmodules' to include all modules.
  724. * @param string $allperms Add all permissions of module $allmodule, subperms $allperms only or '' to include all permissions.
  725. * @param int $entity Entity to use
  726. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  727. * @return int > 0 if OK, < 0 if KO
  728. * @see clearrights(), delrights(), getrights(), hasRight()
  729. */
  730. public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
  731. {
  732. global $conf, $user, $langs;
  733. $entity = (empty($entity) ? $conf->entity : $entity);
  734. dol_syslog(get_class($this) . "::addrights $rid, $allmodule, $allperms, $entity, $notrigger for user id=" . $this->id);
  735. $error = 0;
  736. $whereforadd = '';
  737. $this->db->begin();
  738. if (!empty($rid)) {
  739. $module = $perms = $subperms = '';
  740. // If we ask to add a given permission, we first load properties of this permission (module, perms and subperms).
  741. $sql = "SELECT module, perms, subperms";
  742. $sql .= " FROM " . $this->db->prefix() . "rights_def";
  743. $sql .= " WHERE id = " . ((int) $rid);
  744. $sql .= " AND entity = " . ((int) $entity);
  745. $result = $this->db->query($sql);
  746. if ($result) {
  747. $obj = $this->db->fetch_object($result);
  748. if ($obj) {
  749. $module = $obj->module;
  750. $perms = $obj->perms;
  751. $subperms = $obj->subperms;
  752. }
  753. } else {
  754. $error++;
  755. dol_print_error($this->db);
  756. }
  757. // Define the where for the permission to add
  758. $whereforadd = "id=" . ((int) $rid);
  759. // Add also inherited permissions
  760. if (!empty($subperms)) {
  761. $whereforadd .= " OR (module='" . $this->db->escape($module) . "' AND perms='" . $this->db->escape($perms) . "' AND (subperms='lire' OR subperms='read'))";
  762. } elseif (!empty($perms)) {
  763. $whereforadd .= " OR (module='" . $this->db->escape($module) . "' AND (perms='lire' OR perms='read') AND subperms IS NULL)";
  764. }
  765. } else {
  766. // On a pas demande un droit en particulier mais une liste de droits
  767. // sur la base d'un nom de module de de perms
  768. // Where pour la liste des droits a ajouter
  769. if (!empty($allmodule)) {
  770. if ($allmodule == 'allmodules') {
  771. $whereforadd = 'allmodules';
  772. } else {
  773. $whereforadd = "module='" . $this->db->escape($allmodule) . "'";
  774. if (!empty($allperms)) {
  775. $whereforadd .= " AND perms='" . $this->db->escape($allperms) . "'";
  776. }
  777. }
  778. }
  779. }
  780. // Add automatically other permission using the criteria whereforadd
  781. if (!empty($whereforadd)) {
  782. //print "$module-$perms-$subperms";
  783. $sql = "SELECT id";
  784. $sql .= " FROM " . $this->db->prefix() . "rights_def";
  785. $sql .= " WHERE entity = " . ((int) $entity);
  786. if (!empty($whereforadd) && $whereforadd != 'allmodules') {
  787. $sql .= " AND (" . $whereforadd . ")"; // Note: parenthesis are important because whereforadd can contains OR. Also note that $whereforadd is already sanitized
  788. }
  789. $result = $this->db->query($sql);
  790. if ($result) {
  791. $num = $this->db->num_rows($result);
  792. $i = 0;
  793. while ($i < $num) {
  794. $obj = $this->db->fetch_object($result);
  795. if ($obj) {
  796. $nid = $obj->id;
  797. $sql = "DELETE FROM " . $this->db->prefix() . "user_rights WHERE fk_user = " . ((int) $this->id) . " AND fk_id = " . ((int) $nid) . " AND entity = " . ((int) $entity);
  798. if (!$this->db->query($sql)) {
  799. $error++;
  800. }
  801. $sql = "INSERT INTO " . $this->db->prefix() . "user_rights (entity, fk_user, fk_id) VALUES (" . ((int) $entity) . ", " . ((int) $this->id) . ", " . ((int) $nid) . ")";
  802. if (!$this->db->query($sql)) {
  803. $error++;
  804. }
  805. }
  806. $i++;
  807. }
  808. } else {
  809. $error++;
  810. dol_print_error($this->db);
  811. }
  812. }
  813. if (!$error && !$notrigger) {
  814. $langs->load("other");
  815. $this->context = array('audit' => $langs->trans("PermissionsAdd") . ($rid ? ' (id=' . $rid . ')' : ''));
  816. // Call trigger
  817. $result = $this->call_trigger('USER_MODIFY', $user);
  818. if ($result < 0) {
  819. $error++;
  820. }
  821. // End call triggers
  822. }
  823. if ($error) {
  824. $this->db->rollback();
  825. return -$error;
  826. } else {
  827. $this->db->commit();
  828. return 1;
  829. }
  830. }
  831. /**
  832. * Remove a right to the user
  833. *
  834. * @param int $rid Id du droit a retirer
  835. * @param string $allmodule Retirer tous les droits du module allmodule
  836. * @param string $allperms Retirer tous les droits du module allmodule, perms allperms
  837. * @param int $entity Entity to use
  838. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  839. * @return int > 0 if OK, < 0 if OK
  840. * @see clearrights(), addrights(), getrights(), hasRight()
  841. */
  842. public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
  843. {
  844. global $conf, $user, $langs;
  845. $error = 0;
  846. $wherefordel = '';
  847. $entity = (!empty($entity) ? $entity : $conf->entity);
  848. $this->db->begin();
  849. if (!empty($rid)) {
  850. $module = $perms = $subperms = '';
  851. // Si on a demande supression d'un droit en particulier, on recupere
  852. // les caracteristiques module, perms et subperms de ce droit.
  853. $sql = "SELECT module, perms, subperms";
  854. $sql .= " FROM " . $this->db->prefix() . "rights_def";
  855. $sql .= " WHERE id = '" . $this->db->escape($rid) . "'";
  856. $sql .= " AND entity = " . ((int) $entity);
  857. $result = $this->db->query($sql);
  858. if ($result) {
  859. $obj = $this->db->fetch_object($result);
  860. if ($obj) {
  861. $module = $obj->module;
  862. $perms = $obj->perms;
  863. $subperms = $obj->subperms;
  864. }
  865. } else {
  866. $error++;
  867. dol_print_error($this->db);
  868. }
  869. // Where pour la liste des droits a supprimer
  870. $wherefordel = "id=" . ((int) $rid);
  871. // Suppression des droits induits
  872. if ($subperms == 'lire' || $subperms == 'read') {
  873. $wherefordel .= " OR (module='" . $this->db->escape($module) . "' AND perms='" . $this->db->escape($perms) . "' AND subperms IS NOT NULL)";
  874. }
  875. if ($perms == 'lire' || $perms == 'read') {
  876. $wherefordel .= " OR (module='" . $this->db->escape($module) . "')";
  877. }
  878. } else {
  879. // On a demande suppression d'un droit sur la base d'un nom de module ou perms
  880. // Where pour la liste des droits a supprimer
  881. if (!empty($allmodule)) {
  882. if ($allmodule == 'allmodules') {
  883. $wherefordel = 'allmodules';
  884. } else {
  885. $wherefordel = "module='" . $this->db->escape($allmodule) . "'";
  886. if (!empty($allperms)) {
  887. $wherefordel .= " AND perms='" . $this->db->escape($allperms) . "'";
  888. }
  889. }
  890. }
  891. }
  892. // Suppression des droits selon critere defini dans wherefordel
  893. if (!empty($wherefordel)) {
  894. //print "$module-$perms-$subperms";
  895. $sql = "SELECT id";
  896. $sql .= " FROM " . $this->db->prefix() . "rights_def";
  897. $sql .= " WHERE entity = " . ((int) $entity);
  898. if (!empty($wherefordel) && $wherefordel != 'allmodules') {
  899. $sql .= " AND (" . $wherefordel . ")"; // Note: parenthesis are important because wherefordel can contains OR. Also note that $wherefordel is already sanitized
  900. }
  901. // avoid admin can remove his own important rights
  902. if ($this->admin == 1) {
  903. $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
  904. $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
  905. $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
  906. $sql .= " AND id NOT IN (358)"; // user export
  907. }
  908. $result = $this->db->query($sql);
  909. if ($result) {
  910. $num = $this->db->num_rows($result);
  911. $i = 0;
  912. while ($i < $num) {
  913. $obj = $this->db->fetch_object($result);
  914. $nid = $obj->id;
  915. $sql = "DELETE FROM " . $this->db->prefix() . "user_rights";
  916. $sql .= " WHERE fk_user = " . ((int) $this->id) . " AND fk_id = " . ((int) $nid);
  917. $sql .= " AND entity = " . ((int) $entity);
  918. if (!$this->db->query($sql)) {
  919. $error++;
  920. }
  921. $i++;
  922. }
  923. } else {
  924. $error++;
  925. dol_print_error($this->db);
  926. }
  927. }
  928. if (!$error && !$notrigger) {
  929. $langs->load("other");
  930. $this->context = array('audit' => $langs->trans("PermissionsDelete") . ($rid ? ' (id=' . $rid . ')' : ''));
  931. // Call trigger
  932. $result = $this->call_trigger('USER_MODIFY', $user);
  933. if ($result < 0) {
  934. $error++;
  935. }
  936. // End call triggers
  937. }
  938. if ($error) {
  939. $this->db->rollback();
  940. return -$error;
  941. } else {
  942. $this->db->commit();
  943. return 1;
  944. }
  945. }
  946. /**
  947. * Clear all permissions array of user
  948. *
  949. * @return void
  950. * @see getrights(), hasRight()
  951. */
  952. public function clearrights()
  953. {
  954. dol_syslog(get_class($this) . "::clearrights reset user->rights");
  955. $this->rights = null;
  956. $this->nb_rights = 0;
  957. $this->all_permissions_are_loaded = 0;
  958. $this->_tab_loaded = array();
  959. }
  960. /**
  961. * Load permissions granted to user into object user
  962. *
  963. * @param string $moduletag Limit permission for a particular module ('' by default means load all permissions)
  964. * @param int $forcereload Force reload of permissions even if they were already loaded (ignore cache)
  965. * @return void
  966. * @see clearrights(), delrights(), addrights(), hasRight()
  967. */
  968. public function getrights($moduletag = '', $forcereload = 0)
  969. {
  970. global $conf;
  971. if (empty($forcereload)) {
  972. if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
  973. // Rights for this module are already loaded, so we leave
  974. return;
  975. }
  976. if (!empty($this->all_permissions_are_loaded)) {
  977. // We already loaded all rights for this user, so we leave
  978. return;
  979. }
  980. }
  981. // For avoid error
  982. if (!isset($this->rights) || !is_object($this->rights)) {
  983. $this->rights = new stdClass(); // For avoid error
  984. }
  985. if (!isset($this->rights->user) || !is_object($this->rights->user)) {
  986. $this->rights->user = new stdClass(); // For avoid error
  987. }
  988. // Get permission of users + Get permissions of groups
  989. // First user permissions
  990. $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
  991. $sql .= " FROM " . $this->db->prefix() . "user_rights as ur,";
  992. $sql .= " " . $this->db->prefix() . "rights_def as r";
  993. $sql .= " WHERE r.id = ur.fk_id";
  994. if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
  995. // on old version, we use entity defined into table r only
  996. $sql .= " AND r.entity IN (0," . (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) ? "1," : "") . $conf->entity . ")";
  997. } else {
  998. // On table r=rights_def, the unique key is (id, entity) because id is hard coded into module descriptor and insert during module activation.
  999. // So we must include the filter on entity on both table r. and ur.
  1000. $sql .= " AND r.entity = " . ((int) $conf->entity) . " AND ur.entity = " . ((int) $conf->entity);
  1001. }
  1002. $sql .= " AND ur.fk_user= " . ((int) $this->id);
  1003. $sql .= " AND r.perms IS NOT NULL";
  1004. if ($moduletag) {
  1005. $sql .= " AND r.module = '" . $this->db->escape($moduletag) . "'";
  1006. }
  1007. $resql = $this->db->query($sql);
  1008. if ($resql) {
  1009. $num = $this->db->num_rows($resql);
  1010. $i = 0;
  1011. while ($i < $num) {
  1012. $obj = $this->db->fetch_object($resql);
  1013. if ($obj) {
  1014. $module = $obj->module;
  1015. $perms = $obj->perms;
  1016. $subperms = $obj->subperms;
  1017. if (!empty($perms)) {
  1018. if (!empty($module)) {
  1019. if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
  1020. $this->rights->$module = new stdClass();
  1021. }
  1022. if (!empty($subperms)) {
  1023. if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
  1024. $this->rights->$module->$perms = new stdClass();
  1025. }
  1026. if (empty($this->rights->$module->$perms->$subperms)) {
  1027. $this->nb_rights++;
  1028. }
  1029. $this->rights->$module->$perms->$subperms = 1;
  1030. } else {
  1031. if (empty($this->rights->$module->$perms)) {
  1032. $this->nb_rights++;
  1033. }
  1034. $this->rights->$module->$perms = 1;
  1035. }
  1036. }
  1037. }
  1038. }
  1039. $i++;
  1040. }
  1041. $this->db->free($resql);
  1042. }
  1043. // Now permissions of groups
  1044. $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
  1045. $sql .= " FROM " . $this->db->prefix() . "usergroup_rights as gr,";
  1046. $sql .= " " . $this->db->prefix() . "usergroup_user as gu,";
  1047. $sql .= " " . $this->db->prefix() . "rights_def as r";
  1048. $sql .= " WHERE r.id = gr.fk_id";
  1049. // A very strange business rules. Must be same than into user->getrights() user/perms.php and user/group/perms.php
  1050. if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
  1051. if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1052. $sql .= " AND gu.entity IN (0," . $conf->entity . ")";
  1053. } else {
  1054. $sql .= " AND r.entity = " . ((int) $conf->entity);
  1055. }
  1056. } else {
  1057. $sql .= " AND gr.entity = " . ((int) $conf->entity); // Only groups created in current entity
  1058. // The entity on the table usergroup_user should be useless and should never be used because it is alreay into gr and r.
  1059. // but when using MULTICOMPANY_TRANSVERSE_MODE, we may insert record that make rubbish result due to duplicate record of
  1060. // other entities, so we are forced to add a filter here
  1061. $sql .= " AND gu.entity IN (0," . $conf->entity . ")";
  1062. $sql .= " AND r.entity = " . ((int) $conf->entity); // Only permission of modules enabled in current entity
  1063. }
  1064. // End of strange business rule
  1065. $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
  1066. $sql .= " AND gu.fk_user = " . ((int) $this->id);
  1067. $sql .= " AND r.perms IS NOT NULL";
  1068. if ($moduletag) {
  1069. $sql .= " AND r.module = '" . $this->db->escape($moduletag) . "'";
  1070. }
  1071. $resql = $this->db->query($sql);
  1072. if ($resql) {
  1073. $num = $this->db->num_rows($resql);
  1074. $i = 0;
  1075. while ($i < $num) {
  1076. $obj = $this->db->fetch_object($resql);
  1077. if ($obj) {
  1078. $module = $obj->module;
  1079. $perms = $obj->perms;
  1080. $subperms = $obj->subperms;
  1081. if (!empty($perms)) {
  1082. if (!empty($module)) {
  1083. if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
  1084. $this->rights->$module = new stdClass();
  1085. }
  1086. if (!empty($subperms)) {
  1087. if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
  1088. $this->rights->$module->$perms = new stdClass();
  1089. }
  1090. if (empty($this->rights->$module->$perms->$subperms)) {
  1091. $this->nb_rights++;
  1092. }
  1093. $this->rights->$module->$perms->$subperms = 1;
  1094. } else {
  1095. if (empty($this->rights->$module->$perms)) {
  1096. $this->nb_rights++;
  1097. }
  1098. // if we have already define a subperm like this $this->rights->$module->level1->level2 with llx_user_rights, we don't want override level1 because the level2 can be not define on user group
  1099. if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
  1100. $this->rights->$module->$perms = 1;
  1101. }
  1102. }
  1103. }
  1104. }
  1105. }
  1106. $i++;
  1107. }
  1108. $this->db->free($resql);
  1109. }
  1110. // Force permission on user for admin
  1111. if (!empty($this->admin)) {
  1112. if (empty($this->rights->user->user)) {
  1113. $this->rights->user->user = new stdClass();
  1114. }
  1115. $listofpermtotest = array('lire', 'creer', 'password', 'supprimer', 'export');
  1116. foreach ($listofpermtotest as $permtotest) {
  1117. if (empty($this->rights->user->user->$permtotest)) {
  1118. $this->rights->user->user->$permtotest = 1;
  1119. $this->nb_rights++;
  1120. }
  1121. }
  1122. if (empty($this->rights->user->self)) {
  1123. $this->rights->user->self = new stdClass();
  1124. }
  1125. $listofpermtotest = array('creer', 'password');
  1126. foreach ($listofpermtotest as $permtotest) {
  1127. if (empty($this->rights->user->self->$permtotest)) {
  1128. $this->rights->user->self->$permtotest = 1;
  1129. $this->nb_rights++;
  1130. }
  1131. }
  1132. // Add test on advanced permissions
  1133. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
  1134. if (empty($this->rights->user->user_advance)) {
  1135. $this->rights->user->user_advance = new stdClass();
  1136. }
  1137. $listofpermtotest = array('readperms', 'write');
  1138. foreach ($listofpermtotest as $permtotest) {
  1139. if (empty($this->rights->user->user_advance->$permtotest)) {
  1140. $this->rights->user->user_advance->$permtotest = 1;
  1141. $this->nb_rights++;
  1142. }
  1143. }
  1144. if (empty($this->rights->user->self_advance)) {
  1145. $this->rights->user->self_advance = new stdClass();
  1146. }
  1147. $listofpermtotest = array('readperms', 'writeperms');
  1148. foreach ($listofpermtotest as $permtotest) {
  1149. if (empty($this->rights->user->self_advance->$permtotest)) {
  1150. $this->rights->user->self_advance->$permtotest = 1;
  1151. $this->nb_rights++;
  1152. }
  1153. }
  1154. if (empty($this->rights->user->group_advance)) {
  1155. $this->rights->user->group_advance = new stdClass();
  1156. }
  1157. $listofpermtotest = array('read', 'readperms', 'write', 'delete');
  1158. foreach ($listofpermtotest as $permtotest) {
  1159. if (empty($this->rights->user) || empty($this->rights->user->group_advance->$permtotest)) {
  1160. $this->rights->user->group_advance->$permtotest = 1;
  1161. $this->nb_rights++;
  1162. }
  1163. }
  1164. }
  1165. }
  1166. // For backward compatibility
  1167. if (isset($this->rights->propale) && !isset($this->rights->propal)) {
  1168. $this->rights->propal = $this->rights->propale;
  1169. }
  1170. if (isset($this->rights->propal) && !isset($this->rights->propale)) {
  1171. $this->rights->propale = $this->rights->propal;
  1172. }
  1173. if (!$moduletag) {
  1174. // Si module etait non defini, alors on a tout charge, on peut donc considerer
  1175. // que les droits sont en cache (car tous charges) pour cet instance de user
  1176. $this->all_permissions_are_loaded = 1;
  1177. } else {
  1178. // If module defined, we flag it as loaded into cache
  1179. $this->_tab_loaded[$moduletag] = 1;
  1180. }
  1181. }
  1182. /**
  1183. * Change status of a user
  1184. *
  1185. * @param int $status Status to set
  1186. * @return int <0 if KO, 0 if nothing is done, >0 if OK
  1187. */
  1188. public function setstatus($status)
  1189. {
  1190. global $conf, $langs, $user;
  1191. $error = 0;
  1192. // Check parameters
  1193. if (isset($this->statut)) {
  1194. if ($this->statut == $status) {
  1195. return 0;
  1196. }
  1197. } elseif (isset($this->status) && $this->status == $status) {
  1198. return 0;
  1199. }
  1200. $this->db->begin();
  1201. // Save in database
  1202. $sql = "UPDATE " . $this->db->prefix() . "user";
  1203. $sql .= " SET statut = " . ((int) $status);
  1204. $sql .= " WHERE rowid = " . ((int) $this->id);
  1205. $result = $this->db->query($sql);
  1206. dol_syslog(get_class($this) . "::setstatus", LOG_DEBUG);
  1207. if ($result) {
  1208. // Call trigger
  1209. $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
  1210. if ($result < 0) {
  1211. $error++;
  1212. }
  1213. // End call triggers
  1214. }
  1215. if ($error) {
  1216. $this->db->rollback();
  1217. return -$error;
  1218. } else {
  1219. $this->status = $status;
  1220. $this->statut = $status;
  1221. $this->db->commit();
  1222. return 1;
  1223. }
  1224. }
  1225. /**
  1226. * Sets object to supplied categories.
  1227. *
  1228. * Deletes object from existing categories not supplied.
  1229. * Adds it to non existing supplied categories.
  1230. * Existing categories are left untouch.
  1231. *
  1232. * @param int[]|int $categories Category or categories IDs
  1233. * @return int <0 if KO, >0 if OK
  1234. */
  1235. public function setCategories($categories)
  1236. {
  1237. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  1238. return parent::setCategoriesCommon($categories, Categorie::TYPE_USER);
  1239. }
  1240. /**
  1241. * Delete the user
  1242. *
  1243. * @param User $user User than delete
  1244. * @return int <0 if KO, >0 if OK
  1245. */
  1246. public function delete(User $user)
  1247. {
  1248. global $conf, $langs;
  1249. $error = 0;
  1250. $this->db->begin();
  1251. $this->fetch($this->id);
  1252. dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
  1253. // Remove rights
  1254. $sql = "DELETE FROM " . $this->db->prefix() . "user_rights WHERE fk_user = " . ((int) $this->id);
  1255. if (!$error && !$this->db->query($sql)) {
  1256. $error++;
  1257. $this->error = $this->db->lasterror();
  1258. }
  1259. // Remove group
  1260. $sql = "DELETE FROM " . $this->db->prefix() . "usergroup_user WHERE fk_user = " . ((int) $this->id);
  1261. if (!$error && !$this->db->query($sql)) {
  1262. $error++;
  1263. $this->error = $this->db->lasterror();
  1264. }
  1265. // Remove params
  1266. $sql = "DELETE FROM " . $this->db->prefix() . "user_param WHERE fk_user = " . ((int) $this->id);
  1267. if (!$error && !$this->db->query($sql)) {
  1268. $error++;
  1269. $this->error = $this->db->lasterror();
  1270. }
  1271. // If contact, remove link
  1272. if ($this->contact_id > 0) {
  1273. $sql = "UPDATE " . $this->db->prefix() . "socpeople SET fk_user_creat = null WHERE rowid = " . ((int) $this->contact_id);
  1274. if (!$error && !$this->db->query($sql)) {
  1275. $error++;
  1276. $this->error = $this->db->lasterror();
  1277. }
  1278. }
  1279. // Remove extrafields
  1280. if (!$error) {
  1281. $result = $this->deleteExtraFields();
  1282. if ($result < 0) {
  1283. $error++;
  1284. dol_syslog(get_class($this) . "::delete error -4 " . $this->error, LOG_ERR);
  1285. }
  1286. }
  1287. // Remove user
  1288. if (!$error) {
  1289. $sql = "DELETE FROM " . $this->db->prefix() . "user WHERE rowid = " . ((int) $this->id);
  1290. dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
  1291. if (!$this->db->query($sql)) {
  1292. $error++;
  1293. $this->error = $this->db->lasterror();
  1294. }
  1295. }
  1296. if (!$error) {
  1297. // Call trigger
  1298. $result = $this->call_trigger('USER_DELETE', $user);
  1299. if ($result < 0) {
  1300. $error++;
  1301. $this->db->rollback();
  1302. return -1;
  1303. }
  1304. // End call triggers
  1305. $this->db->commit();
  1306. return 1;
  1307. } else {
  1308. $this->db->rollback();
  1309. return -1;
  1310. }
  1311. }
  1312. /**
  1313. * Create a user into database
  1314. *
  1315. * @param User $user Objet user doing creation
  1316. * @param int $notrigger 1=do not execute triggers, 0 otherwise
  1317. * @return int <0 if KO, id of created user if OK
  1318. */
  1319. public function create($user, $notrigger = 0)
  1320. {
  1321. global $conf, $langs;
  1322. global $mysoc;
  1323. // Clean parameters
  1324. $this->setUpperOrLowerCase();
  1325. $this->civility_code = trim((string) $this->civility_code);
  1326. $this->login = trim((string) $this->login);
  1327. if (!isset($this->entity)) {
  1328. $this->entity = $conf->entity; // If not defined, we use default value
  1329. }
  1330. dol_syslog(get_class($this) . "::create login=" . $this->login . ", user=" . (is_object($user) ? $user->id : ''), LOG_DEBUG);
  1331. $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',<>"\'');
  1332. // Check parameters
  1333. if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
  1334. $langs->load("errors");
  1335. $this->error = $langs->trans("ErrorBadEMail", $this->email);
  1336. return -1;
  1337. }
  1338. if (empty($this->login)) {
  1339. $langs->load("errors");
  1340. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
  1341. return -1;
  1342. } elseif (preg_match('/[' . preg_quote($badCharUnauthorizedIntoLoginName, '/') . ']/', $this->login)) {
  1343. $langs->load("errors");
  1344. $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
  1345. return -1;
  1346. }
  1347. $this->datec = dol_now();
  1348. $error = 0;
  1349. $this->db->begin();
  1350. // Check if login already exists in same entity or into entity 0.
  1351. if ($this->login) {
  1352. $sqltochecklogin = "SELECT COUNT(*) as nb FROM " . $this->db->prefix() . "user WHERE entity IN (" . $this->db->sanitize((int) $this->entity) . ", 0) AND login = '" . $this->db->escape($this->login) . "'";
  1353. $resqltochecklogin = $this->db->query($sqltochecklogin);
  1354. if ($resqltochecklogin) {
  1355. $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
  1356. if ($objtochecklogin && $objtochecklogin->nb > 0) {
  1357. $langs->load("errors");
  1358. $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
  1359. dol_syslog(get_class($this) . "::create " . $this->error, LOG_DEBUG);
  1360. $this->db->rollback();
  1361. return -6;
  1362. }
  1363. $this->db->free($resqltochecklogin);
  1364. }
  1365. }
  1366. if (!empty($this->email)) {
  1367. $sqltochecklogin = "SELECT COUNT(*) as nb FROM " . $this->db->prefix() . "user WHERE entity IN (" . $this->db->sanitize((int) $this->entity) . ", 0) AND email = '" . $this->db->escape($this->email) . "'";
  1368. $resqltochecklogin = $this->db->query($sqltochecklogin);
  1369. if ($resqltochecklogin) {
  1370. $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
  1371. if ($objtochecklogin && $objtochecklogin->nb > 0) {
  1372. $langs->load("errors");
  1373. $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
  1374. dol_syslog(get_class($this) . "::create " . $this->error, LOG_DEBUG);
  1375. $this->db->rollback();
  1376. return -6;
  1377. }
  1378. $this->db->free($resqltochecklogin);
  1379. }
  1380. }
  1381. // Insert into database
  1382. $sql = "INSERT INTO " . $this->db->prefix() . "user (datec, login, ldap_sid, entity)";
  1383. $sql .= " VALUES('" . $this->db->idate($this->datec) . "', '" . $this->db->escape($this->login) . "', '" . $this->db->escape($this->ldap_sid) . "', " . ((int) $this->entity) . ")";
  1384. $result = $this->db->query($sql);
  1385. dol_syslog(get_class($this) . "::create", LOG_DEBUG);
  1386. if ($result) {
  1387. $this->id = $this->db->last_insert_id($this->db->prefix() . "user");
  1388. // Set default rights
  1389. if ($this->set_default_rights() < 0) {
  1390. $this->error = 'ErrorFailedToSetDefaultRightOfUser';
  1391. $this->db->rollback();
  1392. return -5;
  1393. }
  1394. if (!empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER) && !empty($conf->global->STOCK_USERSTOCK_AUTOCREATE)) {
  1395. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  1396. $langs->load("stocks");
  1397. $entrepot = new Entrepot($this->db);
  1398. $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
  1399. $entrepot->libelle = $entrepot->label; // For backward compatibility
  1400. $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
  1401. $entrepot->statut = 1;
  1402. $entrepot->country_id = $mysoc->country_id;
  1403. $warehouseid = $entrepot->create($user);
  1404. $this->fk_warehouse = $warehouseid;
  1405. }
  1406. // Update minor fields
  1407. $result = $this->update($user, 1, 1);
  1408. if ($result < 0) {
  1409. $this->db->rollback();
  1410. return -4;
  1411. }
  1412. if (!$notrigger) {
  1413. // Call trigger
  1414. $result = $this->call_trigger('USER_CREATE', $user);
  1415. if ($result < 0) {
  1416. $error++;
  1417. }
  1418. // End call triggers
  1419. }
  1420. if (!$error) {
  1421. $this->db->commit();
  1422. return $this->id;
  1423. } else {
  1424. //$this->error=$interface->error;
  1425. dol_syslog(get_class($this) . "::create " . $this->error, LOG_ERR);
  1426. $this->db->rollback();
  1427. return -3;
  1428. }
  1429. } else {
  1430. $this->error = $this->db->lasterror();
  1431. $this->db->rollback();
  1432. return -2;
  1433. }
  1434. }
  1435. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1436. /**
  1437. * Create a user from a contact object. User will be internal but if contact is linked to a third party, user will be external
  1438. *
  1439. * @param Contact $contact Object for source contact
  1440. * @param string $login Login to force
  1441. * @param string $password Password to force
  1442. * @return int <0 if error, if OK returns id of created user
  1443. */
  1444. public function create_from_contact($contact, $login = '', $password = '')
  1445. {
  1446. // phpcs:enable
  1447. global $conf, $user, $langs;
  1448. $error = 0;
  1449. // Define parameters
  1450. $this->admin = 0;
  1451. $this->civility_code = $contact->civility_code;
  1452. $this->lastname = $contact->lastname;
  1453. $this->firstname = $contact->firstname;
  1454. $this->gender = $contact->gender;
  1455. $this->email = $contact->email;
  1456. $this->socialnetworks = $contact->socialnetworks;
  1457. $this->office_phone = $contact->phone_pro;
  1458. $this->office_fax = $contact->fax;
  1459. $this->user_mobile = $contact->phone_mobile;
  1460. $this->address = $contact->address;
  1461. $this->zip = $contact->zip;
  1462. $this->town = $contact->town;
  1463. $this->setUpperOrLowerCase();
  1464. $this->state_id = $contact->state_id;
  1465. $this->country_id = $contact->country_id;
  1466. $this->employee = 0;
  1467. if (empty($login)) {
  1468. include_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
  1469. $login = dol_buildlogin($contact->lastname, $contact->firstname);
  1470. }
  1471. $this->login = $login;
  1472. $this->db->begin();
  1473. // Create user and set $this->id. Trigger is disabled because executed later.
  1474. $result = $this->create($user, 1);
  1475. if ($result > 0) {
  1476. $sql = "UPDATE " . $this->db->prefix() . "user";
  1477. $sql .= " SET fk_socpeople=" . ((int) $contact->id);
  1478. $sql .= ", civility='" . $this->db->escape($contact->civility_code) . "'";
  1479. if ($contact->socid > 0) {
  1480. $sql .= ", fk_soc=" . ((int) $contact->socid);
  1481. }
  1482. $sql .= " WHERE rowid=" . ((int) $this->id);
  1483. $resql = $this->db->query($sql);
  1484. dol_syslog(get_class($this) . "::create_from_contact", LOG_DEBUG);
  1485. if ($resql) {
  1486. $this->context['createfromcontact'] = 'createfromcontact';
  1487. // Call trigger
  1488. $result = $this->call_trigger('USER_CREATE', $user);
  1489. if ($result < 0) {
  1490. $error++;
  1491. $this->db->rollback();
  1492. return -1;
  1493. }
  1494. // End call triggers
  1495. $this->db->commit();
  1496. return $this->id;
  1497. } else {
  1498. $this->error = $this->db->error();
  1499. $this->db->rollback();
  1500. return -1;
  1501. }
  1502. } else {
  1503. // $this->error deja positionne
  1504. dol_syslog(get_class($this) . "::create_from_contact - 0");
  1505. $this->db->rollback();
  1506. return $result;
  1507. }
  1508. }
  1509. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1510. /**
  1511. * Create a user into database from a member object.
  1512. * If $member->fk_soc is set, it will be an external user.
  1513. *
  1514. * @param Adherent $member Object member source
  1515. * @param string $login Login to force
  1516. * @return int <0 if KO, if OK, return id of created account
  1517. */
  1518. public function create_from_member($member, $login = '')
  1519. {
  1520. // phpcs:enable
  1521. global $conf, $user, $langs;
  1522. // Set properties on new user
  1523. $this->admin = 0;
  1524. $this->civility_code = $member->civility_id;
  1525. $this->lastname = $member->lastname;
  1526. $this->firstname = $member->firstname;
  1527. $this->gender = $member->gender;
  1528. $this->email = $member->email;
  1529. $this->fk_member = $member->id;
  1530. $this->address = $member->address;
  1531. $this->zip = $member->zip;
  1532. $this->town = $member->town;
  1533. $this->setUpperOrLowerCase();
  1534. $this->state_id = $member->state_id;
  1535. $this->country_id = $member->country_id;
  1536. $this->socialnetworks = $member->socialnetworks;
  1537. $this->pass = $member->pass;
  1538. $this->pass_crypted = $member->pass_indatabase_crypted;
  1539. if (empty($login)) {
  1540. include_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
  1541. $login = dol_buildlogin($member->lastname, $member->firstname);
  1542. }
  1543. $this->login = $login;
  1544. $this->db->begin();
  1545. // Create and set $this->id
  1546. $result = $this->create($user);
  1547. if ($result > 0) {
  1548. if (!empty($this->pass)) { // If a clear password was received (this situation should not happen anymore now), we use it to save it into database
  1549. $newpass = $this->setPassword($user, $this->pass);
  1550. if (is_numeric($newpass) && $newpass < 0) {
  1551. $result = -2;
  1552. }
  1553. } elseif (!empty($this->pass_crypted)) { // If a crypted password is already known, we save it directly into database because the previous create did not save it.
  1554. $sql = "UPDATE " . $this->db->prefix() . "user";
  1555. $sql .= " SET pass_crypted = '" . $this->db->escape($this->pass_crypted) . "'";
  1556. $sql .= " WHERE rowid=" . ((int) $this->id);
  1557. $resql = $this->db->query($sql);
  1558. if (!$resql) {
  1559. $result = -1;
  1560. }
  1561. }
  1562. if ($result > 0 && $member->fk_soc) { // If member is linked to a thirdparty
  1563. $sql = "UPDATE " . $this->db->prefix() . "user";
  1564. $sql .= " SET fk_soc=" . ((int) $member->fk_soc);
  1565. $sql .= " WHERE rowid=" . ((int) $this->id);
  1566. dol_syslog(get_class($this) . "::create_from_member", LOG_DEBUG);
  1567. $resql = $this->db->query($sql);
  1568. if ($resql) {
  1569. $this->db->commit();
  1570. return $this->id;
  1571. } else {
  1572. $this->error = $this->db->lasterror();
  1573. $this->db->rollback();
  1574. return -1;
  1575. }
  1576. }
  1577. }
  1578. if ($result > 0) {
  1579. $this->db->commit();
  1580. return $this->id;
  1581. } else {
  1582. // $this->error deja positionne
  1583. $this->db->rollback();
  1584. return -2;
  1585. }
  1586. }
  1587. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1588. /**
  1589. * Assign rights by default
  1590. *
  1591. * @return integer erreur <0, si ok renvoi le nbre de droits par defaut positionnes
  1592. */
  1593. public function set_default_rights()
  1594. {
  1595. // phpcs:enable
  1596. global $conf;
  1597. $rd = array();
  1598. $num = 0;
  1599. $sql = "SELECT id FROM " . $this->db->prefix() . "rights_def";
  1600. $sql .= " WHERE bydefault = 1";
  1601. $sql .= " AND entity = " . ((int) $conf->entity);
  1602. $resql = $this->db->query($sql);
  1603. if ($resql) {
  1604. $num = $this->db->num_rows($resql);
  1605. $i = 0;
  1606. while ($i < $num) {
  1607. $row = $this->db->fetch_row($resql);
  1608. $rd[$i] = $row[0];
  1609. $i++;
  1610. }
  1611. $this->db->free($resql);
  1612. }
  1613. $i = 0;
  1614. while ($i < $num) {
  1615. $sql = "DELETE FROM " . $this->db->prefix() . "user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
  1616. $result = $this->db->query($sql);
  1617. $sql = "INSERT INTO " . $this->db->prefix() . "user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
  1618. $result = $this->db->query($sql);
  1619. if (!$result) {
  1620. return -1;
  1621. }
  1622. $i++;
  1623. }
  1624. return $i;
  1625. }
  1626. /**
  1627. * Update a user into database (and also password if this->pass is defined)
  1628. *
  1629. * @param User $user User making update
  1630. * @param int $notrigger 1=do not execute triggers, 0 by default
  1631. * @param int $nosyncmember 0=Synchronize linked member (standard info), 1=Do not synchronize linked member
  1632. * @param int $nosyncmemberpass 0=Synchronize linked member (password), 1=Do not synchronize linked member
  1633. * @param int $nosynccontact 0=Synchronize linked contact, 1=Do not synchronize linked contact
  1634. * @return int <0 if KO, >=0 if OK
  1635. */
  1636. public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
  1637. {
  1638. global $conf, $langs;
  1639. $nbrowsaffected = 0;
  1640. $error = 0;
  1641. dol_syslog(get_class($this) . "::update notrigger=" . $notrigger . ", nosyncmember=" . $nosyncmember . ", nosyncmemberpass=" . $nosyncmemberpass);
  1642. // Clean parameters
  1643. $this->civility_code = trim((string) $this->civility_code);
  1644. $this->lastname = trim((string) $this->lastname);
  1645. $this->firstname = trim((string) $this->firstname);
  1646. $this->ref_employee = trim((string) $this->ref_employee);
  1647. $this->national_registration_number = trim((string) $this->national_registration_number);
  1648. $this->employee = ($this->employee > 0 ? $this->employee : 0);
  1649. $this->login = trim((string) $this->login);
  1650. $this->gender = trim((string) $this->gender);
  1651. $this->pass = trim((string) $this->pass);
  1652. $this->api_key = trim((string) $this->api_key);
  1653. $this->address = trim((string) $this->address);
  1654. $this->zip = trim((string) $this->zip);
  1655. $this->town = trim((string) $this->town);
  1656. $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
  1657. $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
  1658. $this->office_phone = trim((string) $this->office_phone);
  1659. $this->office_fax = trim((string) $this->office_fax);
  1660. $this->user_mobile = trim((string) $this->user_mobile);
  1661. $this->personal_mobile = trim((string) $this->personal_mobile);
  1662. $this->email = trim((string) $this->email);
  1663. $this->personal_email = trim((string) $this->personal_email);
  1664. $this->job = trim((string) $this->job);
  1665. $this->signature = trim((string) $this->signature);
  1666. $this->note_public = trim((string) $this->note_public);
  1667. $this->note_private = trim((string) $this->note_private);
  1668. $this->openid = trim((string) $this->openid);
  1669. $this->admin = ($this->admin > 0 ? $this->admin : 0);
  1670. $this->accountancy_code = trim((string) $this->accountancy_code);
  1671. $this->color = trim((string) $this->color);
  1672. $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
  1673. $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
  1674. $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
  1675. $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
  1676. $this->birth = empty($this->birth) ? '' : $this->birth;
  1677. $this->fk_warehouse = (int) $this->fk_warehouse;
  1678. $this->setUpperOrLowerCase();
  1679. // Check parameters
  1680. $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',<>"\'');
  1681. if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
  1682. $langs->load("errors");
  1683. $this->error = $langs->trans("ErrorBadEMail", $this->email);
  1684. return -1;
  1685. }
  1686. if (empty($this->login)) {
  1687. $langs->load("errors");
  1688. $this->error = $langs->trans("ErrorFieldRequired", 'Login');
  1689. return -1;
  1690. } elseif (preg_match('/[' . preg_quote($badCharUnauthorizedIntoLoginName, '/') . ']/', $this->login)) {
  1691. $langs->load("errors");
  1692. $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
  1693. return -1;
  1694. }
  1695. $this->db->begin();
  1696. // Check if login already exists in same entity or into entity 0.
  1697. if (!empty($this->oldcopy) && $this->oldcopy->login != $this->login) {
  1698. $sqltochecklogin = "SELECT COUNT(*) as nb FROM " . $this->db->prefix() . "user WHERE entity IN (" . $this->db->sanitize((int) $this->entity) . ", 0) AND login = '" . $this->db->escape($this->login) . "'";
  1699. $resqltochecklogin = $this->db->query($sqltochecklogin);
  1700. if ($resqltochecklogin) {
  1701. $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
  1702. if ($objtochecklogin && $objtochecklogin->nb > 0) {
  1703. $langs->load("errors");
  1704. $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
  1705. dol_syslog(get_class($this) . "::create " . $this->error, LOG_DEBUG);
  1706. $this->db->rollback();
  1707. return -1;
  1708. }
  1709. }
  1710. }
  1711. if (!empty($this->oldcopy) && !empty($this->email) && $this->oldcopy->email != $this->email) {
  1712. $sqltochecklogin = "SELECT COUNT(*) as nb FROM " . $this->db->prefix() . "user WHERE entity IN (" . $this->db->sanitize((int) $this->entity) . ", 0) AND email = '" . $this->db->escape($this->email) . "'";
  1713. $resqltochecklogin = $this->db->query($sqltochecklogin);
  1714. if ($resqltochecklogin) {
  1715. $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
  1716. if ($objtochecklogin && $objtochecklogin->nb > 0) {
  1717. $langs->load("errors");
  1718. $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
  1719. dol_syslog(get_class($this) . "::create " . $this->error, LOG_DEBUG);
  1720. $this->db->rollback();
  1721. return -1;
  1722. }
  1723. }
  1724. }
  1725. // Update datas
  1726. $sql = "UPDATE " . $this->db->prefix() . "user SET";
  1727. $sql .= " civility = '" . $this->db->escape($this->civility_code) . "'";
  1728. $sql .= ", lastname = '" . $this->db->escape($this->lastname) . "'";
  1729. $sql .= ", firstname = '" . $this->db->escape($this->firstname) . "'";
  1730. $sql .= ", ref_employee = '" . $this->db->escape($this->ref_employee) . "'";
  1731. $sql .= ", national_registration_number = '" . $this->db->escape($this->national_registration_number) . "'";
  1732. $sql .= ", employee = " . (int) $this->employee;
  1733. $sql .= ", login = '" . $this->db->escape($this->login) . "'";
  1734. $sql .= ", api_key = " . ($this->api_key ? "'" . $this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr')) . "'" : "null");
  1735. $sql .= ", gender = " . ($this->gender != -1 ? "'" . $this->db->escape($this->gender) . "'" : "null"); // 'man' or 'woman'
  1736. $sql .= ", birth=" . (strval($this->birth) != '' ? "'" . $this->db->idate($this->birth, 'tzserver') . "'" : 'null');
  1737. if (!empty($user->admin)) {
  1738. $sql .= ", admin = " . (int) $this->admin; // admin flag can be set/unset only by an admin user
  1739. }
  1740. $sql .= ", address = '" . $this->db->escape($this->address) . "'";
  1741. $sql .= ", zip = '" . $this->db->escape($this->zip) . "'";
  1742. $sql .= ", town = '" . $this->db->escape($this->town) . "'";
  1743. $sql .= ", fk_state = " . ((!empty($this->state_id) && $this->state_id > 0) ? "'" . $this->db->escape($this->state_id) . "'" : "null");
  1744. $sql .= ", fk_country = " . ((!empty($this->country_id) && $this->country_id > 0) ? "'" . $this->db->escape($this->country_id) . "'" : "null");
  1745. $sql .= ", office_phone = '" . $this->db->escape($this->office_phone) . "'";
  1746. $sql .= ", office_fax = '" . $this->db->escape($this->office_fax) . "'";
  1747. $sql .= ", user_mobile = '" . $this->db->escape($this->user_mobile) . "'";
  1748. $sql .= ", personal_mobile = '" . $this->db->escape($this->personal_mobile) . "'";
  1749. $sql .= ", email = '" . $this->db->escape($this->email) . "'";
  1750. $sql .= ", personal_email = '" . $this->db->escape($this->personal_email) . "'";
  1751. $sql .= ", socialnetworks = '" . $this->db->escape(json_encode($this->socialnetworks)) . "'";
  1752. $sql .= ", job = '" . $this->db->escape($this->job) . "'";
  1753. $sql .= ", signature = '" . $this->db->escape($this->signature) . "'";
  1754. $sql .= ", accountancy_code = '" . $this->db->escape($this->accountancy_code) . "'";
  1755. $sql .= ", color = '" . $this->db->escape($this->color) . "'";
  1756. $sql .= ", dateemployment=" . (strval($this->dateemployment) != '' ? "'" . $this->db->idate($this->dateemployment) . "'" : 'null');
  1757. $sql .= ", dateemploymentend=" . (strval($this->dateemploymentend) != '' ? "'" . $this->db->idate($this->dateemploymentend) . "'" : 'null');
  1758. $sql .= ", datestartvalidity=" . (strval($this->datestartvalidity) != '' ? "'" . $this->db->idate($this->datestartvalidity) . "'" : 'null');
  1759. $sql .= ", dateendvalidity=" . (strval($this->dateendvalidity) != '' ? "'" . $this->db->idate($this->dateendvalidity) . "'" : 'null');
  1760. $sql .= ", note_private = '" . $this->db->escape($this->note_private) . "'";
  1761. $sql .= ", note_public = '" . $this->db->escape($this->note_public) . "'";
  1762. $sql .= ", photo = " . ($this->photo ? "'" . $this->db->escape($this->photo) . "'" : "null");
  1763. $sql .= ", openid = " . ($this->openid ? "'" . $this->db->escape($this->openid) . "'" : "null");
  1764. $sql .= ", fk_user = " . ($this->fk_user > 0 ? "'" . $this->db->escape($this->fk_user) . "'" : "null");
  1765. $sql .= ", fk_user_expense_validator = " . ($this->fk_user_expense_validator > 0 ? "'" . $this->db->escape($this->fk_user_expense_validator) . "'" : "null");
  1766. $sql .= ", fk_user_holiday_validator = " . ($this->fk_user_holiday_validator > 0 ? "'" . $this->db->escape($this->fk_user_holiday_validator) . "'" : "null");
  1767. if (isset($this->thm) || $this->thm != '') {
  1768. $sql .= ", thm= " . ($this->thm != '' ? "'" . $this->db->escape($this->thm) . "'" : "null");
  1769. }
  1770. if (isset($this->tjm) || $this->tjm != '') {
  1771. $sql .= ", tjm= " . ($this->tjm != '' ? "'" . $this->db->escape($this->tjm) . "'" : "null");
  1772. }
  1773. if (isset($this->salary) || $this->salary != '') {
  1774. $sql .= ", salary= " . ($this->salary != '' ? "'" . $this->db->escape($this->salary) . "'" : "null");
  1775. }
  1776. if (isset($this->salaryextra) || $this->salaryextra != '') {
  1777. $sql .= ", salaryextra= " . ($this->salaryextra != '' ? "'" . $this->db->escape($this->salaryextra) . "'" : "null");
  1778. }
  1779. $sql .= ", weeklyhours= " . ($this->weeklyhours != '' ? "'" . $this->db->escape($this->weeklyhours) . "'" : "null");
  1780. if (!empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
  1781. $sql .= ", entity = " . ((int) $this->entity); // entity flag can be set/unset only by an another superadmin user
  1782. }
  1783. $sql .= ", default_range = " . ($this->default_range > 0 ? $this->default_range : 'null');
  1784. $sql .= ", default_c_exp_tax_cat = " . ($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
  1785. $sql .= ", fk_warehouse = " . ($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
  1786. $sql .= ", lang = " . ($this->lang ? "'" . $this->db->escape($this->lang) . "'" : "null");
  1787. $sql .= " WHERE rowid = " . ((int) $this->id);
  1788. dol_syslog(get_class($this) . "::update", LOG_DEBUG);
  1789. $resql = $this->db->query($sql);
  1790. if ($resql) {
  1791. $nbrowsaffected += $this->db->affected_rows($resql);
  1792. // Update password
  1793. if (!empty($this->pass)) {
  1794. if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
  1795. // If a new value for password is set and different than the one crypted into database
  1796. $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
  1797. if ($result < 0) {
  1798. return -5;
  1799. }
  1800. }
  1801. }
  1802. // If user is linked to a member, remove old link to this member
  1803. if ($this->fk_member > 0) {
  1804. dol_syslog(get_class($this) . "::update remove link with member. We will recreate it later", LOG_DEBUG);
  1805. $sql = "UPDATE " . $this->db->prefix() . "user SET fk_member = NULL where fk_member = " . ((int) $this->fk_member);
  1806. $resql = $this->db->query($sql);
  1807. if (!$resql) {
  1808. $this->error = $this->db->error();
  1809. $this->db->rollback();
  1810. return -5;
  1811. }
  1812. }
  1813. // Set link to user
  1814. dol_syslog(get_class($this) . "::update set link with member", LOG_DEBUG);
  1815. $sql = "UPDATE " . $this->db->prefix() . "user SET fk_member =" . ($this->fk_member > 0 ? ((int) $this->fk_member) : 'null') . " where rowid = " . ((int) $this->id);
  1816. $resql = $this->db->query($sql);
  1817. if (!$resql) {
  1818. $this->error = $this->db->error();
  1819. $this->db->rollback();
  1820. return -5;
  1821. }
  1822. if ($nbrowsaffected) { // If something has changed in data
  1823. if ($this->fk_member > 0 && !$nosyncmember) {
  1824. dol_syslog(get_class($this) . "::update user is linked with a member. We try to update member too.", LOG_DEBUG);
  1825. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  1826. // This user is linked with a member, so we also update member information
  1827. // if this is an update.
  1828. $adh = new Adherent($this->db);
  1829. $result = $adh->fetch($this->fk_member);
  1830. if ($result > 0) {
  1831. $adh->civility_code = $this->civility_code;
  1832. $adh->firstname = $this->firstname;
  1833. $adh->lastname = $this->lastname;
  1834. $adh->login = $this->login;
  1835. $adh->gender = $this->gender;
  1836. $adh->birth = $this->birth;
  1837. $adh->pass = $this->pass;
  1838. $adh->address = $this->address;
  1839. $adh->town = $this->town;
  1840. $adh->zip = $this->zip;
  1841. $adh->state_id = $this->state_id;
  1842. $adh->country_id = $this->country_id;
  1843. $adh->email = $this->email;
  1844. $adh->socialnetworks = $this->socialnetworks;
  1845. $adh->phone = $this->office_phone;
  1846. $adh->phone_mobile = $this->user_mobile;
  1847. $adh->default_lang = $this->lang;
  1848. $adh->user_id = $this->id;
  1849. $adh->user_login = $this->login;
  1850. $result = $adh->update($user, 0, 1, 0);
  1851. if ($result < 0) {
  1852. $this->error = $adh->error;
  1853. $this->errors = $adh->errors;
  1854. dol_syslog(get_class($this) . "::update error after calling adh->update to sync it with user: " . $this->error, LOG_ERR);
  1855. $error++;
  1856. }
  1857. } elseif ($result < 0) {
  1858. $this->error = $adh->error;
  1859. $this->errors = $adh->errors;
  1860. $error++;
  1861. }
  1862. }
  1863. if ($this->contact_id > 0 && !$nosynccontact) {
  1864. dol_syslog(get_class($this) . "::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
  1865. require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  1866. // This user is linked with a contact, so we also update contact information if this is an update.
  1867. $tmpobj = new Contact($this->db);
  1868. $result = $tmpobj->fetch($this->contact_id);
  1869. if ($result >= 0) {
  1870. $tmpobj->civility_code = $this->civility_code;
  1871. $tmpobj->firstname = $this->firstname;
  1872. $tmpobj->lastname = $this->lastname;
  1873. $tmpobj->login = $this->login;
  1874. $tmpobj->gender = $this->gender;
  1875. $tmpobj->birth = $this->birth;
  1876. //$tmpobj->pass=$this->pass;
  1877. $tmpobj->email = $this->email;
  1878. $tmpobj->socialnetworks = $this->socialnetworks;
  1879. $tmpobj->phone_pro = $this->office_phone;
  1880. $tmpobj->phone_mobile = $this->user_mobile;
  1881. $tmpobj->fax = $this->office_fax;
  1882. $tmpobj->default_lang = $this->lang;
  1883. $tmpobj->address = $this->address;
  1884. $tmpobj->town = $this->town;
  1885. $tmpobj->zip = $this->zip;
  1886. $tmpobj->state_id = $this->state_id;
  1887. $tmpobj->country_id = $this->country_id;
  1888. $tmpobj->user_id = $this->id;
  1889. $tmpobj->user_login = $this->login;
  1890. $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
  1891. if ($result < 0) {
  1892. $this->error = $tmpobj->error;
  1893. $this->errors = $tmpobj->errors;
  1894. dol_syslog(get_class($this) . "::update error after calling adh->update to sync it with user: " . $this->error, LOG_ERR);
  1895. $error++;
  1896. }
  1897. } else {
  1898. $this->error = $tmpobj->error;
  1899. $this->errors = $tmpobj->errors;
  1900. $error++;
  1901. }
  1902. }
  1903. }
  1904. $action = 'update';
  1905. // Actions on extra fields
  1906. if (!$error) {
  1907. $result = $this->insertExtraFields();
  1908. if ($result < 0) {
  1909. $error++;
  1910. }
  1911. }
  1912. if (!$error && !$notrigger) {
  1913. // Call trigger
  1914. $result = $this->call_trigger('USER_MODIFY', $user);
  1915. if ($result < 0) {
  1916. $error++;
  1917. }
  1918. // End call triggers
  1919. }
  1920. if (!$error) {
  1921. $this->db->commit();
  1922. return $nbrowsaffected;
  1923. } else {
  1924. dol_syslog(get_class($this) . "::update error=" . $this->error, LOG_ERR);
  1925. $this->db->rollback();
  1926. return -1;
  1927. }
  1928. } else {
  1929. $this->error = $this->db->lasterror();
  1930. $this->db->rollback();
  1931. return -2;
  1932. }
  1933. }
  1934. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1935. /**
  1936. * Mise a jour en base de la date de derniere connexion d'un utilisateur
  1937. * Fonction appelee lors d'une nouvelle connexion
  1938. *
  1939. * @return int <0 si echec, >=0 si ok
  1940. */
  1941. public function update_last_login_date()
  1942. {
  1943. // phpcs:enable
  1944. $now = dol_now();
  1945. $userremoteip = getUserRemoteIP();
  1946. $sql = "UPDATE " . $this->db->prefix() . "user SET";
  1947. $sql .= " datepreviouslogin = datelastlogin,";
  1948. $sql .= " ippreviouslogin = iplastlogin,";
  1949. $sql .= " datelastlogin = '" . $this->db->idate($now) . "',";
  1950. $sql .= " iplastlogin = '" . $this->db->escape($userremoteip) . "',";
  1951. $sql .= " tms = tms"; // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
  1952. $sql .= " WHERE rowid = " . ((int) $this->id);
  1953. dol_syslog(get_class($this) . "::update_last_login_date user->id=" . $this->id . " " . $sql, LOG_DEBUG);
  1954. $resql = $this->db->query($sql);
  1955. if ($resql) {
  1956. $this->datepreviouslogin = $this->datelastlogin;
  1957. $this->datelastlogin = $now;
  1958. $this->ippreviouslogin = $this->iplastlogin;
  1959. $this->iplastlogin = $userremoteip;
  1960. return 1;
  1961. } else {
  1962. $this->error = $this->db->lasterror() . ' sql=' . $sql;
  1963. return -1;
  1964. }
  1965. }
  1966. /**
  1967. * Change password of a user
  1968. *
  1969. * @param User $user Object user of user requesting the change (not the user for who we change the password). May be unknown.
  1970. * @param string $password New password, in clear text or already encrypted (to generate if not provided)
  1971. * @param int $changelater 0=Default, 1=Save password into pass_temp to change password only after clicking on confirm email
  1972. * @param int $notrigger 1=Does not launch triggers
  1973. * @param int $nosyncmember Do not synchronize linked member
  1974. * @param int $passwordalreadycrypted 0=Value is cleartext password, 1=Value is crypted value.
  1975. * @return string If OK return clear password, 0 if no change (warning, you may retreive 1 instead of 0 even if password was same), < 0 if error
  1976. */
  1977. public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0)
  1978. {
  1979. global $conf, $langs;
  1980. require_once DOL_DOCUMENT_ROOT . '/core/lib/security2.lib.php';
  1981. $error = 0;
  1982. dol_syslog(get_class($this) . "::setPassword user=" . $user->id . " password=" . preg_replace('/./i', '*', $password) . " changelater=" . $changelater . " notrigger=" . $notrigger . " nosyncmember=" . $nosyncmember, LOG_DEBUG);
  1983. // If new password not provided, we generate one
  1984. if (!$password) {
  1985. $password = getRandomPassword(false);
  1986. }
  1987. // Check and encrypt the password
  1988. if (empty($passwordalreadycrypted)) {
  1989. if (!empty($conf->global->USER_PASSWORD_GENERATED)) {
  1990. // Add a check on rules for password syntax using the setup of the password generator
  1991. $modGeneratePassClass = 'modGeneratePass' . ucfirst($conf->global->USER_PASSWORD_GENERATED);
  1992. include_once DOL_DOCUMENT_ROOT . '/core/modules/security/generate/' . $modGeneratePassClass . '.class.php';
  1993. if (class_exists($modGeneratePassClass)) {
  1994. $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
  1995. // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
  1996. $modGeneratePass->WithoutAmbi = 0;
  1997. // Call to validatePassword($password) to check pass match rules
  1998. $testpassword = $modGeneratePass->validatePassword($password);
  1999. if (!$testpassword) {
  2000. $this->error = $modGeneratePass->error;
  2001. return -1;
  2002. }
  2003. }
  2004. }
  2005. // Now, we encrypt the new password
  2006. $password_crypted = dol_hash($password);
  2007. }
  2008. // Update password
  2009. if (!$changelater) {
  2010. if (!is_object($this->oldcopy)) {
  2011. $this->oldcopy = clone $this;
  2012. }
  2013. $this->db->begin();
  2014. $sql = "UPDATE " . $this->db->prefix() . "user";
  2015. $sql .= " SET pass_crypted = '" . $this->db->escape($password_crypted) . "',";
  2016. $sql .= " pass_temp = null";
  2017. if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
  2018. $sql .= ", pass = null";
  2019. } else {
  2020. $sql .= ", pass = '" . $this->db->escape($password) . "'";
  2021. }
  2022. $sql .= " WHERE rowid = " . ((int) $this->id);
  2023. dol_syslog(get_class($this) . "::setPassword", LOG_DEBUG);
  2024. $result = $this->db->query($sql);
  2025. if ($result) {
  2026. if ($this->db->affected_rows($result)) {
  2027. $this->pass = $password;
  2028. $this->pass_indatabase = $password;
  2029. $this->pass_indatabase_crypted = $password_crypted;
  2030. if ($this->fk_member && !$nosyncmember) {
  2031. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  2032. // This user is linked with a member, so we also update members informations
  2033. // if this is an update.
  2034. $adh = new Adherent($this->db);
  2035. $result = $adh->fetch($this->fk_member);
  2036. if ($result >= 0) {
  2037. $result = $adh->setPassword($user, $this->pass, (empty($conf->global->DATABASE_PWD_ENCRYPTED) ? 0 : 1), 1); // Cryptage non gere dans module adherent
  2038. if ($result < 0) {
  2039. $this->error = $adh->error;
  2040. dol_syslog(get_class($this) . "::setPassword " . $this->error, LOG_ERR);
  2041. $error++;
  2042. }
  2043. } else {
  2044. $this->error = $adh->error;
  2045. $error++;
  2046. }
  2047. }
  2048. dol_syslog(get_class($this) . "::setPassword notrigger=" . $notrigger . " error=" . $error, LOG_DEBUG);
  2049. if (!$error && !$notrigger) {
  2050. // Call trigger
  2051. $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
  2052. if ($result < 0) {
  2053. $error++;
  2054. $this->db->rollback();
  2055. return -1;
  2056. }
  2057. // End call triggers
  2058. }
  2059. $this->db->commit();
  2060. return $this->pass;
  2061. } else {
  2062. $this->db->rollback();
  2063. return 0;
  2064. }
  2065. } else {
  2066. $this->db->rollback();
  2067. dol_print_error($this->db);
  2068. return -1;
  2069. }
  2070. } else {
  2071. // We store password in password temporary field.
  2072. // After receiving confirmation link, we will erase and store it in pass_crypted
  2073. $sql = "UPDATE " . $this->db->prefix() . "user";
  2074. $sql .= " SET pass_temp = '" . $this->db->escape($password) . "'";
  2075. $sql .= " WHERE rowid = " . ((int) $this->id);
  2076. dol_syslog(get_class($this) . "::setPassword", LOG_DEBUG); // No log
  2077. $result = $this->db->query($sql);
  2078. if ($result) {
  2079. return $password;
  2080. } else {
  2081. dol_print_error($this->db);
  2082. return -3;
  2083. }
  2084. }
  2085. }
  2086. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2087. /**
  2088. * Send new password by email
  2089. *
  2090. * @param User $user Object user that send the email (not the user we send to) @todo object $user is not used !
  2091. * @param string $password New password
  2092. * @param int $changelater 0=Send clear passwod into email, 1=Change password only after clicking on confirm email. @todo Add method 2 = Send link to reset password
  2093. * @return int < 0 si erreur, > 0 si ok
  2094. */
  2095. public function send_password($user, $password = '', $changelater = 0)
  2096. {
  2097. // phpcs:enable
  2098. global $conf, $langs, $mysoc;
  2099. global $dolibarr_main_url_root;
  2100. require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
  2101. $msgishtml = 0;
  2102. // Define $msg
  2103. $mesg = '';
  2104. $outputlangs = new Translate("", $conf);
  2105. if (
  2106. isset($this->conf->MAIN_LANG_DEFAULT)
  2107. && $this->conf->MAIN_LANG_DEFAULT != 'auto'
  2108. ) { // If user has defined its own language (rare because in most cases, auto is used)
  2109. $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
  2110. }
  2111. if ($this->conf->MAIN_LANG_DEFAULT) {
  2112. $outputlangs->setDefaultLang($this->conf->MAIN_LANG_DEFAULT);
  2113. } else { // If user has not defined its own language, we used current language
  2114. $outputlangs = $langs;
  2115. }
  2116. // Load translation files required by the page
  2117. $outputlangs->loadLangs(array("main", "errors", "users", "other"));
  2118. $appli = constant('DOL_APPLICATION_TITLE');
  2119. if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
  2120. $appli = $conf->global->MAIN_APPLICATION_TITLE;
  2121. }
  2122. $subject = '[' . $mysoc->name . '] ' . $outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
  2123. // Define $urlwithroot
  2124. $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($dolibarr_main_url_root));
  2125. $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT; // This is to use external domain name found into config file
  2126. if (!$changelater) {
  2127. $url = $urlwithroot . '/';
  2128. if (!empty($conf->global->URL_REDIRECTION_AFTER_CHANGEPASSWORD))
  2129. $url = $conf->global->URL_REDIRECTION_AFTER_CHANGEPASSWORD;
  2130. $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived") . ".\n";
  2131. $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs") . " :\n\n";
  2132. $mesg .= $outputlangs->transnoentitiesnoconv("Login") . " = " . $this->login . "\n";
  2133. $mesg .= $outputlangs->transnoentitiesnoconv("Password") . " = " . $password . "\n\n";
  2134. $mesg .= "\n";
  2135. $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli) . ': ' . $url . "\n\n";
  2136. $mesg .= "--\n";
  2137. $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
  2138. dol_syslog(get_class($this) . "::send_password changelater is off, url=" . $url);
  2139. } else {
  2140. global $dolibarr_main_instance_unique_id;
  2141. //print $password.'-'.$this->id.'-'.$dolibarr_main_instance_unique_id;
  2142. $url = $urlwithroot . '/user/passwordforgotten.php?action=validatenewpassword';
  2143. $url .= '&username=' . urlencode($this->login) . "&passworduidhash=" . urlencode(dol_hash($password . '-' . $this->id . '-' . $dolibarr_main_instance_unique_id));
  2144. if (!empty($conf->multicompany->enabled)) {
  2145. $url .= '&entity=' . (!empty($this->entity) ? $this->entity : 1);
  2146. }
  2147. $msgishtml = 1;
  2148. $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived") . "<br>\n";
  2149. $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe") . " :<br>\n<br>\n";
  2150. $mesg .= '<strong>' . $outputlangs->transnoentitiesnoconv("Login") . "</strong> = " . $this->login . "<br>\n";
  2151. $mesg .= '<strong>' . $outputlangs->transnoentitiesnoconv("Password") . "</strong> = " . $password . "<br>\n<br>\n";
  2152. $mesg .= "<br>\n";
  2153. $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange") . " :<br>\n";
  2154. $mesg .= '<a href="' . $url . '" rel="noopener">' . $outputlangs->transnoentitiesnoconv("ConfirmPasswordChange") . '</a>' . "<br>\n<br>\n";
  2155. $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing") . "<br>\n<br>\n";
  2156. dol_syslog(get_class($this) . "::send_password changelater is on, url=" . $url);
  2157. }
  2158. $trackid = 'use' . $this->id;
  2159. $mailfile = new CMailFile(
  2160. $subject,
  2161. $this->email,
  2162. $conf->global->MAIN_MAIL_EMAIL_FROM,
  2163. $mesg,
  2164. array(),
  2165. array(),
  2166. array(),
  2167. '',
  2168. '',
  2169. 0,
  2170. $msgishtml,
  2171. '',
  2172. '',
  2173. $trackid
  2174. );
  2175. if ($mailfile->sendfile()) {
  2176. return 1;
  2177. } else {
  2178. $langs->trans("errors");
  2179. $this->error = $langs->trans("ErrorFailedToSendPassword") . ' ' . $mailfile->error;
  2180. return -1;
  2181. }
  2182. }
  2183. /**
  2184. * Renvoie la derniere erreur fonctionnelle de manipulation de l'objet
  2185. *
  2186. * @return string chaine erreur
  2187. */
  2188. public function error()
  2189. {
  2190. return $this->error;
  2191. }
  2192. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2193. /**
  2194. * Read clicktodial information for user
  2195. *
  2196. * @return int <0 if KO, >0 if OK
  2197. */
  2198. public function fetch_clicktodial()
  2199. {
  2200. // phpcs:enable
  2201. $sql = "SELECT url, login, pass, poste ";
  2202. $sql .= " FROM " . $this->db->prefix() . "user_clicktodial as u";
  2203. $sql .= " WHERE u.fk_user = " . ((int) $this->id);
  2204. $resql = $this->db->query($sql);
  2205. if ($resql) {
  2206. if ($this->db->num_rows($resql)) {
  2207. $obj = $this->db->fetch_object($resql);
  2208. $this->clicktodial_url = $obj->url;
  2209. $this->clicktodial_login = $obj->login;
  2210. $this->clicktodial_password = $obj->pass;
  2211. $this->clicktodial_poste = $obj->poste;
  2212. }
  2213. $this->clicktodial_loaded = 1; // Data loaded (found or not)
  2214. $this->db->free($resql);
  2215. return 1;
  2216. } else {
  2217. $this->error = $this->db->error();
  2218. return -1;
  2219. }
  2220. }
  2221. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2222. /**
  2223. * Update clicktodial info
  2224. *
  2225. * @return int <0 if KO, >0 if OK
  2226. */
  2227. public function update_clicktodial()
  2228. {
  2229. // phpcs:enable
  2230. $this->db->begin();
  2231. $sql = "DELETE FROM " . $this->db->prefix() . "user_clicktodial";
  2232. $sql .= " WHERE fk_user = " . ((int) $this->id);
  2233. dol_syslog(get_class($this) . '::update_clicktodial', LOG_DEBUG);
  2234. $result = $this->db->query($sql);
  2235. $sql = "INSERT INTO " . $this->db->prefix() . "user_clicktodial";
  2236. $sql .= " (fk_user,url,login,pass,poste)";
  2237. $sql .= " VALUES (" . $this->id;
  2238. $sql .= ", '" . $this->db->escape($this->clicktodial_url) . "'";
  2239. $sql .= ", '" . $this->db->escape($this->clicktodial_login) . "'";
  2240. $sql .= ", '" . $this->db->escape($this->clicktodial_password) . "'";
  2241. $sql .= ", '" . $this->db->escape($this->clicktodial_poste) . "')";
  2242. dol_syslog(get_class($this) . '::update_clicktodial', LOG_DEBUG);
  2243. $result = $this->db->query($sql);
  2244. if ($result) {
  2245. $this->db->commit();
  2246. return 1;
  2247. } else {
  2248. $this->db->rollback();
  2249. $this->error = $this->db->lasterror();
  2250. return -1;
  2251. }
  2252. }
  2253. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2254. /**
  2255. * Add user into a group
  2256. *
  2257. * @param int $group Id of group
  2258. * @param int $entity Entity
  2259. * @param int $notrigger Disable triggers
  2260. * @return int <0 if KO, >0 if OK
  2261. */
  2262. public function SetInGroup($group, $entity, $notrigger = 0)
  2263. {
  2264. // phpcs:enable
  2265. global $conf, $langs, $user;
  2266. $error = 0;
  2267. $this->db->begin();
  2268. $sql = "DELETE FROM " . $this->db->prefix() . "usergroup_user";
  2269. $sql .= " WHERE fk_user = " . ((int) $this->id);
  2270. $sql .= " AND fk_usergroup = " . ((int) $group);
  2271. $sql .= " AND entity = " . ((int) $entity);
  2272. $result = $this->db->query($sql);
  2273. $sql = "INSERT INTO " . $this->db->prefix() . "usergroup_user (entity, fk_user, fk_usergroup)";
  2274. $sql .= " VALUES (" . ((int) $entity) . "," . ((int) $this->id) . "," . ((int) $group) . ")";
  2275. $result = $this->db->query($sql);
  2276. if ($result) {
  2277. if (!$error && !$notrigger) {
  2278. $this->newgroupid = $group; // deprecated. Remove this.
  2279. $this->context = array('audit' => $langs->trans("UserSetInGroup"), 'newgroupid' => $group);
  2280. // Call trigger
  2281. $result = $this->call_trigger('USER_MODIFY', $user);
  2282. if ($result < 0) {
  2283. $error++;
  2284. }
  2285. // End call triggers
  2286. }
  2287. if (!$error) {
  2288. $this->db->commit();
  2289. return 1;
  2290. } else {
  2291. dol_syslog(get_class($this) . "::SetInGroup " . $this->error, LOG_ERR);
  2292. $this->db->rollback();
  2293. return -2;
  2294. }
  2295. } else {
  2296. $this->error = $this->db->lasterror();
  2297. $this->db->rollback();
  2298. return -1;
  2299. }
  2300. }
  2301. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2302. /**
  2303. * Remove a user from a group
  2304. *
  2305. * @param int $group Id of group
  2306. * @param int $entity Entity
  2307. * @param int $notrigger Disable triggers
  2308. * @return int <0 if KO, >0 if OK
  2309. */
  2310. public function RemoveFromGroup($group, $entity, $notrigger = 0)
  2311. {
  2312. // phpcs:enable
  2313. global $conf, $langs, $user;
  2314. $error = 0;
  2315. $this->db->begin();
  2316. $sql = "DELETE FROM " . $this->db->prefix() . "usergroup_user";
  2317. $sql .= " WHERE fk_user = " . ((int) $this->id);
  2318. $sql .= " AND fk_usergroup = " . ((int) $group);
  2319. $sql .= " AND entity = " . ((int) $entity);
  2320. $result = $this->db->query($sql);
  2321. if ($result) {
  2322. if (!$error && !$notrigger) {
  2323. $this->oldgroupid = $group; // deprecated. Remove this.
  2324. $this->context = array('audit' => $langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
  2325. // Call trigger
  2326. $result = $this->call_trigger('USER_MODIFY', $user);
  2327. if ($result < 0) {
  2328. $error++;
  2329. }
  2330. // End call triggers
  2331. }
  2332. if (!$error) {
  2333. $this->db->commit();
  2334. return 1;
  2335. } else {
  2336. dol_syslog(get_class($this) . "::RemoveFromGroup " . $this->error, LOG_ERR);
  2337. $this->db->rollback();
  2338. return -2;
  2339. }
  2340. } else {
  2341. $this->error = $this->db->lasterror();
  2342. $this->db->rollback();
  2343. return -1;
  2344. }
  2345. }
  2346. /**
  2347. * Return a link with photo
  2348. * Use this->id,this->photo
  2349. *
  2350. * @param int $width Width of image
  2351. * @param int $height Height of image
  2352. * @param string $cssclass Force a css class
  2353. * @param string $imagesize 'mini', 'small' or '' (original)
  2354. * @return string String with URL link
  2355. */
  2356. public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
  2357. {
  2358. $result = '<a href="' . DOL_URL_ROOT . '/user/card.php?id=' . $this->id . '">';
  2359. $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
  2360. $result .= '</a>';
  2361. return $result;
  2362. }
  2363. /**
  2364. * Return a HTML link to the user card (with optionaly the picto)
  2365. * Use this->id,this->lastname, this->firstname
  2366. *
  2367. * @param int $withpictoimg Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto, -1=Include photo into link, -2=Only picto photo, -3=Only photo very small)
  2368. * @param string $option On what the link point to ('leave', 'accountancy', 'nolink', )
  2369. * @param integer $infologin 0=Add default info tooltip, 1=Add complete info tooltip, -1=No info tooltip
  2370. * @param integer $notooltip 1=Disable tooltip on picto and name
  2371. * @param int $maxlen Max length of visible user name
  2372. * @param int $hidethirdpartylogo Hide logo of thirdparty if user is external user
  2373. * @param string $mode ''=Show firstname and lastname, 'firstname'=Show only firstname, 'firstelselast'=Show firstname or lastname if not defined, 'login'=Show login
  2374. * @param string $morecss Add more css on link
  2375. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  2376. * @return string String with URL
  2377. */
  2378. public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
  2379. {
  2380. global $langs, $conf, $db, $hookmanager, $user;
  2381. global $dolibarr_main_authentication, $dolibarr_main_demo;
  2382. global $menumanager;
  2383. if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
  2384. $option = 'nolink';
  2385. }
  2386. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) {
  2387. $withpictoimg = 0;
  2388. }
  2389. $result = '';
  2390. $label = '';
  2391. $companylink = '';
  2392. if (!empty($this->photo)) {
  2393. $label .= '<div class="photointooltip floatright">';
  2394. $label .= Form::showphoto('userphoto', $this, 0, 60, 0, 'photoref photowithmargin photologintooltip', 'small', 0, 1); // Force height to 60 so we total height of tooltip can be calculated and collision can be managed
  2395. $label .= '</div>';
  2396. //$label .= '<div style="clear: both;"></div>';
  2397. }
  2398. // Info Login
  2399. $label .= '<div class="centpercent">';
  2400. $label .= img_picto('', $this->picto) . ' <u class="paddingrightonly">' . $langs->trans("User") . '</u>';
  2401. $label .= ' ' . $this->getLibStatut(4);
  2402. $label .= '<br><b>' . $langs->trans('Name') . ':</b> ' . dol_string_nohtmltag($this->getFullName($langs, ''));
  2403. if (!empty($this->login)) {
  2404. $label .= '<br><b>' . $langs->trans('Login') . ':</b> ' . dol_string_nohtmltag($this->login);
  2405. }
  2406. if (!empty($this->job)) {
  2407. $label .= '<br><b>' . $langs->trans("Job") . ':</b> ' . dol_string_nohtmltag($this->job);
  2408. }
  2409. $label .= '<br><b>' . $langs->trans("Email") . ':</b> ' . dol_string_nohtmltag($this->email);
  2410. if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
  2411. $phonelist = array();
  2412. if ($this->office_phone) {
  2413. $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
  2414. }
  2415. if ($this->office_fax) {
  2416. $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
  2417. }
  2418. if ($this->user_mobile) {
  2419. $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
  2420. }
  2421. $label .= '<br><b>' . $langs->trans('Phone') . ':</b> ' . implode('&nbsp;', $phonelist);
  2422. }
  2423. if (!empty($this->admin)) {
  2424. $label .= '<br><b>' . $langs->trans("Administrator") . '</b>: ' . yn($this->admin);
  2425. }
  2426. if (!empty($this->accountancy_code) || $option == 'accountancy') {
  2427. $label .= '<br><b>' . $langs->trans("AccountancyCode") . '</b>: ' . $this->accountancy_code;
  2428. }
  2429. $company = '';
  2430. if (!empty($this->socid)) { // Add thirdparty for external users
  2431. $thirdpartystatic = new Societe($db);
  2432. $thirdpartystatic->fetch($this->socid);
  2433. if (empty($hidethirdpartylogo)) {
  2434. $companylink = ' ' . $thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
  2435. }
  2436. $company = ' (' . $langs->trans("Company") . ': ' . img_picto('', 'company') . ' ' . dol_string_nohtmltag($thirdpartystatic->name) . ')';
  2437. }
  2438. $type = ($this->socid ? $langs->trans("ExternalUser") . $company : $langs->trans("InternalUser"));
  2439. $label .= '<br><b>' . $langs->trans("Type") . ':</b> ' . $type;
  2440. $label .= '</div>';
  2441. if ($infologin > 0) {
  2442. $label .= '<br>';
  2443. $label .= '<br><u>' . $langs->trans("Session") . '</u>';
  2444. $label .= '<br><b>' . $langs->trans("IPAddress") . '</b>: ' . dol_string_nohtmltag(getUserRemoteIP());
  2445. if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) {
  2446. $label .= '<br><b>' . $langs->trans("ConnectedOnMultiCompany") . ':</b> ' . $conf->entity . ' (User entity ' . $this->entity . ')';
  2447. }
  2448. $label .= '<br><b>' . $langs->trans("AuthenticationMode") . ':</b> ' . dol_string_nohtmltag($_SESSION["dol_authmode"] . (empty($dolibarr_main_demo) ? '' : ' (demo)'));
  2449. $label .= '<br><b>' . $langs->trans("ConnectedSince") . ':</b> ' . dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
  2450. $label .= '<br><b>' . $langs->trans("PreviousConnexion") . ':</b> ' . dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
  2451. $label .= '<br><b>' . $langs->trans("CurrentTheme") . ':</b> ' . dol_string_nohtmltag($conf->theme);
  2452. $label .= '<br><b>' . $langs->trans("CurrentMenuManager") . ':</b> ' . dol_string_nohtmltag($menumanager->name);
  2453. $s = picto_from_langcode($langs->getDefaultLang());
  2454. $label .= '<br><b>' . $langs->trans("CurrentUserLanguage") . ':</b> ' . dol_string_nohtmltag(($s ? $s . ' ' : '') . $langs->getDefaultLang());
  2455. $label .= '<br><b>' . $langs->trans("Browser") . ':</b> ' . dol_string_nohtmltag($conf->browser->name . ($conf->browser->version ? ' ' . $conf->browser->version : '') . ' (' . $_SERVER['HTTP_USER_AGENT'] . ')');
  2456. $label .= '<br><b>' . $langs->trans("Layout") . ':</b> ' . dol_string_nohtmltag($conf->browser->layout);
  2457. $label .= '<br><b>' . $langs->trans("Screen") . ':</b> ' . dol_string_nohtmltag($_SESSION['dol_screenwidth'] . ' x ' . $_SESSION['dol_screenheight']);
  2458. if ($conf->browser->layout == 'phone') {
  2459. $label .= '<br><b>' . $langs->trans("Phone") . ':</b> ' . $langs->trans("Yes");
  2460. }
  2461. if (!empty($_SESSION["disablemodules"])) {
  2462. $label .= '<br><b>' . $langs->trans("DisabledModules") . ':</b> <br>' . dol_string_nohtmltag(join(', ', explode(',', $_SESSION["disablemodules"])));
  2463. }
  2464. }
  2465. if ($infologin < 0) {
  2466. $label = '';
  2467. }
  2468. $url = DOL_URL_ROOT . '/user/card.php?id=' . $this->id;
  2469. if ($option == 'leave') {
  2470. $url = DOL_URL_ROOT . '/holiday/list.php?id=' . $this->id;
  2471. }
  2472. if ($option != 'nolink') {
  2473. // Add param to save lastsearch_values or not
  2474. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  2475. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  2476. $add_save_lastsearch_values = 1;
  2477. }
  2478. if ($add_save_lastsearch_values) {
  2479. $url .= '&save_lastsearch_values=1';
  2480. }
  2481. }
  2482. $linkstart = '<a href="' . $url . '"';
  2483. $linkclose = "";
  2484. if (empty($notooltip)) {
  2485. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  2486. $langs->load("users");
  2487. $label = $langs->trans("ShowUser");
  2488. $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
  2489. }
  2490. $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
  2491. $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
  2492. }
  2493. $linkstart .= $linkclose . '>';
  2494. $linkend = '</a>';
  2495. //if ($withpictoimg == -1) $result.='<div class="nowrap">';
  2496. $result .= (($option == 'nolink') ? '' : $linkstart);
  2497. if ($withpictoimg) {
  2498. $paddafterimage = '';
  2499. if (abs((int) $withpictoimg) == 1) {
  2500. $paddafterimage = 'style="margin-' . ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right') . ': 3px;"';
  2501. }
  2502. // Only picto
  2503. if ($withpictoimg > 0) {
  2504. $picto = '<!-- picto user --><span class="nopadding userimg' . ($morecss ? ' ' . $morecss : '') . '">' . img_object('', 'user', $paddafterimage . ' ' . ($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1) . '</span>';
  2505. } else {
  2506. // Picto must be a photo
  2507. $picto = '<!-- picto photo user --><span class="nopadding userimg' . ($morecss ? ' ' . $morecss : '') . '"' . ($paddafterimage ? ' ' . $paddafterimage : '') . '>' . Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto' . ($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1) . '</span>';
  2508. }
  2509. $result .= $picto;
  2510. }
  2511. if ($withpictoimg > -2 && $withpictoimg != 2) {
  2512. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  2513. $result .= '<span class="nopadding usertext' . ((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled') . ($morecss ? ' ' . $morecss : '') . '">';
  2514. }
  2515. if ($mode == 'login') {
  2516. $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
  2517. } else {
  2518. $result .= dol_string_nohtmltag($this->getFullName($langs, '', ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
  2519. }
  2520. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  2521. $result .= '</span>';
  2522. }
  2523. }
  2524. $result .= (($option == 'nolink') ? '' : $linkend);
  2525. //if ($withpictoimg == -1) $result.='</div>';
  2526. $result .= $companylink;
  2527. global $action;
  2528. $hookmanager->initHooks(array('userdao'));
  2529. $parameters = array('id' => $this->id, 'getnomurl' => &$result);
  2530. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2531. if ($reshook > 0) {
  2532. $result = $hookmanager->resPrint;
  2533. } else {
  2534. $result .= $hookmanager->resPrint;
  2535. }
  2536. return $result;
  2537. }
  2538. /**
  2539. * Return clickable link of login (eventualy with picto)
  2540. *
  2541. * @param int $withpictoimg Include picto into link (1=picto, -1=photo)
  2542. * @param string $option On what the link point to ('leave', 'accountancy', 'nolink', )
  2543. * @param integer $notooltip 1=Disable tooltip on picto and name
  2544. * @param string $morecss Add more css on link
  2545. * @return string String with URL
  2546. */
  2547. public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
  2548. {
  2549. global $langs, $user;
  2550. $result = '';
  2551. $linkstart = '<a href="' . DOL_URL_ROOT . '/user/card.php?id=' . $this->id . '">';
  2552. $linkend = '</a>';
  2553. //Check user's rights to see an other user
  2554. if ((!$user->rights->user->user->lire && $this->id != $user->id)) {
  2555. $option = 'nolink';
  2556. }
  2557. if ($option == 'xxx') {
  2558. $linkstart = '<a href="' . DOL_URL_ROOT . '/user/card.php?id=' . $this->id . '">';
  2559. $linkend = '</a>';
  2560. }
  2561. if ($option == 'nolink') {
  2562. $linkstart = '';
  2563. $linkend = '';
  2564. }
  2565. $result .= $linkstart;
  2566. if ($withpictoimg) {
  2567. $paddafterimage = '';
  2568. if (abs($withpictoimg) == 1) {
  2569. $paddafterimage = 'style="margin-' . ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right') . ': 3px;"';
  2570. }
  2571. // Only picto
  2572. if ($withpictoimg > 0) {
  2573. $picto = '<!-- picto user --><span class="nopadding userimg' . ($morecss ? ' ' . $morecss : '') . '">' . img_object('', 'user', $paddafterimage . ' ' . ($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1) . '</span>';
  2574. } else {
  2575. // Picto must be a photo
  2576. $picto = '<!-- picto photo user --><span class="nopadding userimg' . ($morecss ? ' ' . $morecss : '') . '"' . ($paddafterimage ? ' ' . $paddafterimage : '') . '>' . Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto' . ($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1) . '</span>';
  2577. }
  2578. $result .= $picto;
  2579. }
  2580. $result .= $this->login;
  2581. $result .= $linkend;
  2582. return $result;
  2583. }
  2584. /**
  2585. * Return the label of the status of user (active, inactive)
  2586. *
  2587. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  2588. * @return string Label of status
  2589. */
  2590. public function getLibStatut($mode = 0)
  2591. {
  2592. return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
  2593. }
  2594. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2595. /**
  2596. * Return the label of a status of user (active, inactive)
  2597. *
  2598. * @param int $status Id status
  2599. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  2600. * @return string Label of status
  2601. */
  2602. public function LibStatut($status, $mode = 0)
  2603. {
  2604. // phpcs:enable
  2605. global $langs;
  2606. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  2607. global $langs;
  2608. //$langs->load("mymodule");
  2609. $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
  2610. $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
  2611. $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
  2612. $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
  2613. }
  2614. $statusType = 'status5';
  2615. if ($status == self::STATUS_ENABLED) {
  2616. $statusType = 'status4';
  2617. }
  2618. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  2619. }
  2620. /**
  2621. * Return clicable link of object (with eventually picto)
  2622. *
  2623. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  2624. * @return string HTML Code for Kanban thumb.
  2625. */
  2626. public function getKanbanView($option = '')
  2627. {
  2628. $return = '<div class="box-flex-item box-flex-grow-zero">';
  2629. $return .= '<div class="info-box info-box-sm">';
  2630. $return .= '<span class="info-box-icon bg-infobox-action">';
  2631. $label = '';
  2632. if (!empty($this->photo)) {
  2633. //$label .= '<div class="photointooltip floatright">';
  2634. $label .= Form::showphoto('userphoto', $this, 0, 60, 0, 'photokanban photoref photowithmargin photologintooltip', 'small', 0, 1); // Force height to 60 so we total height of tooltip can be calculated and collision can be managed
  2635. //$label .= '</div>';
  2636. //$label .= '<div style="clear: both;"></div>';
  2637. $return .= $label;
  2638. } else {
  2639. $return .= img_picto('', $this->picto);
  2640. }
  2641. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  2642. $return .= '</span>';
  2643. $return .= '<div class="info-box-content">';
  2644. $return .= '<span class="info-box-ref">' . (method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref) . '</span>';
  2645. if (property_exists($this, 'label')) {
  2646. $return .= '<br><span class="info-box-label opacitymedium">' . $this->label . '</span>';
  2647. }
  2648. if ($this->email) {
  2649. $return .= '<br><span class="info-box-label opacitymedium small">' . img_picto('', 'email') . ' ' . $this->email . '</span>';
  2650. }
  2651. if (method_exists($this, 'getLibStatut')) {
  2652. $return .= '<br><div class="info-box-status margintoponly">' . $this->getLibStatut(5) . '</div>';
  2653. }
  2654. $return .= '</div>';
  2655. $return .= '</div>';
  2656. $return .= '</div>';
  2657. return $return;
  2658. }
  2659. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  2660. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2661. /**
  2662. * Retourne chaine DN complete dans l'annuaire LDAP pour l'objet
  2663. *
  2664. * @param array $info Info array loaded by _load_ldap_info
  2665. * @param int $mode 0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb)
  2666. * 1=Return parent (ou=xxx,dc=aaa,dc=bbb)
  2667. * 2=Return key only (RDN) (uid=qqq)
  2668. * @return string DN
  2669. */
  2670. public function _load_ldap_dn($info, $mode = 0)
  2671. {
  2672. // phpcs:enable
  2673. global $conf;
  2674. $dn = '';
  2675. if ($mode == 0) {
  2676. $dn = $conf->global->LDAP_KEY_USERS . "=" . $info[$conf->global->LDAP_KEY_USERS] . "," . $conf->global->LDAP_USER_DN;
  2677. } elseif ($mode == 1) {
  2678. $dn = $conf->global->LDAP_USER_DN;
  2679. } elseif ($mode == 2) {
  2680. $dn = $conf->global->LDAP_KEY_USERS . "=" . $info[$conf->global->LDAP_KEY_USERS];
  2681. }
  2682. return $dn;
  2683. }
  2684. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  2685. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2686. /**
  2687. * Initialize the info array (array of LDAP values) that will be used to call LDAP functions
  2688. *
  2689. * @return array Tableau info des attributs
  2690. */
  2691. public function _load_ldap_info()
  2692. {
  2693. // phpcs:enable
  2694. global $conf, $langs;
  2695. $info = array();
  2696. $socialnetworks = getArrayOfSocialNetworks();
  2697. $keymodified = false;
  2698. // Object classes
  2699. $info["objectclass"] = explode(',', $conf->global->LDAP_USER_OBJECT_CLASS);
  2700. $this->fullname = $this->getFullName($langs);
  2701. // Possible LDAP KEY (constname => varname)
  2702. $ldapkey = array(
  2703. 'LDAP_FIELD_FULLNAME' => 'fullname',
  2704. 'LDAP_FIELD_NAME' => 'lastname',
  2705. 'LDAP_FIELD_FIRSTNAME' => 'firstname',
  2706. 'LDAP_FIELD_LOGIN' => 'login',
  2707. 'LDAP_FIELD_LOGIN_SAMBA' => 'login',
  2708. 'LDAP_FIELD_PHONE' => 'office_phone',
  2709. 'LDAP_FIELD_MOBILE' => 'user_mobile',
  2710. 'LDAP_FIELD_FAX' => 'office_fax',
  2711. 'LDAP_FIELD_MAIL' => 'email',
  2712. 'LDAP_FIELD_SID' => 'ldap_sid',
  2713. );
  2714. // Champs
  2715. foreach ($ldapkey as $constname => $varname) {
  2716. if (!empty($this->$varname) && !empty($conf->global->$constname)) {
  2717. $info[$conf->global->$constname] = $this->$varname;
  2718. // Check if it is the LDAP key and if its value has been changed
  2719. if (!empty($conf->global->LDAP_KEY_USERS) && $conf->global->LDAP_KEY_USERS == $conf->global->$constname) {
  2720. if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
  2721. $keymodified = true; // For check if LDAP key has been modified
  2722. }
  2723. }
  2724. }
  2725. }
  2726. foreach ($socialnetworks as $key => $value) {
  2727. if (!empty($this->socialnetworks[$value['label']]) && !empty($conf->global->{'LDAP_FIELD_' . strtoupper($value['label'])})) {
  2728. $info[$conf->global->{'LDAP_FIELD_' . strtoupper($value['label'])}] = $this->socialnetworks[$value['label']];
  2729. }
  2730. }
  2731. if ($this->address && !empty($conf->global->LDAP_FIELD_ADDRESS)) {
  2732. $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address;
  2733. }
  2734. if ($this->zip && !empty($conf->global->LDAP_FIELD_ZIP)) {
  2735. $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip;
  2736. }
  2737. if ($this->town && !empty($conf->global->LDAP_FIELD_TOWN)) {
  2738. $info[$conf->global->LDAP_FIELD_TOWN] = $this->town;
  2739. }
  2740. if ($this->note_public && !empty($conf->global->LDAP_FIELD_DESCRIPTION)) {
  2741. $info[$conf->global->LDAP_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_public, 2);
  2742. }
  2743. if ($this->socid > 0) {
  2744. $soc = new Societe($this->db);
  2745. $soc->fetch($this->socid);
  2746. $info[$conf->global->LDAP_FIELD_COMPANY] = $soc->name;
  2747. if ($soc->client == 1) {
  2748. $info["businessCategory"] = "Customers";
  2749. }
  2750. if ($soc->client == 2) {
  2751. $info["businessCategory"] = "Prospects";
  2752. }
  2753. if ($soc->fournisseur == 1) {
  2754. $info["businessCategory"] = "Suppliers";
  2755. }
  2756. }
  2757. // When password is modified
  2758. if (!empty($this->pass)) {
  2759. if (!empty($conf->global->LDAP_FIELD_PASSWORD)) {
  2760. $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte
  2761. }
  2762. if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
  2763. $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
  2764. }
  2765. } elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') {
  2766. // Set LDAP password if possible
  2767. // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
  2768. if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
  2769. // Just for the default MD5 !
  2770. if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) {
  2771. if ($this->pass_indatabase_crypted && !empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
  2772. $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
  2773. }
  2774. }
  2775. } elseif (!empty($this->pass_indatabase)) {
  2776. // Use $this->pass_indatabase value if exists
  2777. if (!empty($conf->global->LDAP_FIELD_PASSWORD)) {
  2778. $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte
  2779. }
  2780. if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
  2781. $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
  2782. }
  2783. }
  2784. }
  2785. if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') {
  2786. $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
  2787. $info['uidnumber'] = $this->id;
  2788. $info['phpgwTz'] = 0;
  2789. $info['phpgwMailType'] = 'INTERNET';
  2790. $info['phpgwMailHomeType'] = 'INTERNET';
  2791. $info["phpgwContactTypeId"] = 'n';
  2792. $info["phpgwContactCatId"] = 0;
  2793. $info["phpgwContactAccess"] = "public";
  2794. if (dol_strlen($this->egroupware_id) == 0) {
  2795. $this->egroupware_id = 1;
  2796. }
  2797. $info["phpgwContactOwner"] = $this->egroupware_id;
  2798. if ($this->email) {
  2799. $info["rfc822Mailbox"] = $this->email;
  2800. }
  2801. if ($this->phone_mobile) {
  2802. $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
  2803. }
  2804. }
  2805. if (!empty($conf->global->LDAP_FIELD_USERID)) {
  2806. $info[$conf->global->LDAP_FIELD_USERID] = $this->id;
  2807. }
  2808. if (!empty($conf->global->LDAP_FIELD_GROUPID)) {
  2809. $usergroup = new UserGroup($this->db);
  2810. $groupslist = $usergroup->listGroupsForUser($this->id);
  2811. $info[$conf->global->LDAP_FIELD_GROUPID] = '65534';
  2812. if (!empty($groupslist)) {
  2813. foreach ($groupslist as $groupforuser) {
  2814. $info[$conf->global->LDAP_FIELD_GROUPID] = $groupforuser->id; //Select first group in list
  2815. break;
  2816. }
  2817. }
  2818. }
  2819. if (!empty($conf->global->LDAP_FIELD_HOMEDIRECTORY) && !empty($conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX)) {
  2820. $info[$conf->global->LDAP_FIELD_HOMEDIRECTORY] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->login";
  2821. }
  2822. return $info;
  2823. }
  2824. /**
  2825. * Initialise an instance with random values.
  2826. * Used to build previews or test instances.
  2827. * id must be 0 if object instance is a specimen.
  2828. *
  2829. * @return int
  2830. */
  2831. public function initAsSpecimen()
  2832. {
  2833. global $user, $langs;
  2834. $now = dol_now();
  2835. // Initialise parametres
  2836. $this->id = 0;
  2837. $this->ref = 'SPECIMEN';
  2838. $this->specimen = 1;
  2839. $this->lastname = 'DOLIBARR';
  2840. $this->firstname = 'SPECIMEN';
  2841. $this->gender = 'man';
  2842. $this->note_public = 'This is a note public';
  2843. $this->note_private = 'This is a note private';
  2844. $this->email = 'email@specimen.com';
  2845. $this->personal_email = 'personalemail@specimen.com';
  2846. $this->socialnetworks = array(
  2847. 'skype' => 'skypepseudo',
  2848. 'twitter' => 'twitterpseudo',
  2849. 'facebook' => 'facebookpseudo',
  2850. 'linkedin' => 'linkedinpseudo',
  2851. );
  2852. $this->office_phone = '0999999999';
  2853. $this->office_fax = '0999999998';
  2854. $this->user_mobile = '0999999997';
  2855. $this->personal_mobile = '0999999996';
  2856. $this->admin = 0;
  2857. $this->login = 'dolibspec';
  2858. $this->pass = 'dolibSpec+@123';
  2859. //$this->pass_indatabase='dolibspec'; Set after a fetch
  2860. //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
  2861. $this->datec = $now;
  2862. $this->datem = $now;
  2863. $this->datelastlogin = $now;
  2864. $this->iplastlogin = '127.0.0.1';
  2865. $this->datepreviouslogin = $now;
  2866. $this->ippreviouslogin = '127.0.0.1';
  2867. $this->statut = 1; // deprecated
  2868. $this->status = 1;
  2869. $this->entity = 1;
  2870. return 1;
  2871. }
  2872. /**
  2873. * Load info of user object
  2874. *
  2875. * @param int $id Id of user to load
  2876. * @return void
  2877. */
  2878. public function info($id)
  2879. {
  2880. $sql = "SELECT u.rowid, u.login as ref, u.datec,";
  2881. $sql .= " u.tms as date_modification, u.entity";
  2882. $sql .= " FROM " . $this->db->prefix() . "user as u";
  2883. $sql .= " WHERE u.rowid = " . ((int) $id);
  2884. $result = $this->db->query($sql);
  2885. if ($result) {
  2886. if ($this->db->num_rows($result)) {
  2887. $obj = $this->db->fetch_object($result);
  2888. $this->id = $obj->rowid;
  2889. $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
  2890. $this->date_creation = $this->db->jdate($obj->datec);
  2891. $this->date_modification = $this->db->jdate($obj->date_modification);
  2892. $this->entity = $obj->entity;
  2893. }
  2894. $this->db->free($result);
  2895. } else {
  2896. dol_print_error($this->db);
  2897. }
  2898. }
  2899. /**
  2900. * Return number of mass Emailing received by this contacts with its email
  2901. *
  2902. * @return int Number of EMailings
  2903. */
  2904. public function getNbOfEMailings()
  2905. {
  2906. $sql = "SELECT count(mc.email) as nb";
  2907. $sql .= " FROM " . $this->db->prefix() . "mailing_cibles as mc";
  2908. $sql .= " WHERE mc.email = '" . $this->db->escape($this->email) . "'";
  2909. $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes
  2910. $resql = $this->db->query($sql);
  2911. if ($resql) {
  2912. $obj = $this->db->fetch_object($resql);
  2913. $nb = $obj->nb;
  2914. $this->db->free($resql);
  2915. return $nb;
  2916. } else {
  2917. $this->error = $this->db->error();
  2918. return -1;
  2919. }
  2920. }
  2921. /**
  2922. * Return number of existing users
  2923. *
  2924. * @param string $limitTo Limit to '' or 'active'
  2925. * @param string $option 'superadmin' = return for entity 0 only
  2926. * @param int $admin Filter on admin tag
  2927. * @return int Number of users
  2928. */
  2929. public function getNbOfUsers($limitTo, $option = '', $admin = -1)
  2930. {
  2931. global $conf;
  2932. $sql = "SELECT count(rowid) as nb";
  2933. $sql .= " FROM " . $this->db->prefix() . "user";
  2934. if ($option == 'superadmin') {
  2935. $sql .= " WHERE entity = 0";
  2936. } else {
  2937. $sql .= " WHERE entity IN (" . getEntity('user', 0) . ")";
  2938. if ($limitTo == 'active') {
  2939. $sql .= " AND statut = 1";
  2940. }
  2941. }
  2942. if ($admin >= 0) {
  2943. $sql .= " AND admin = " . (int) $admin;
  2944. }
  2945. $resql = $this->db->query($sql);
  2946. if ($resql) {
  2947. $obj = $this->db->fetch_object($resql);
  2948. $nb = (int) $obj->nb;
  2949. $this->db->free($resql);
  2950. return $nb;
  2951. } else {
  2952. $this->error = $this->db->lasterror();
  2953. return -1;
  2954. }
  2955. }
  2956. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2957. /**
  2958. * Update user using data from the LDAP
  2959. *
  2960. * @param Object $ldapuser Ladp User
  2961. * @return int <0 if KO, >0 if OK
  2962. */
  2963. public function update_ldap2dolibarr(&$ldapuser)
  2964. {
  2965. // phpcs:enable
  2966. // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
  2967. global $user, $conf;
  2968. $socialnetworks = getArrayOfSocialNetworks();
  2969. $this->firstname = $ldapuser->{$conf->global->LDAP_FIELD_FIRSTNAME};
  2970. $this->lastname = $ldapuser->{$conf->global->LDAP_FIELD_NAME};
  2971. $this->login = $ldapuser->{$conf->global->LDAP_FIELD_LOGIN};
  2972. $this->pass = $ldapuser->{$conf->global->LDAP_FIELD_PASSWORD};
  2973. $this->pass_indatabase_crypted = $ldapuser->{$conf->global->LDAP_FIELD_PASSWORD_CRYPTED};
  2974. $this->office_phone = $ldapuser->{$conf->global->LDAP_FIELD_PHONE};
  2975. $this->user_mobile = $ldapuser->{$conf->global->LDAP_FIELD_MOBILE};
  2976. $this->office_fax = $ldapuser->{$conf->global->LDAP_FIELD_FAX};
  2977. $this->email = $ldapuser->{$conf->global->LDAP_FIELD_MAIL};
  2978. foreach ($socialnetworks as $key => $value) {
  2979. $tmpkey = 'LDAP_FIELD_' . strtoupper($value['label']);
  2980. $this->socialnetworks[$value['label']] = $ldapuser->{$conf->global->$tmpkey};
  2981. }
  2982. $this->ldap_sid = $ldapuser->{$conf->global->LDAP_FIELD_SID};
  2983. $this->job = $ldapuser->{$conf->global->LDAP_FIELD_TITLE};
  2984. $this->note_public = $ldapuser->{$conf->global->LDAP_FIELD_DESCRIPTION};
  2985. $result = $this->update($user);
  2986. dol_syslog(get_class($this) . "::update_ldap2dolibarr result=" . $result, LOG_DEBUG);
  2987. return $result;
  2988. }
  2989. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2990. /**
  2991. * Return and array with all instanciated first level children users of current user
  2992. *
  2993. * @return User[]|int
  2994. * @see getAllChildIds()
  2995. */
  2996. public function get_children()
  2997. {
  2998. // phpcs:enable
  2999. $sql = "SELECT rowid FROM " . $this->db->prefix() . "user";
  3000. $sql .= " WHERE fk_user = " . ((int) $this->id);
  3001. dol_syslog(get_class($this) . "::get_children", LOG_DEBUG);
  3002. $res = $this->db->query($sql);
  3003. if ($res) {
  3004. $users = array();
  3005. while ($rec = $this->db->fetch_array($res)) {
  3006. $user = new User($this->db);
  3007. $user->fetch($rec['rowid']);
  3008. $users[] = $user;
  3009. }
  3010. return $users;
  3011. } else {
  3012. dol_print_error($this->db);
  3013. return -1;
  3014. }
  3015. }
  3016. /**
  3017. * Load this->parentof that is array(id_son=>id_parent, ...)
  3018. *
  3019. * @return int <0 if KO, >0 if OK
  3020. */
  3021. private function loadParentOf()
  3022. {
  3023. global $conf;
  3024. $this->parentof = array();
  3025. // Load array[child]=parent
  3026. $sql = "SELECT fk_user as id_parent, rowid as id_son";
  3027. $sql .= " FROM " . $this->db->prefix() . "user";
  3028. $sql .= " WHERE fk_user <> 0";
  3029. $sql .= " AND entity IN (" . getEntity('user') . ")";
  3030. dol_syslog(get_class($this) . "::loadParentOf", LOG_DEBUG);
  3031. $resql = $this->db->query($sql);
  3032. if ($resql) {
  3033. while ($obj = $this->db->fetch_object($resql)) {
  3034. $this->parentof[$obj->id_son] = $obj->id_parent;
  3035. }
  3036. return 1;
  3037. } else {
  3038. dol_print_error($this->db);
  3039. return -1;
  3040. }
  3041. }
  3042. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3043. /**
  3044. * Build the hierarchy/tree of users into an array.
  3045. * Set and return this->users that is an array sorted according to tree with arrays of:
  3046. * id = id user
  3047. * lastname
  3048. * firstname
  3049. * fullname = nom avec chemin complet du user
  3050. * fullpath = chemin complet compose des id: "_grandparentid_parentid_id"
  3051. *
  3052. * @param int $deleteafterid Removed all users including the leaf $deleteafterid (and all its child) in user tree.
  3053. * @param string $filter SQL filter on users. This parameter must not come from user intput.
  3054. * @return array Array of users $this->users. Note: $this->parentof is also set.
  3055. */
  3056. public function get_full_tree($deleteafterid = 0, $filter = '')
  3057. {
  3058. // phpcs:enable
  3059. global $conf, $user;
  3060. global $hookmanager;
  3061. // Actions hooked (by external module)
  3062. $hookmanager->initHooks(array('userdao'));
  3063. $this->users = array();
  3064. // Init this->parentof that is array(id_son=>id_parent, ...)
  3065. $this->loadParentOf();
  3066. // Init $this->users array
  3067. $sql = "SELECT DISTINCT u.rowid, u.firstname, u.lastname, u.fk_user, u.fk_soc, u.login, u.email, u.gender, u.admin, u.statut, u.photo, u.entity"; // Distinct reduce pb with old tables with duplicates
  3068. $sql .= " FROM " . $this->db->prefix() . "user as u";
  3069. // Add fields from hooks
  3070. $parameters = array();
  3071. $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
  3072. if ($reshook > 0) {
  3073. $sql .= $hookmanager->resPrint;
  3074. } else {
  3075. $sql .= " WHERE u.entity IN (" . getEntity('user') . ")";
  3076. }
  3077. if ($filter) {
  3078. $sql .= " AND " . $filter;
  3079. }
  3080. dol_syslog(get_class($this) . "::get_full_tree get user list", LOG_DEBUG);
  3081. $resql = $this->db->query($sql);
  3082. if ($resql) {
  3083. $i = 0;
  3084. while ($obj = $this->db->fetch_object($resql)) {
  3085. $this->users[$obj->rowid]['rowid'] = $obj->rowid;
  3086. $this->users[$obj->rowid]['id'] = $obj->rowid;
  3087. $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
  3088. $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
  3089. $this->users[$obj->rowid]['firstname'] = $obj->firstname;
  3090. $this->users[$obj->rowid]['lastname'] = $obj->lastname;
  3091. $this->users[$obj->rowid]['login'] = $obj->login;
  3092. $this->users[$obj->rowid]['statut'] = $obj->statut;
  3093. $this->users[$obj->rowid]['entity'] = $obj->entity;
  3094. $this->users[$obj->rowid]['email'] = $obj->email;
  3095. $this->users[$obj->rowid]['gender'] = $obj->gender;
  3096. $this->users[$obj->rowid]['admin'] = $obj->admin;
  3097. $this->users[$obj->rowid]['photo'] = $obj->photo;
  3098. $i++;
  3099. }
  3100. } else {
  3101. dol_print_error($this->db);
  3102. return -1;
  3103. }
  3104. // We add the fullpath property to each elements of first level (no parent exists)
  3105. dol_syslog(get_class($this) . "::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
  3106. foreach ($this->users as $key => $val) {
  3107. $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
  3108. if ($result < 0) {
  3109. $this->error = 'ErrorLoopInHierarchy';
  3110. return -1;
  3111. }
  3112. }
  3113. // Exclude leaf including $deleteafterid from tree
  3114. if ($deleteafterid) {
  3115. //print "Look to discard user ".$deleteafterid."\n";
  3116. $keyfilter1 = '^' . $deleteafterid . '$';
  3117. $keyfilter2 = '_' . $deleteafterid . '$';
  3118. $keyfilter3 = '^' . $deleteafterid . '_';
  3119. $keyfilter4 = '_' . $deleteafterid . '_';
  3120. foreach ($this->users as $key => $val) {
  3121. if (
  3122. preg_match('/' . $keyfilter1 . '/', $val['fullpath']) || preg_match('/' . $keyfilter2 . '/', $val['fullpath'])
  3123. || preg_match('/' . $keyfilter3 . '/', $val['fullpath']) || preg_match('/' . $keyfilter4 . '/', $val['fullpath'])
  3124. ) {
  3125. unset($this->users[$key]);
  3126. }
  3127. }
  3128. }
  3129. dol_syslog(get_class($this) . "::get_full_tree dol_sort_array", LOG_DEBUG);
  3130. $this->users = dol_sort_array($this->users, 'fullname', 'asc', true, false);
  3131. //var_dump($this->users);
  3132. return $this->users;
  3133. }
  3134. /**
  3135. * Return list of all child users id in herarchy (all sublevels).
  3136. * Note: Calling this function also reset full list of users into $this->users.
  3137. *
  3138. * @param int $addcurrentuser 1=Add also current user id to the list.
  3139. * @return array Array of user id lower than user (all levels under user). This overwrite this->users.
  3140. * @see get_children()
  3141. */
  3142. public function getAllChildIds($addcurrentuser = 0)
  3143. {
  3144. $childids = array();
  3145. if (isset($this->cache_childids[$this->id])) {
  3146. $childids = $this->cache_childids[$this->id];
  3147. } else {
  3148. // Init this->users
  3149. $this->get_full_tree();
  3150. $idtoscan = $this->id;
  3151. dol_syslog("Build childid for id = " . $idtoscan);
  3152. foreach ($this->users as $id => $val) {
  3153. //var_dump($val['fullpath']);
  3154. if (preg_match('/_' . $idtoscan . '_/', $val['fullpath'])) {
  3155. $childids[$val['id']] = $val['id'];
  3156. }
  3157. }
  3158. }
  3159. $this->cache_childids[$this->id] = $childids;
  3160. if ($addcurrentuser) {
  3161. $childids[$this->id] = $this->id;
  3162. }
  3163. return $childids;
  3164. }
  3165. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3166. /**
  3167. * For user id_user and its childs available in this->users, define property fullpath and fullname.
  3168. * Function called by get_full_tree().
  3169. *
  3170. * @param int $id_user id_user entry to update
  3171. * @param int $protection Deep counter to avoid infinite loop (no more required, a protection is added with array useridfound)
  3172. * @return int < 0 if KO (infinit loop), >= 0 if OK
  3173. */
  3174. public function build_path_from_id_user($id_user, $protection = 0)
  3175. {
  3176. // phpcs:enable
  3177. //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
  3178. if (!empty($this->users[$id_user]['fullpath'])) {
  3179. // Already defined
  3180. dol_syslog(get_class($this) . "::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
  3181. return 0;
  3182. }
  3183. // Define fullpath and fullname
  3184. $this->users[$id_user]['fullpath'] = '_' . $id_user;
  3185. $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
  3186. $i = 0;
  3187. $cursor_user = $id_user;
  3188. $useridfound = array($id_user);
  3189. while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) {
  3190. if (in_array($this->parentof[$cursor_user], $useridfound)) {
  3191. dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
  3192. return -1; // Should not happen. Protection against looping hierarchy
  3193. }
  3194. $useridfound[] = $this->parentof[$cursor_user];
  3195. $this->users[$id_user]['fullpath'] = '_' . $this->parentof[$cursor_user] . $this->users[$id_user]['fullpath'];
  3196. $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'] . ' >> ' . $this->users[$id_user]['fullname'];
  3197. $i++;
  3198. $cursor_user = $this->parentof[$cursor_user];
  3199. }
  3200. // We count number of _ to have level
  3201. $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
  3202. return 1;
  3203. }
  3204. /**
  3205. * Function used to replace a thirdparty id with another one.
  3206. *
  3207. * @param DoliDB $db Database handler
  3208. * @param int $origin_id Old thirdparty id
  3209. * @param int $dest_id New thirdparty id
  3210. * @return bool
  3211. */
  3212. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  3213. {
  3214. $tables = array(
  3215. 'user',
  3216. );
  3217. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  3218. }
  3219. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3220. /**
  3221. * Load metrics this->nb for dashboard
  3222. *
  3223. * @return int <0 if KO, >0 if OK
  3224. */
  3225. public function load_state_board()
  3226. {
  3227. // phpcs:enable
  3228. global $conf;
  3229. $this->nb = array();
  3230. $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
  3231. $sql .= " FROM " . $this->db->prefix() . "user as u";
  3232. if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  3233. $sql .= ", " . $this->db->prefix() . "usergroup_user as ug";
  3234. $sql .= " WHERE ug.entity IN (" . getEntity('usergroup') . ")";
  3235. $sql .= " AND ug.fk_user = u.rowid";
  3236. } else {
  3237. $sql .= " WHERE u.entity IN (" . getEntity('user') . ")";
  3238. }
  3239. $sql .= " AND u.statut > 0";
  3240. //$sql.= " AND employee != 0";
  3241. $resql = $this->db->query($sql);
  3242. if ($resql) {
  3243. while ($obj = $this->db->fetch_object($resql)) {
  3244. $this->nb["users"] = $obj->nb;
  3245. }
  3246. $this->db->free($resql);
  3247. return 1;
  3248. } else {
  3249. dol_print_error($this->db);
  3250. $this->error = $this->db->error();
  3251. return -1;
  3252. }
  3253. }
  3254. /**
  3255. * Create a document onto disk according to template module.
  3256. *
  3257. * @param string $modele Force model to use ('' to not force)
  3258. * @param Translate $outputlangs Object langs to use for output
  3259. * @param int $hidedetails Hide details of lines
  3260. * @param int $hidedesc Hide description
  3261. * @param int $hideref Hide ref
  3262. * @param null|array $moreparams Array to provide more information
  3263. * @return int 0 if KO, 1 if OK
  3264. */
  3265. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  3266. {
  3267. global $conf, $user, $langs;
  3268. $langs->load("user");
  3269. // Positionne le modele sur le nom du modele a utiliser
  3270. if (!dol_strlen($modele)) {
  3271. if (!empty($conf->global->USER_ADDON_PDF)) {
  3272. $modele = $conf->global->USER_ADDON_PDF;
  3273. } else {
  3274. $modele = 'bluesky';
  3275. }
  3276. }
  3277. $modelpath = "core/modules/user/doc/";
  3278. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  3279. }
  3280. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3281. /**
  3282. * Return property of user from its id
  3283. *
  3284. * @param int $rowid id of contact
  3285. * @param string $mode 'email' or 'mobile'
  3286. * @return string Email of user with format: "Full name <email>"
  3287. */
  3288. public function user_get_property($rowid, $mode)
  3289. {
  3290. // phpcs:enable
  3291. $user_property = '';
  3292. if (empty($rowid)) {
  3293. return '';
  3294. }
  3295. $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
  3296. $sql .= " FROM " . $this->db->prefix() . "user";
  3297. $sql .= " WHERE rowid = " . ((int) $rowid);
  3298. $resql = $this->db->query($sql);
  3299. if ($resql) {
  3300. $nump = $this->db->num_rows($resql);
  3301. if ($nump) {
  3302. $obj = $this->db->fetch_object($resql);
  3303. if ($mode == 'email') {
  3304. $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname) . " <" . $obj->email . ">";
  3305. } elseif ($mode == 'mobile') {
  3306. $user_property = $obj->user_mobile;
  3307. }
  3308. }
  3309. return $user_property;
  3310. } else {
  3311. dol_print_error($this->db);
  3312. }
  3313. }
  3314. /**
  3315. * Load all objects into $this->users
  3316. *
  3317. * @param string $sortorder sort order
  3318. * @param string $sortfield sort field
  3319. * @param int $limit limit page
  3320. * @param int $offset page
  3321. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  3322. * @param string $filtermode Filter mode (AND or OR)
  3323. * @param bool $entityfilter Activate entity filter
  3324. * @return int <0 if KO, >0 if OK
  3325. */
  3326. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = array(), $filtermode = 'AND', $entityfilter = false)
  3327. {
  3328. global $conf, $user;
  3329. $sql = "SELECT t.rowid";
  3330. $sql .= ' FROM ' . $this->db->prefix() . $this->table_element . ' as t ';
  3331. if ($entityfilter) {
  3332. if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  3333. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  3334. $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
  3335. } else {
  3336. $sql .= "," . $this->db->prefix() . "usergroup_user as ug";
  3337. $sql .= " WHERE ((ug.fk_user = t.rowid";
  3338. $sql .= " AND ug.entity IN (" . getEntity('usergroup') . "))";
  3339. $sql .= " OR t.entity = 0)"; // Show always superadmin
  3340. }
  3341. } else {
  3342. $sql .= " WHERE t.entity IN (" . getEntity('user') . ")";
  3343. }
  3344. } else {
  3345. $sql .= " WHERE 1 = 1";
  3346. }
  3347. // Manage filter
  3348. $sqlwhere = array();
  3349. if (!empty($filter)) {
  3350. foreach ($filter as $key => $value) {
  3351. if ($key == 't.rowid') {
  3352. $sqlwhere[] = $key . " = " . ((int) $value);
  3353. } elseif (isset($this->fields[$key]['type']) && in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
  3354. $sqlwhere[] = $key . " = '" . $this->db->idate($value) . "'";
  3355. } elseif ($key == 'customsql') {
  3356. $sqlwhere[] = $value;
  3357. } else {
  3358. $sqlwhere[] = $key . " LIKE '%" . $this->db->escape($value) . "%'";
  3359. }
  3360. }
  3361. }
  3362. if (count($sqlwhere) > 0) {
  3363. $sql .= ' AND (' . implode(' ' . $this->db->escape($filtermode) . ' ', $sqlwhere) . ')';
  3364. }
  3365. $sql .= $this->db->order($sortfield, $sortorder);
  3366. if ($limit) {
  3367. $sql .= $this->db->plimit($limit + 1, $offset);
  3368. }
  3369. dol_syslog(__METHOD__, LOG_DEBUG);
  3370. $resql = $this->db->query($sql);
  3371. if ($resql) {
  3372. $this->users = array();
  3373. $num = $this->db->num_rows($resql);
  3374. if ($num) {
  3375. while ($obj = $this->db->fetch_object($resql)) {
  3376. $line = new self($this->db);
  3377. $result = $line->fetch($obj->rowid);
  3378. if ($result > 0 && !empty($line->id)) {
  3379. $this->users[$obj->rowid] = clone $line;
  3380. }
  3381. }
  3382. $this->db->free($resql);
  3383. }
  3384. return $num;
  3385. } else {
  3386. $this->errors[] = $this->db->lasterror();
  3387. return -1;
  3388. }
  3389. }
  3390. /**
  3391. * Cache the SQL results of the function "findUserIdByEmail($email)"
  3392. *
  3393. * NOTE: findUserIdByEmailCache[...] === -1 means not found in database
  3394. *
  3395. * @var array
  3396. */
  3397. private $findUserIdByEmailCache;
  3398. /**
  3399. * Find a user by the given e-mail and return it's user id when found
  3400. *
  3401. * NOTE:
  3402. * Use AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR
  3403. * to disable exact e-mail search
  3404. *
  3405. * @param string $email The full e-mail (or a part of a e-mail)
  3406. * @return int <0 = user was not found, >0 = The id of the user
  3407. */
  3408. public function findUserIdByEmail($email)
  3409. {
  3410. if (isset($this->findUserIdByEmailCache[$email])) {
  3411. return $this->findUserIdByEmailCache[$email];
  3412. }
  3413. $this->findUserIdByEmailCache[$email] = -1;
  3414. global $conf;
  3415. $sql = 'SELECT rowid';
  3416. $sql .= ' FROM ' . $this->db->prefix() . 'user';
  3417. if (!empty($conf->global->AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR)) {
  3418. $sql .= " WHERE email LIKE '%" . $this->db->escape($email) . "%'";
  3419. } else {
  3420. $sql .= " WHERE email = '" . $this->db->escape($email) . "'";
  3421. }
  3422. $sql .= ' LIMIT 1';
  3423. $resql = $this->db->query($sql);
  3424. if (!$resql) {
  3425. return -1;
  3426. }
  3427. $obj = $this->db->fetch_object($resql);
  3428. if (!$obj) {
  3429. return -1;
  3430. }
  3431. $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
  3432. return $this->findUserIdByEmailCache[$email];
  3433. }
  3434. }