user.class.php 111 KB

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