user.class.php 129 KB

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