user.class.php 136 KB

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