user.class.php 131 KB

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