user.class.php 138 KB

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