user.class.php 125 KB

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