user.class.php 130 KB

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