user.class.php 112 KB

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