user.class.php 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376
  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-2012 Regis Houssin <regis.houssin@capnetworks.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-2014 Philippe Grand <philippe.grand@atoo-net.com>
  11. * Copyright (C) 2013 Alexandre Spangaro <alexandre.spangaro@gmail.com>
  12. *
  13. * This program is free software; you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation; either version 3 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. */
  26. /**
  27. * \file htdocs/user/class/user.class.php
  28. * \brief File of class to manage users
  29. * \ingroup core
  30. */
  31. require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
  32. /**
  33. * Class to manage Dolibarr users
  34. */
  35. class User extends CommonObject
  36. {
  37. public $element='user';
  38. public $table_element='user';
  39. protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  40. var $id=0;
  41. var $ref;
  42. var $ref_ext;
  43. var $ldap_sid;
  44. var $search_sid;
  45. var $lastname;
  46. var $firstname;
  47. var $note;
  48. var $email;
  49. var $skype;
  50. var $job;
  51. var $signature;
  52. var $office_phone;
  53. var $office_fax;
  54. var $user_mobile;
  55. var $admin;
  56. var $login;
  57. var $entity;
  58. //! Clear password in memory
  59. var $pass;
  60. //! Clear password in database (defined if DATABASE_PWD_ENCRYPTED=0)
  61. var $pass_indatabase;
  62. //! Encrypted password in database (always defined)
  63. var $pass_indatabase_crypted;
  64. var $datec;
  65. var $datem;
  66. //! If this is defined, it is an external user
  67. var $societe_id; // deprecated
  68. var $contact_id; // deprecated
  69. var $socid;
  70. var $contactid;
  71. var $fk_member;
  72. var $fk_user;
  73. var $clicktodial_url;
  74. var $clicktodial_login;
  75. var $clicktodial_password;
  76. var $clicktodial_poste;
  77. var $datelastlogin;
  78. var $datepreviouslogin;
  79. var $statut;
  80. var $photo;
  81. var $lang;
  82. var $rights; // Array of permissions user->rights->permx
  83. var $all_permissions_are_loaded; /**< \private all_permissions_are_loaded */
  84. private $_tab_loaded=array(); // Array of cache of already loaded permissions
  85. var $conf; // To store personal config
  86. var $oldcopy; // To contains a clone of this when we need to save old properties of object
  87. var $users; // To store all tree of users hierarchy
  88. var $parentof; // To store an array of all parents for all ids.
  89. var $accountancy_code; // Accountancy code in prevision of the complete accountancy module
  90. var $thm; // Average cost of employee
  91. var $tjm; // Average cost of employee
  92. var $salary; // Monthly salary
  93. var $salaryextra; // Monthly salary extra
  94. var $weeklyhours; // Weekly hours
  95. var $color; // Define background color for user in agenda
  96. /**
  97. * Constructor de la classe
  98. *
  99. * @param DoliDb $db Database handler
  100. */
  101. function __construct($db)
  102. {
  103. $this->db = $db;
  104. // Preference utilisateur
  105. $this->liste_limit = 0;
  106. $this->clicktodial_loaded = 0;
  107. $this->all_permissions_are_loaded = 0;
  108. $this->admin=0;
  109. $this->conf = new stdClass();
  110. $this->rights = new stdClass();
  111. $this->rights->user = new stdClass();
  112. $this->rights->user->user = new stdClass();
  113. $this->rights->user->self = new stdClass();
  114. }
  115. /**
  116. * Load a user from database with its id or ref (login)
  117. *
  118. * @param int $id Si defini, id a utiliser pour recherche
  119. * @param string $login Si defini, login a utiliser pour recherche
  120. * @param string $sid Si defini, sid a utiliser pour recherche
  121. * @param int $loadpersonalconf Also load personal conf of user (in $user->conf->xxx)
  122. * @return int <0 if KO, 0 not found, >0 if OK
  123. */
  124. function fetch($id='', $login='',$sid='',$loadpersonalconf=1)
  125. {
  126. global $conf, $user;
  127. // Clean parameters
  128. $login=trim($login);
  129. // Get user
  130. $sql = "SELECT u.rowid, u.lastname, u.firstname, u.email, u.job, u.skype, u.signature, u.office_phone, u.office_fax, u.user_mobile,";
  131. $sql.= " u.admin, u.login, u.note,";
  132. $sql.= " u.pass, u.pass_crypted, u.pass_temp,";
  133. $sql.= " u.fk_societe, u.fk_socpeople, u.fk_member, u.fk_user, u.ldap_sid,";
  134. $sql.= " u.statut, u.lang, u.entity,";
  135. $sql.= " u.datec as datec,";
  136. $sql.= " u.tms as datem,";
  137. $sql.= " u.datelastlogin as datel,";
  138. $sql.= " u.datepreviouslogin as datep,";
  139. $sql.= " u.photo as photo,";
  140. $sql.= " u.openid as openid,";
  141. $sql.= " u.accountancy_code,";
  142. $sql.= " u.thm,";
  143. $sql.= " u.tjm,";
  144. $sql.= " u.salary,";
  145. $sql.= " u.salaryextra,";
  146. $sql.= " u.weeklyhours,";
  147. $sql.= " u.color,";
  148. $sql.= " u.ref_int, u.ref_ext";
  149. $sql.= " FROM ".MAIN_DB_PREFIX."user as u";
  150. if ((empty($conf->multicompany->enabled) || empty($conf->multicompany->transverse_mode)) && (! empty($user->entity)))
  151. {
  152. $sql.= " WHERE u.entity IN (0,".$conf->entity.")";
  153. }
  154. else
  155. {
  156. $sql.= " WHERE u.entity IS NOT NULL";
  157. }
  158. if ($sid) // permet une recherche du user par son SID ActiveDirectory ou Samba
  159. {
  160. $sql.= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."') LIMIT 1";
  161. }
  162. else if ($login)
  163. {
  164. $sql.= " AND u.login = '".$this->db->escape($login)."'";
  165. }
  166. else
  167. {
  168. $sql.= " AND u.rowid = ".$id;
  169. }
  170. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  171. $result = $this->db->query($sql);
  172. if ($result)
  173. {
  174. $obj = $this->db->fetch_object($result);
  175. if ($obj)
  176. {
  177. $this->id = $obj->rowid;
  178. $this->ref = $obj->rowid;
  179. $this->ref_int = $obj->ref_int;
  180. $this->ref_ext = $obj->ref_ext;
  181. $this->ldap_sid = $obj->ldap_sid;
  182. $this->lastname = $obj->lastname;
  183. $this->firstname = $obj->firstname;
  184. $this->login = $obj->login;
  185. $this->pass_indatabase = $obj->pass;
  186. $this->pass_indatabase_crypted = $obj->pass_crypted;
  187. $this->pass = $obj->pass;
  188. $this->pass_temp = $obj->pass_temp;
  189. $this->office_phone = $obj->office_phone;
  190. $this->office_fax = $obj->office_fax;
  191. $this->user_mobile = $obj->user_mobile;
  192. $this->email = $obj->email;
  193. $this->skype = $obj->skype;
  194. $this->job = $obj->job;
  195. $this->signature = $obj->signature;
  196. $this->admin = $obj->admin;
  197. $this->note = $obj->note;
  198. $this->statut = $obj->statut;
  199. $this->photo = $obj->photo;
  200. $this->openid = $obj->openid;
  201. $this->lang = $obj->lang;
  202. $this->entity = $obj->entity;
  203. $this->accountancy_code = $obj->accountancy_code;
  204. $this->thm = $obj->thm;
  205. $this->tjm = $obj->tjm;
  206. $this->salary = $obj->salary;
  207. $this->salaryextra = $obj->salaryextra;
  208. $this->weeklyhours = $obj->weeklyhours;
  209. $this->color = $obj->color;
  210. $this->datec = $this->db->jdate($obj->datec);
  211. $this->datem = $this->db->jdate($obj->datem);
  212. $this->datelastlogin = $this->db->jdate($obj->datel);
  213. $this->datepreviouslogin = $this->db->jdate($obj->datep);
  214. $this->societe_id = $obj->fk_societe; // deprecated
  215. $this->contact_id = $obj->fk_socpeople; // deprecated
  216. $this->socid = $obj->fk_societe;
  217. $this->contactid = $obj->fk_socpeople;
  218. $this->fk_member = $obj->fk_member;
  219. $this->fk_user = $obj->fk_user;
  220. // Retreive all extrafield for thirdparty
  221. // fetch optionals attributes and labels
  222. require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
  223. $extrafields=new ExtraFields($this->db);
  224. $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
  225. $this->fetch_optionals($this->id,$extralabels);
  226. $this->db->free($result);
  227. }
  228. else
  229. {
  230. $this->error="USERNOTFOUND";
  231. dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
  232. $this->db->free($result);
  233. return 0;
  234. }
  235. }
  236. else
  237. {
  238. $this->error=$this->db->error();
  239. return -1;
  240. }
  241. // To get back the global configuration unique to the user
  242. if ($loadpersonalconf)
  243. {
  244. $sql = "SELECT param, value FROM ".MAIN_DB_PREFIX."user_param";
  245. $sql.= " WHERE fk_user = ".$this->id;
  246. $sql.= " AND entity = ".$conf->entity;
  247. //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
  248. $resql=$this->db->query($sql);
  249. if ($resql)
  250. {
  251. $num = $this->db->num_rows($resql);
  252. $i = 0;
  253. while ($i < $num)
  254. {
  255. $obj = $this->db->fetch_object($resql);
  256. $p=(! empty($obj->param)?$obj->param:'');
  257. if (! empty($p)) $this->conf->$p = $obj->value;
  258. $i++;
  259. }
  260. $this->db->free($resql);
  261. }
  262. else
  263. {
  264. $this->error=$this->db->error();
  265. return -2;
  266. }
  267. }
  268. return 1;
  269. }
  270. /**
  271. * Add a right to the user
  272. *
  273. * @param int $rid id du droit a ajouter
  274. * @param string $allmodule Ajouter tous les droits du module allmodule
  275. * @param string $allperms Ajouter tous les droits du module allmodule, perms allperms
  276. * @param int $entity Entity to use
  277. * @return int > 0 if OK, < 0 if KO
  278. */
  279. function addrights($rid, $allmodule='', $allperms='', $entity='')
  280. {
  281. global $conf;
  282. $entity = (! empty($entity)?$entity:$conf->entity);
  283. dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity");
  284. $err=0;
  285. $whereforadd='';
  286. $this->db->begin();
  287. if (! empty($rid))
  288. {
  289. // Si on a demande ajout d'un droit en particulier, on recupere
  290. // les caracteristiques (module, perms et subperms) de ce droit.
  291. $sql = "SELECT module, perms, subperms";
  292. $sql.= " FROM ".MAIN_DB_PREFIX."rights_def";
  293. $sql.= " WHERE id = '".$this->db->escape($rid)."'";
  294. $sql.= " AND entity = ".$entity;
  295. $result=$this->db->query($sql);
  296. if ($result) {
  297. $obj = $this->db->fetch_object($result);
  298. $module=$obj->module;
  299. $perms=$obj->perms;
  300. $subperms=$obj->subperms;
  301. }
  302. else {
  303. $err++;
  304. dol_print_error($this->db);
  305. }
  306. // Where pour la liste des droits a ajouter
  307. $whereforadd="id=".$this->db->escape($rid);
  308. // Ajout des droits induits
  309. if (! empty($subperms)) $whereforadd.=" OR (module='$module' AND perms='$perms' AND (subperms='lire' OR subperms='read'))";
  310. else if (! empty($perms)) $whereforadd.=" OR (module='$module' AND (perms='lire' OR perms='read') AND subperms IS NULL)";
  311. }
  312. else {
  313. // On a pas demande un droit en particulier mais une liste de droits
  314. // sur la base d'un nom de module de de perms
  315. // Where pour la liste des droits a ajouter
  316. if (! empty($allmodule)) $whereforadd="module='".$this->db->escape($allmodule)."'";
  317. if (! empty($allperms)) $whereforadd=" AND perms='".$this->db->escape($allperms)."'";
  318. }
  319. // Ajout des droits trouves grace au critere whereforadd
  320. if (! empty($whereforadd))
  321. {
  322. //print "$module-$perms-$subperms";
  323. $sql = "SELECT id";
  324. $sql.= " FROM ".MAIN_DB_PREFIX."rights_def";
  325. $sql.= " WHERE ".$whereforadd;
  326. $sql.= " AND entity = ".$entity;
  327. $result=$this->db->query($sql);
  328. if ($result)
  329. {
  330. $num = $this->db->num_rows($result);
  331. $i = 0;
  332. while ($i < $num)
  333. {
  334. $obj = $this->db->fetch_object($result);
  335. $nid = $obj->id;
  336. $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = ".$this->id." AND fk_id=".$nid;
  337. if (! $this->db->query($sql)) $err++;
  338. $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rights (fk_user, fk_id) VALUES (".$this->id.", ".$nid.")";
  339. if (! $this->db->query($sql)) $err++;
  340. $i++;
  341. }
  342. }
  343. else
  344. {
  345. $err++;
  346. dol_print_error($this->db);
  347. }
  348. }
  349. if ($err) {
  350. $this->db->rollback();
  351. return -$err;
  352. }
  353. else {
  354. $this->db->commit();
  355. return 1;
  356. }
  357. }
  358. /**
  359. * Remove a right to the user
  360. *
  361. * @param int $rid Id du droit a retirer
  362. * @param string $allmodule Retirer tous les droits du module allmodule
  363. * @param string $allperms Retirer tous les droits du module allmodule, perms allperms
  364. * @param int $entity Entity to use
  365. * @return int > 0 if OK, < 0 if OK
  366. */
  367. function delrights($rid, $allmodule='', $allperms='', $entity='')
  368. {
  369. global $conf;
  370. $err=0;
  371. $wherefordel='';
  372. $entity = (! empty($entity)?$entity:$conf->entity);
  373. $this->db->begin();
  374. if (! empty($rid))
  375. {
  376. // Si on a demande supression d'un droit en particulier, on recupere
  377. // les caracteristiques module, perms et subperms de ce droit.
  378. $sql = "SELECT module, perms, subperms";
  379. $sql.= " FROM ".MAIN_DB_PREFIX."rights_def";
  380. $sql.= " WHERE id = '".$this->db->escape($rid)."'";
  381. $sql.= " AND entity = ".$entity;
  382. $result=$this->db->query($sql);
  383. if ($result) {
  384. $obj = $this->db->fetch_object($result);
  385. $module=$obj->module;
  386. $perms=$obj->perms;
  387. $subperms=$obj->subperms;
  388. }
  389. else {
  390. $err++;
  391. dol_print_error($this->db);
  392. }
  393. // Where pour la liste des droits a supprimer
  394. $wherefordel="id=".$this->db->escape($rid);
  395. // Suppression des droits induits
  396. if ($subperms=='lire' || $subperms=='read') $wherefordel.=" OR (module='$module' AND perms='$perms' AND subperms IS NOT NULL)";
  397. if ($perms=='lire' || $perms=='read') $wherefordel.=" OR (module='$module')";
  398. }
  399. else {
  400. // On a demande suppression d'un droit sur la base d'un nom de module ou perms
  401. // Where pour la liste des droits a supprimer
  402. if (! empty($allmodule)) $wherefordel="module='".$this->db->escape($allmodule)."'";
  403. if (! empty($allperms)) $wherefordel=" AND perms='".$this->db->escape($allperms)."'";
  404. }
  405. // Suppression des droits selon critere defini dans wherefordel
  406. if (! empty($wherefordel))
  407. {
  408. //print "$module-$perms-$subperms";
  409. $sql = "SELECT id";
  410. $sql.= " FROM ".MAIN_DB_PREFIX."rights_def";
  411. $sql.= " WHERE $wherefordel";
  412. $sql.= " AND entity = ".$entity;
  413. $result=$this->db->query($sql);
  414. if ($result)
  415. {
  416. $num = $this->db->num_rows($result);
  417. $i = 0;
  418. while ($i < $num)
  419. {
  420. $obj = $this->db->fetch_object($result);
  421. $nid = $obj->id;
  422. $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights";
  423. $sql.= " WHERE fk_user = ".$this->id." AND fk_id=".$nid;
  424. if (! $this->db->query($sql)) $err++;
  425. $i++;
  426. }
  427. }
  428. else
  429. {
  430. $err++;
  431. dol_print_error($this->db);
  432. }
  433. }
  434. if ($err) {
  435. $this->db->rollback();
  436. return -$err;
  437. }
  438. else {
  439. $this->db->commit();
  440. return 1;
  441. }
  442. }
  443. /**
  444. * Clear all permissions array of user
  445. *
  446. * @return void
  447. * @see getrights
  448. */
  449. function clearrights()
  450. {
  451. dol_syslog(get_class($this)."::clearrights reset user->rights");
  452. $this->rights='';
  453. $this->all_permissions_are_loaded=false;
  454. $this->_tab_loaded=array();
  455. }
  456. /**
  457. * Load permissions granted to user into object user
  458. *
  459. * @param string $moduletag Limit permission for a particular module ('' by default means load all permissions)
  460. * @return void
  461. * @see clearrights
  462. */
  463. function getrights($moduletag='')
  464. {
  465. global $conf;
  466. if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag])
  467. {
  468. // Le fichier de ce module est deja charge
  469. return;
  470. }
  471. if ($this->all_permissions_are_loaded)
  472. {
  473. // Si les permissions ont deja ete charge pour ce user, on quitte
  474. return;
  475. }
  476. // Recuperation des droits utilisateurs + recuperation des droits groupes
  477. // D'abord les droits utilisateurs
  478. $sql = "SELECT r.module, r.perms, r.subperms";
  479. $sql.= " FROM ".MAIN_DB_PREFIX."user_rights as ur";
  480. $sql.= ", ".MAIN_DB_PREFIX."rights_def as r";
  481. $sql.= " WHERE r.id = ur.fk_id";
  482. $sql.= " AND r.entity IN (0,".(! empty($conf->multicompany->enabled) && ! empty($conf->multicompany->transverse_mode)?"1,":"").$conf->entity.")";
  483. $sql.= " AND ur.fk_user= ".$this->id;
  484. $sql.= " AND r.perms IS NOT NULL";
  485. if ($moduletag) $sql.= " AND r.module = '".$this->db->escape($moduletag)."'";
  486. dol_syslog(get_class($this).'::getrights', LOG_DEBUG);
  487. $resql = $this->db->query($sql);
  488. if ($resql)
  489. {
  490. $num = $this->db->num_rows($resql);
  491. $i = 0;
  492. while ($i < $num)
  493. {
  494. $obj = $this->db->fetch_object($resql);
  495. $module=$obj->module;
  496. $perms=$obj->perms;
  497. $subperms=$obj->subperms;
  498. if ($perms)
  499. {
  500. if (! isset($this->rights) || ! is_object($this->rights)) $this->rights = new stdClass(); // For avoid error
  501. if (! isset($this->rights->$module) || ! is_object($this->rights->$module)) $this->rights->$module = new stdClass();
  502. if ($subperms)
  503. {
  504. if (! isset($this->rights->$module->$perms) || ! is_object($this->rights->$module->$perms)) $this->rights->$module->$perms = new stdClass();
  505. $this->rights->$module->$perms->$subperms = 1;
  506. }
  507. else
  508. {
  509. $this->rights->$module->$perms = 1;
  510. }
  511. }
  512. $i++;
  513. }
  514. $this->db->free($resql);
  515. }
  516. // Maintenant les droits groupes
  517. $sql = "SELECT r.module, r.perms, r.subperms";
  518. $sql.= " FROM ".MAIN_DB_PREFIX."usergroup_rights as gr,";
  519. $sql.= " ".MAIN_DB_PREFIX."usergroup_user as gu,";
  520. $sql.= " ".MAIN_DB_PREFIX."rights_def as r";
  521. $sql.= " WHERE r.id = gr.fk_id";
  522. if (! empty($conf->multicompany->enabled) && ! empty($conf->multicompany->transverse_mode)) {
  523. $sql.= " AND gu.entity IN (0,".$conf->entity.")";
  524. } else {
  525. $sql.= " AND r.entity = ".$conf->entity;
  526. }
  527. $sql.= " AND gr.fk_usergroup = gu.fk_usergroup";
  528. $sql.= " AND gu.fk_user = ".$this->id;
  529. $sql.= " AND r.perms IS NOT NULL";
  530. if ($moduletag) $sql.= " AND r.module = '".$this->db->escape($moduletag)."'";
  531. dol_syslog(get_class($this).'::getrights', LOG_DEBUG);
  532. $resql = $this->db->query($sql);
  533. if ($resql)
  534. {
  535. $num = $this->db->num_rows($resql);
  536. $i = 0;
  537. while ($i < $num)
  538. {
  539. $obj = $this->db->fetch_object($resql);
  540. $module=$obj->module;
  541. $perms=$obj->perms;
  542. $subperms=$obj->subperms;
  543. if ($perms)
  544. {
  545. if (! isset($this->rights) || ! is_object($this->rights)) $this->rights = new stdClass(); // For avoid error
  546. if (! isset($this->rights->$module) || ! is_object($this->rights->$module)) $this->rights->$module = new stdClass();
  547. if ($subperms)
  548. {
  549. if (! isset($this->rights->$module->$perms) || ! is_object($this->rights->$module->$perms)) $this->rights->$module->$perms = new stdClass();
  550. $this->rights->$module->$perms->$subperms = 1;
  551. }
  552. else
  553. {
  554. $this->rights->$module->$perms = 1;
  555. }
  556. }
  557. $i++;
  558. }
  559. $this->db->free($resql);
  560. }
  561. // For backward compatibility
  562. if (isset($this->rights->propale))
  563. {
  564. $this->rights->propal = $this->rights->propale;
  565. }
  566. if (! $moduletag)
  567. {
  568. // Si module etait non defini, alors on a tout charge, on peut donc considerer
  569. // que les droits sont en cache (car tous charges) pour cet instance de user
  570. $this->all_permissions_are_loaded=1;
  571. }
  572. else
  573. {
  574. // Si module defini, on le marque comme charge en cache
  575. $this->_tab_loaded[$moduletag]=1;
  576. }
  577. }
  578. /**
  579. * Change status of a user
  580. *
  581. * @param int $statut Status to set
  582. * @return int <0 if KO, 0 if nothing is done, >0 if OK
  583. */
  584. function setstatus($statut)
  585. {
  586. global $conf,$langs,$user;
  587. $error=0;
  588. // Check parameters
  589. if ($this->statut == $statut) return 0;
  590. else $this->statut = $statut;
  591. $this->db->begin();
  592. // Deactivate user
  593. $sql = "UPDATE ".MAIN_DB_PREFIX."user";
  594. $sql.= " SET statut = ".$this->statut;
  595. $sql.= " WHERE rowid = ".$this->id;
  596. $result = $this->db->query($sql);
  597. dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
  598. if ($result)
  599. {
  600. // Call trigger
  601. $result=$this->call_trigger('USER_ENABLEDISABLE',$user);
  602. if ($result < 0) { $error++; }
  603. // End call triggers
  604. }
  605. if ($error)
  606. {
  607. $this->db->rollback();
  608. return -$error;
  609. }
  610. else
  611. {
  612. $this->db->commit();
  613. return 1;
  614. }
  615. }
  616. /**
  617. * Delete the user
  618. *
  619. * @return int <0 if KO, >0 if OK
  620. */
  621. function delete()
  622. {
  623. global $user,$conf,$langs;
  624. $error=0;
  625. $this->db->begin();
  626. $this->fetch($this->id);
  627. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  628. // Remove rights
  629. $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = ".$this->id;
  630. if (! $error && ! $this->db->query($sql))
  631. {
  632. $error++;
  633. $this->error = $this->db->lasterror();
  634. }
  635. // Remove group
  636. $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user WHERE fk_user = ".$this->id;
  637. if (! $error && ! $this->db->query($sql))
  638. {
  639. $error++;
  640. $this->error = $this->db->lasterror();
  641. }
  642. // If contact, remove link
  643. if ($this->contact_id)
  644. {
  645. $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET fk_user_creat = null WHERE rowid = ".$this->contact_id;
  646. if (! $error && ! $this->db->query($sql))
  647. {
  648. $error++;
  649. $this->error = $this->db->lasterror();
  650. }
  651. }
  652. // Remove extrafields
  653. if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
  654. {
  655. $result=$this->deleteExtraFields();
  656. if ($result < 0)
  657. {
  658. $error++;
  659. dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
  660. }
  661. }
  662. // Remove user
  663. if (! $error)
  664. {
  665. $sql = "DELETE FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->id;
  666. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  667. if (! $this->db->query($sql))
  668. {
  669. $error++;
  670. $this->error = $this->db->lasterror();
  671. }
  672. }
  673. if (! $error)
  674. {
  675. // Call trigger
  676. $result=$this->call_trigger('USER_DELETE',$user);
  677. if ($result < 0)
  678. {
  679. $error++;
  680. $this->db->rollback();
  681. return -1;
  682. }
  683. // End call triggers
  684. $this->db->commit();
  685. return 1;
  686. }
  687. else
  688. {
  689. $this->db->rollback();
  690. return -1;
  691. }
  692. }
  693. /**
  694. * Create a user into database
  695. *
  696. * @param User $user Objet user qui demande la creation
  697. * @param int $notrigger 1 ne declenche pas les triggers, 0 sinon
  698. * @return int <0 si KO, id compte cree si OK
  699. */
  700. function create($user,$notrigger=0)
  701. {
  702. global $conf,$langs;
  703. global $mysoc;
  704. // Clean parameters
  705. $this->login = trim($this->login);
  706. if (! isset($this->entity)) $this->entity=$conf->entity; // If not defined, we use default value
  707. dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user)?$user->id:''), LOG_DEBUG);
  708. // Check parameters
  709. if (! empty($conf->global->USER_MAIL_REQUIRED) && ! isValidEMail($this->email))
  710. {
  711. $langs->load("errors");
  712. $this->error = $langs->trans("ErrorBadEMail",$this->email);
  713. return -1;
  714. }
  715. $this->datec = dol_now();
  716. $error=0;
  717. $this->db->begin();
  718. $sql = "SELECT login FROM ".MAIN_DB_PREFIX."user";
  719. $sql.= " WHERE login ='".$this->db->escape($this->login)."'";
  720. $sql.= " AND entity IN (0,".$this->db->escape($conf->entity).")";
  721. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  722. $resql=$this->db->query($sql);
  723. if ($resql)
  724. {
  725. $num = $this->db->num_rows($resql);
  726. $this->db->free($resql);
  727. if ($num)
  728. {
  729. $this->error = 'ErrorLoginAlreadyExists';
  730. dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
  731. $this->db->rollback();
  732. return -6;
  733. }
  734. else
  735. {
  736. $sql = "INSERT INTO ".MAIN_DB_PREFIX."user (datec,login,ldap_sid,entity)";
  737. $sql.= " VALUES('".$this->db->idate($this->datec)."','".$this->db->escape($this->login)."','".$this->db->escape($this->ldap_sid)."',".$this->db->escape($this->entity).")";
  738. $result=$this->db->query($sql);
  739. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  740. if ($result)
  741. {
  742. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."user");
  743. // Set default rights
  744. if ($this->set_default_rights() < 0)
  745. {
  746. $this->error='ErrorFailedToSetDefaultRightOfUser';
  747. $this->db->rollback();
  748. return -5;
  749. }
  750. // Update minor fields
  751. $result = $this->update($user,1,1);
  752. if ($result < 0)
  753. {
  754. $this->db->rollback();
  755. return -4;
  756. }
  757. if (! empty($conf->global->STOCK_USERSTOCK_AUTOCREATE))
  758. {
  759. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  760. $langs->load("stocks");
  761. $entrepot = new Entrepot($this->db);
  762. $entrepot->libelle = $langs->trans("PersonalStock",$this->getFullName($langs));
  763. $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock",$this->getFullName($langs));
  764. $entrepot->statut = 1;
  765. $entrepot->country_id = $mysoc->country_id;
  766. $entrepot->create($user);
  767. }
  768. if (! $notrigger)
  769. {
  770. // Call trigger
  771. $result=$this->call_trigger('USER_CREATE',$user);
  772. if ($result < 0) { $error++; }
  773. // End call triggers
  774. }
  775. if (! $error)
  776. {
  777. $this->db->commit();
  778. return $this->id;
  779. }
  780. else
  781. {
  782. //$this->error=$interface->error;
  783. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  784. $this->db->rollback();
  785. return -3;
  786. }
  787. }
  788. else
  789. {
  790. $this->error=$this->db->lasterror();
  791. $this->db->rollback();
  792. return -2;
  793. }
  794. }
  795. }
  796. else
  797. {
  798. $this->error=$this->db->lasterror();
  799. $this->db->rollback();
  800. return -1;
  801. }
  802. }
  803. /**
  804. * Create a user from a contact object. User will be internal but if contact is linked to a third party, user will be external
  805. *
  806. * @param Contact $contact Object for source contact
  807. * @param string $login Login to force
  808. * @param string $password Password to force
  809. * @return int <0 if error, if OK returns id of created user
  810. */
  811. function create_from_contact($contact,$login='',$password='')
  812. {
  813. global $conf,$user,$langs;
  814. $error=0;
  815. // Positionne parametres
  816. $this->admin = 0;
  817. $this->lastname = $contact->lastname;
  818. $this->firstname = $contact->firstname;
  819. $this->email = $contact->email;
  820. $this->skype = $contact->skype;
  821. $this->office_phone = $contact->phone_pro;
  822. $this->office_fax = $contact->fax;
  823. $this->user_mobile = $contact->phone_mobile;
  824. $this->address = $contact->address;
  825. $this->zip = $contact->zip;
  826. $this->town = $contact->town;
  827. $this->state_id = $contact->state_id;
  828. $this->country_id = $contact->country_id;
  829. if (empty($login)) $login=strtolower(substr($contact->firstname, 0, 4)) . strtolower(substr($contact->lastname, 0, 4));
  830. $this->login = $login;
  831. $this->db->begin();
  832. // Cree et positionne $this->id
  833. $result=$this->create($user);
  834. if ($result > 0)
  835. {
  836. $sql = "UPDATE ".MAIN_DB_PREFIX."user";
  837. $sql.= " SET fk_socpeople=".$contact->id;
  838. if ($contact->socid) $sql.=", fk_societe=".$contact->socid;
  839. $sql.= " WHERE rowid=".$this->id;
  840. $resql=$this->db->query($sql);
  841. dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
  842. if ($resql)
  843. {
  844. // Call trigger
  845. $result=$this->call_trigger('USER_CREATE_FROM_CONTACT',$user);
  846. if ($result < 0) { $error++; $this->db->rollback(); return -1; }
  847. // End call triggers
  848. $this->db->commit();
  849. return $this->id;
  850. }
  851. else
  852. {
  853. $this->error=$this->db->error();
  854. $this->db->rollback();
  855. return -1;
  856. }
  857. }
  858. else
  859. {
  860. // $this->error deja positionne
  861. dol_syslog(get_class($this)."::create_from_contact - 0");
  862. $this->db->rollback();
  863. return $result;
  864. }
  865. }
  866. /**
  867. * Create a user into database from a member object
  868. *
  869. * @param Adherent $member Object member source
  870. * @param string $login Login to force
  871. * @return int <0 if KO, if OK, return id of created account
  872. */
  873. function create_from_member($member,$login='')
  874. {
  875. global $conf,$user,$langs;
  876. // Positionne parametres
  877. $this->admin = 0;
  878. $this->lastname = $member->lastname;
  879. $this->firstname = $member->firstname;
  880. $this->email = $member->email;
  881. $this->fk_member = $member->id;
  882. $this->pass = $member->pass;
  883. $this->address = $member->address;
  884. $this->zip = $member->zip;
  885. $this->town = $member->town;
  886. $this->state_id = $member->state_id;
  887. $this->country_id = $member->country_id;
  888. if (empty($login)) $login=strtolower(substr($member->firstname, 0, 4)) . strtolower(substr($member->lastname, 0, 4));
  889. $this->login = $login;
  890. $this->db->begin();
  891. // Create and set $this->id
  892. $result=$this->create($user);
  893. if ($result > 0)
  894. {
  895. $newpass=$this->setPassword($user,$this->pass);
  896. if (is_numeric($newpass) && $newpass < 0) $result=-2;
  897. if ($result > 0 && $member->fk_soc) // If member is linked to a thirdparty
  898. {
  899. $sql = "UPDATE ".MAIN_DB_PREFIX."user";
  900. $sql.= " SET fk_societe=".$member->fk_soc;
  901. $sql.= " WHERE rowid=".$this->id;
  902. dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
  903. $resql=$this->db->query($sql);
  904. if ($resql)
  905. {
  906. $this->db->commit();
  907. return $this->id;
  908. }
  909. else
  910. {
  911. $this->error=$this->db->lasterror();
  912. $this->db->rollback();
  913. return -1;
  914. }
  915. }
  916. }
  917. if ($result > 0)
  918. {
  919. $this->db->commit();
  920. return $this->id;
  921. }
  922. else
  923. {
  924. // $this->error deja positionne
  925. $this->db->rollback();
  926. return -2;
  927. }
  928. }
  929. /**
  930. * Assign rights by default
  931. *
  932. * @return Si erreur <0, si ok renvoi le nbre de droits par defaut positionnes
  933. */
  934. function set_default_rights()
  935. {
  936. global $conf;
  937. $sql = "SELECT id FROM ".MAIN_DB_PREFIX."rights_def";
  938. $sql.= " WHERE bydefault = 1";
  939. $sql.= " AND entity = ".$conf->entity;
  940. $resql=$this->db->query($sql);
  941. if ($resql)
  942. {
  943. $num = $this->db->num_rows($resql);
  944. $i = 0;
  945. $rd = array();
  946. while ($i < $num)
  947. {
  948. $row = $this->db->fetch_row($resql);
  949. $rd[$i] = $row[0];
  950. $i++;
  951. }
  952. $this->db->free($resql);
  953. }
  954. $i = 0;
  955. while ($i < $num)
  956. {
  957. $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
  958. $result=$this->db->query($sql);
  959. $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
  960. $result=$this->db->query($sql);
  961. if (! $result) return -1;
  962. $i++;
  963. }
  964. return $i;
  965. }
  966. /**
  967. * Update a user into database (and also password if this->pass is defined)
  968. *
  969. * @param User $user User qui fait la mise a jour
  970. * @param int $notrigger 1 ne declenche pas les triggers, 0 sinon
  971. * @param int $nosyncmember 0=Synchronize linked member (standard info), 1=Do not synchronize linked member
  972. * @param int $nosyncmemberpass 0=Synchronize linked member (password), 1=Do not synchronize linked member
  973. * @return int <0 si KO, >=0 si OK
  974. */
  975. function update($user,$notrigger=0,$nosyncmember=0,$nosyncmemberpass=0)
  976. {
  977. global $conf, $langs, $hookmanager;
  978. $nbrowsaffected=0;
  979. $error=0;
  980. dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
  981. // Clean parameters
  982. $this->lastname = trim($this->lastname);
  983. $this->firstname = trim($this->firstname);
  984. $this->login = trim($this->login);
  985. $this->pass = trim($this->pass);
  986. $this->office_phone = trim($this->office_phone);
  987. $this->office_fax = trim($this->office_fax);
  988. $this->user_mobile = trim($this->user_mobile);
  989. $this->email = trim($this->email);
  990. $this->skype = trim($this->skype);
  991. $this->job = trim($this->job);
  992. $this->signature = trim($this->signature);
  993. $this->note = trim($this->note);
  994. $this->openid = trim(empty($this->openid)?'':$this->openid); // Avoid warning
  995. $this->admin = $this->admin?$this->admin:0;
  996. $this->address = empty($this->address)?'':$this->address;
  997. $this->zip = empty($this->zip)?'':$this->zip;
  998. $this->town = empty($this->town)?'':$this->town;
  999. $this->accountancy_code = trim($this->accountancy_code);
  1000. $this->color = empty($this->color)?'':$this->color;
  1001. // Check parameters
  1002. if (! empty($conf->global->USER_MAIL_REQUIRED) && ! isValidEMail($this->email))
  1003. {
  1004. $langs->load("errors");
  1005. $this->error = $langs->trans("ErrorBadEMail",$this->email);
  1006. return -1;
  1007. }
  1008. $this->db->begin();
  1009. // Mise a jour autres infos
  1010. $sql = "UPDATE ".MAIN_DB_PREFIX."user SET";
  1011. $sql.= " lastname = '".$this->db->escape($this->lastname)."'";
  1012. $sql.= ", firstname = '".$this->db->escape($this->firstname)."'";
  1013. $sql.= ", login = '".$this->db->escape($this->login)."'";
  1014. $sql.= ", admin = ".$this->admin;
  1015. $sql.= ", address = '".$this->db->escape($this->address)."'";
  1016. $sql.= ", zip = '".$this->db->escape($this->zip)."'";
  1017. $sql.= ", town = '".$this->db->escape($this->town)."'";
  1018. $sql.= ", fk_state = ".((! empty($this->state_id) && $this->state_id > 0)?"'".$this->db->escape($this->state_id)."'":"null");
  1019. $sql.= ", fk_country = ".((! empty($this->country_id) && $this->country_id > 0)?"'".$this->db->escape($this->country_id)."'":"null");
  1020. $sql.= ", office_phone = '".$this->db->escape($this->office_phone)."'";
  1021. $sql.= ", office_fax = '".$this->db->escape($this->office_fax)."'";
  1022. $sql.= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
  1023. $sql.= ", email = '".$this->db->escape($this->email)."'";
  1024. $sql.= ", skype = '".$this->db->escape($this->skype)."'";
  1025. $sql.= ", job = '".$this->db->escape($this->job)."'";
  1026. $sql.= ", signature = '".$this->db->escape($this->signature)."'";
  1027. $sql.= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
  1028. $sql.= ", color = '".$this->db->escape($this->color)."'";
  1029. $sql.= ", note = '".$this->db->escape($this->note)."'";
  1030. $sql.= ", photo = ".($this->photo?"'".$this->db->escape($this->photo)."'":"null");
  1031. $sql.= ", openid = ".($this->openid?"'".$this->db->escape($this->openid)."'":"null");
  1032. $sql.= ", fk_user = ".($this->fk_user > 0?"'".$this->db->escape($this->fk_user)."'":"null");
  1033. if (isset($this->thm) || $this->thm != '') $sql.= ", thm= ".($this->thm != ''?"'".$this->db->escape($this->thm)."'":"null");
  1034. if (isset($this->tjm) || $this->tjm != '') $sql.= ", tjm= ".($this->tjm != ''?"'".$this->db->escape($this->tjm)."'":"null");
  1035. if (isset($this->salary) || $this->salary != '') $sql.= ", salary= ".($this->salary != ''?"'".$this->db->escape($this->salary)."'":"null");
  1036. if (isset($this->salaryextra) || $this->salaryextra != '') $sql.= ", salaryextra= ".($this->salaryextra != ''?"'".$this->db->escape($this->salaryextra)."'":"null");
  1037. $sql.= ", weeklyhours= ".($this->weeklyhours != ''?"'".$this->db->escape($this->weeklyhours)."'":"null");
  1038. $sql.= ", entity = '".$this->entity."'";
  1039. $sql.= " WHERE rowid = ".$this->id;
  1040. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  1041. $resql = $this->db->query($sql);
  1042. if ($resql)
  1043. {
  1044. $nbrowsaffected+=$this->db->affected_rows($resql);
  1045. // Update password
  1046. if ($this->pass)
  1047. {
  1048. if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted)
  1049. {
  1050. // Si mot de passe saisi et different de celui en base
  1051. $result=$this->setPassword($user,$this->pass,0,$notrigger,$nosyncmemberpass);
  1052. if (! $nbrowsaffected) $nbrowsaffected++;
  1053. }
  1054. }
  1055. // If user is linked to a member, remove old link to this member
  1056. if ($this->fk_member > 0)
  1057. {
  1058. $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL where fk_member = ".$this->fk_member;
  1059. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  1060. $resql = $this->db->query($sql);
  1061. if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -5; }
  1062. }
  1063. // Set link to user
  1064. $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member =".($this->fk_member>0?$this->fk_member:'null')." where rowid = ".$this->id;
  1065. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  1066. $resql = $this->db->query($sql);
  1067. if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -5; }
  1068. if ($nbrowsaffected) // If something has changed in data
  1069. {
  1070. if ($this->fk_member > 0 && ! $nosyncmember)
  1071. {
  1072. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  1073. // This user is linked with a member, so we also update members informations
  1074. // if this is an update.
  1075. $adh=new Adherent($this->db);
  1076. $result=$adh->fetch($this->fk_member);
  1077. if ($result >= 0)
  1078. {
  1079. $adh->firstname=$this->firstname;
  1080. $adh->lastname=$this->lastname;
  1081. $adh->login=$this->login;
  1082. $adh->pass=$this->pass;
  1083. $adh->societe=(empty($adh->societe) && $this->societe_id ? $this->societe_id : $adh->societe);
  1084. $adh->email=$this->email;
  1085. $adh->skype=$this->skype;
  1086. $adh->phone=$this->office_phone;
  1087. $adh->phone_mobile=$this->user_mobile;
  1088. $adh->note=$this->note;
  1089. $adh->user_id=$this->id;
  1090. $adh->user_login=$this->login;
  1091. $result=$adh->update($user,0,1);
  1092. if ($result < 0)
  1093. {
  1094. $this->error=$luser->error;
  1095. dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
  1096. $error++;
  1097. }
  1098. }
  1099. else
  1100. {
  1101. $this->error=$adh->error;
  1102. $error++;
  1103. }
  1104. }
  1105. }
  1106. $action='update';
  1107. // Actions on extra fields (by external module or standard code)
  1108. // FIXME le hook fait double emploi avec le trigger !!
  1109. $hookmanager->initHooks(array('userdao'));
  1110. $parameters=array('socid'=>$this->id);
  1111. $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  1112. if (empty($reshook))
  1113. {
  1114. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  1115. {
  1116. $result=$this->insertExtraFields();
  1117. if ($result < 0)
  1118. {
  1119. $error++;
  1120. }
  1121. }
  1122. }
  1123. else if ($reshook < 0) $error++;
  1124. if (! $error && ! $notrigger)
  1125. {
  1126. // Call trigger
  1127. $result=$this->call_trigger('USER_MODIFY',$user);
  1128. if ($result < 0) { $error++; }
  1129. // End call triggers
  1130. }
  1131. if (! $error)
  1132. {
  1133. $this->db->commit();
  1134. return $nbrowsaffected;
  1135. }
  1136. else
  1137. {
  1138. dol_syslog(get_class($this)."::update error=".$this->error,LOG_ERR);
  1139. $this->db->rollback();
  1140. return -1;
  1141. }
  1142. }
  1143. else
  1144. {
  1145. $this->error=$this->db->lasterror();
  1146. $this->db->rollback();
  1147. return -2;
  1148. }
  1149. }
  1150. /**
  1151. * Mise a jour en base de la date de derniere connexion d'un utilisateur
  1152. * Fonction appelee lors d'une nouvelle connexion
  1153. *
  1154. * @return <0 si echec, >=0 si ok
  1155. */
  1156. function update_last_login_date()
  1157. {
  1158. $now=dol_now();
  1159. $sql = "UPDATE ".MAIN_DB_PREFIX."user SET";
  1160. $sql.= " datepreviouslogin = datelastlogin,";
  1161. $sql.= " datelastlogin = '".$this->db->idate($now)."',";
  1162. $sql.= " tms = tms"; // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
  1163. $sql.= " WHERE rowid = ".$this->id;
  1164. dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
  1165. $resql = $this->db->query($sql);
  1166. if ($resql)
  1167. {
  1168. $this->datepreviouslogin=$this->datelastlogin;
  1169. $this->datelastlogin=$now;
  1170. return 1;
  1171. }
  1172. else
  1173. {
  1174. $this->error=$this->db->lasterror().' sql='.$sql;
  1175. return -1;
  1176. }
  1177. }
  1178. /**
  1179. * Change password of a user
  1180. *
  1181. * @param User $user Object user of user making change
  1182. * @param string $password New password in clear text (to generate if not provided)
  1183. * @param int $changelater 1=Change password only after clicking on confirm email
  1184. * @param int $notrigger 1=Does not launch triggers
  1185. * @param int $nosyncmember Do not synchronize linked member
  1186. * @return string If OK return clear password, 0 if no change, < 0 if error
  1187. */
  1188. function setPassword($user, $password='', $changelater=0, $notrigger=0, $nosyncmember=0)
  1189. {
  1190. global $conf, $langs;
  1191. require_once DOL_DOCUMENT_ROOT .'/core/lib/security2.lib.php';
  1192. $error=0;
  1193. dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i','*',$password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
  1194. // If new password not provided, we generate one
  1195. if (! $password)
  1196. {
  1197. $password=getRandomPassword(false);
  1198. }
  1199. // Crypte avec md5
  1200. $password_crypted = dol_hash($password);
  1201. // Mise a jour
  1202. if (! $changelater)
  1203. {
  1204. if (! is_object($this->oldcopy)) $this->oldcopy=dol_clone($this);
  1205. $this->db->begin();
  1206. $sql = "UPDATE ".MAIN_DB_PREFIX."user";
  1207. $sql.= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
  1208. $sql.= " pass_temp = null";
  1209. if (! empty($conf->global->DATABASE_PWD_ENCRYPTED))
  1210. {
  1211. $sql.= ", pass = null";
  1212. }
  1213. else
  1214. {
  1215. $sql.= ", pass = '".$this->db->escape($password)."'";
  1216. }
  1217. $sql.= " WHERE rowid = ".$this->id;
  1218. dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
  1219. $result = $this->db->query($sql);
  1220. if ($result)
  1221. {
  1222. if ($this->db->affected_rows($result))
  1223. {
  1224. $this->pass=$password;
  1225. $this->pass_indatabase=$password;
  1226. $this->pass_indatabase_crypted=$password_crypted;
  1227. if ($this->fk_member && ! $nosyncmember)
  1228. {
  1229. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  1230. // This user is linked with a member, so we also update members informations
  1231. // if this is an update.
  1232. $adh=new Adherent($this->db);
  1233. $result=$adh->fetch($this->fk_member);
  1234. if ($result >= 0)
  1235. {
  1236. $result=$adh->setPassword($user,$this->pass,0,1); // Cryptage non gere dans module adherent
  1237. if ($result < 0)
  1238. {
  1239. $this->error=$adh->error;
  1240. dol_syslog(get_class($this)."::setPassword ".$this->error,LOG_ERR);
  1241. $error++;
  1242. }
  1243. }
  1244. else
  1245. {
  1246. $this->error=$adh->error;
  1247. $error++;
  1248. }
  1249. }
  1250. dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error,LOG_DEBUG);
  1251. if (! $error && ! $notrigger)
  1252. {
  1253. // Call trigger
  1254. $result=$this->call_trigger('USER_NEW_PASSWORD',$user);
  1255. if ($result < 0) { $error++; $this->db->rollback(); return -1; }
  1256. // End call triggers
  1257. }
  1258. $this->db->commit();
  1259. return $this->pass;
  1260. }
  1261. else
  1262. {
  1263. $this->db->rollback();
  1264. return 0;
  1265. }
  1266. }
  1267. else
  1268. {
  1269. $this->db->rollback();
  1270. dol_print_error($this->db);
  1271. return -1;
  1272. }
  1273. }
  1274. else
  1275. {
  1276. // We store clear password in password temporary field.
  1277. // After receiving confirmation link, we will crypt it and store it in pass_crypted
  1278. $sql = "UPDATE ".MAIN_DB_PREFIX."user";
  1279. $sql.= " SET pass_temp = '".$this->db->escape($password)."'";
  1280. $sql.= " WHERE rowid = ".$this->id;
  1281. dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
  1282. $result = $this->db->query($sql);
  1283. if ($result)
  1284. {
  1285. return $password;
  1286. }
  1287. else
  1288. {
  1289. dol_print_error($this->db);
  1290. return -3;
  1291. }
  1292. }
  1293. }
  1294. /**
  1295. * Send new password by email
  1296. *
  1297. * @param User $user Object user that send email
  1298. * @param string $password New password
  1299. * @param int $changelater 1=Change password only after clicking on confirm email
  1300. * @return int < 0 si erreur, > 0 si ok
  1301. */
  1302. function send_password($user, $password='', $changelater=0)
  1303. {
  1304. global $conf,$langs;
  1305. global $dolibarr_main_url_root;
  1306. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1307. $msgishtml=0;
  1308. // Define $msg
  1309. $mesg = '';
  1310. $outputlangs=new Translate("",$conf);
  1311. if (isset($this->conf->MAIN_LANG_DEFAULT)
  1312. && $this->conf->MAIN_LANG_DEFAULT != 'auto')
  1313. { // If user has defined its own language (rare because in most cases, auto is used)
  1314. $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
  1315. }
  1316. else
  1317. { // If user has not defined its own language, we used current language
  1318. $outputlangs=$langs;
  1319. }
  1320. $outputlangs->load("main");
  1321. $outputlangs->load("errors");
  1322. $outputlangs->load("users");
  1323. $outputlangs->load("other");
  1324. $subject = $outputlangs->transnoentitiesnoconv("SubjectNewPassword");
  1325. // Define $urlwithroot
  1326. //$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  1327. //$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1328. $urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1329. if (! $changelater)
  1330. {
  1331. $mesg.= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
  1332. $mesg.= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
  1333. $mesg.= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
  1334. $mesg.= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
  1335. $mesg.= "\n";
  1336. $url = $urlwithroot.'/';
  1337. $mesg.= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $conf->global->MAIN_APPLICATION_TITLE).': '.$url."\n\n";
  1338. $mesg.= "--\n";
  1339. $mesg.= $user->getFullName($outputlangs); // Username that make then sending
  1340. }
  1341. else
  1342. {
  1343. $mesg.= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."\n";
  1344. $mesg.= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :\n\n";
  1345. $mesg.= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
  1346. $mesg.= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
  1347. $mesg.= "\n";
  1348. $mesg.= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :\n";
  1349. $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword&username='.$this->login."&passwordhash=".dol_hash($password);
  1350. $mesg.= $url."\n\n";
  1351. $mesg.= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."\n\n";
  1352. dol_syslog(get_class($this)."::send_password url=".$url);
  1353. }
  1354. $mailfile = new CMailFile(
  1355. $subject,
  1356. $this->email,
  1357. $conf->notification->email_from,
  1358. $mesg,
  1359. array(),
  1360. array(),
  1361. array(),
  1362. '',
  1363. '',
  1364. 0,
  1365. $msgishtml
  1366. );
  1367. if ($mailfile->sendfile())
  1368. {
  1369. return 1;
  1370. }
  1371. else
  1372. {
  1373. $langs->trans("errors");
  1374. $this->error=$langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
  1375. return -1;
  1376. }
  1377. }
  1378. /**
  1379. * Renvoie la derniere erreur fonctionnelle de manipulation de l'objet
  1380. *
  1381. * @return string chaine erreur
  1382. */
  1383. function error()
  1384. {
  1385. return $this->error;
  1386. }
  1387. /**
  1388. * Read clicktodial information for user
  1389. *
  1390. * @return <0 if KO, >0 if OK
  1391. */
  1392. function fetch_clicktodial()
  1393. {
  1394. $sql = "SELECT url, login, pass, poste ";
  1395. $sql.= " FROM ".MAIN_DB_PREFIX."user_clicktodial as u";
  1396. $sql.= " WHERE u.fk_user = ".$this->id;
  1397. $resql = $this->db->query($sql);
  1398. if ($resql)
  1399. {
  1400. if ($this->db->num_rows($resql))
  1401. {
  1402. $obj = $this->db->fetch_object($resql);
  1403. $this->clicktodial_url = $obj->url;
  1404. $this->clicktodial_login = $obj->login;
  1405. $this->clicktodial_password = $obj->pass;
  1406. $this->clicktodial_poste = $obj->poste;
  1407. }
  1408. $this->clicktodial_loaded = 1; // Data loaded (found or not)
  1409. $this->db->free($resql);
  1410. return 1;
  1411. }
  1412. else
  1413. {
  1414. $this->error=$this->db->error();
  1415. return -1;
  1416. }
  1417. }
  1418. /**
  1419. * Update clicktodial info
  1420. *
  1421. * @return void
  1422. */
  1423. function update_clicktodial()
  1424. {
  1425. $this->db->begin();
  1426. $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_clicktodial";
  1427. $sql .= " WHERE fk_user = ".$this->id;
  1428. dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
  1429. $result = $this->db->query($sql);
  1430. $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_clicktodial";
  1431. $sql .= " (fk_user,url,login,pass,poste)";
  1432. $sql .= " VALUES (".$this->id;
  1433. $sql .= ", '". $this->db->escape($this->clicktodial_url) ."'";
  1434. $sql .= ", '". $this->db->escape($this->clicktodial_login) ."'";
  1435. $sql .= ", '". $this->db->escape($this->clicktodial_password) ."'";
  1436. $sql .= ", '". $this->db->escape($this->clicktodial_poste) ."')";
  1437. dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
  1438. $result = $this->db->query($sql);
  1439. if ($result)
  1440. {
  1441. $this->db->commit();
  1442. return 1;
  1443. }
  1444. else
  1445. {
  1446. $this->db->rollback();
  1447. $this->error=$this->db->lasterror();
  1448. return -1;
  1449. }
  1450. }
  1451. /**
  1452. * Add user into a group
  1453. *
  1454. * @param int $group Id of group
  1455. * @param int $entity Entity
  1456. * @param int $notrigger Disable triggers
  1457. * @return int <0 if KO, >0 if OK
  1458. */
  1459. function SetInGroup($group, $entity, $notrigger=0)
  1460. {
  1461. global $conf, $langs, $user;
  1462. $error=0;
  1463. $this->db->begin();
  1464. $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user";
  1465. $sql.= " WHERE fk_user = ".$this->id;
  1466. $sql.= " AND fk_usergroup = ".$group;
  1467. $sql.= " AND entity = ".$entity;
  1468. $result = $this->db->query($sql);
  1469. $sql = "INSERT INTO ".MAIN_DB_PREFIX."usergroup_user (entity, fk_user, fk_usergroup)";
  1470. $sql.= " VALUES (".$entity.",".$this->id.",".$group.")";
  1471. $result = $this->db->query($sql);
  1472. if ($result)
  1473. {
  1474. if (! $error && ! $notrigger)
  1475. {
  1476. $this->newgroupid=$group;
  1477. // Call trigger
  1478. $result=$this->call_trigger('USER_SETINGROUP',$user);
  1479. if ($result < 0) { $error++; }
  1480. // End call triggers
  1481. }
  1482. if (! $error)
  1483. {
  1484. $this->db->commit();
  1485. return 1;
  1486. }
  1487. else
  1488. {
  1489. dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
  1490. $this->db->rollback();
  1491. return -2;
  1492. }
  1493. }
  1494. else
  1495. {
  1496. $this->error=$this->db->lasterror();
  1497. $this->db->rollback();
  1498. return -1;
  1499. }
  1500. }
  1501. /**
  1502. * Remove a user from a group
  1503. *
  1504. * @param int $group Id of group
  1505. * @param int $entity Entity
  1506. * @param int $notrigger Disable triggers
  1507. * @return int <0 if KO, >0 if OK
  1508. */
  1509. function RemoveFromGroup($group, $entity, $notrigger=0)
  1510. {
  1511. global $conf,$langs,$user;
  1512. $error=0;
  1513. $this->db->begin();
  1514. $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user";
  1515. $sql.= " WHERE fk_user = ".$this->id;
  1516. $sql.= " AND fk_usergroup = ".$group;
  1517. $sql.= " AND entity = ".$entity;
  1518. $result = $this->db->query($sql);
  1519. if ($result)
  1520. {
  1521. if (! $error && ! $notrigger)
  1522. {
  1523. $this->oldgroupid=$group;
  1524. // Call trigger
  1525. $result=$this->call_trigger('USER_REMOVEFROMGROUP',$user);
  1526. if ($result < 0) { $error++; }
  1527. // End call triggers
  1528. }
  1529. if (! $error)
  1530. {
  1531. $this->db->commit();
  1532. return 1;
  1533. }
  1534. else
  1535. {
  1536. $this->error=$interface->error;
  1537. dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
  1538. $this->db->rollback();
  1539. return -2;
  1540. }
  1541. }
  1542. else
  1543. {
  1544. $this->error=$this->db->lasterror();
  1545. $this->db->rollback();
  1546. return -1;
  1547. }
  1548. }
  1549. /**
  1550. * Return a link to the user card (with optionaly the picto)
  1551. * Use this->id,this->lastname, this->firstname
  1552. *
  1553. * @param int $withpicto Include picto in link (0=No picto, 1=Inclut le picto dans le lien, 2=Picto seul)
  1554. * @param string $option On what the link point to
  1555. * @return string String with URL
  1556. */
  1557. function getNomUrl($withpicto=0,$option='')
  1558. {
  1559. global $langs;
  1560. $result='';
  1561. $lien = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
  1562. $lienfin='</a>';
  1563. if ($withpicto)
  1564. {
  1565. $result.=($lien.img_object($langs->trans("ShowUser"),'user').$lienfin);
  1566. if ($withpicto != 2) $result.=' ';
  1567. }
  1568. $result.=$lien.$this->getFullName($langs,'',-1,24).$lienfin;
  1569. return $result;
  1570. }
  1571. /**
  1572. * Renvoie login clicable (avec eventuellement le picto)
  1573. *
  1574. * @param int $withpicto Inclut le picto dans le lien
  1575. * @param string $option Sur quoi pointe le lien
  1576. * @return string Chaine avec URL
  1577. */
  1578. function getLoginUrl($withpicto=0,$option='')
  1579. {
  1580. global $langs;
  1581. $result='';
  1582. $lien = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
  1583. $lienfin='</a>';
  1584. if ($option == 'xxx')
  1585. {
  1586. $lien = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
  1587. $lienfin='</a>';
  1588. }
  1589. if ($withpicto) $result.=($lien.img_object($langs->trans("ShowUser"),'user').$lienfin.' ');
  1590. $result.=$lien.$this->login.$lienfin;
  1591. return $result;
  1592. }
  1593. /**
  1594. * Retourne le libelle du statut d'un user (actif, inactif)
  1595. *
  1596. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1597. * @return string Label of status
  1598. */
  1599. function getLibStatut($mode=0)
  1600. {
  1601. return $this->LibStatut($this->statut,$mode);
  1602. }
  1603. /**
  1604. * Renvoi le libelle d'un statut donne
  1605. *
  1606. * @param int $statut Id statut
  1607. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1608. * @return string Label of status
  1609. */
  1610. function LibStatut($statut,$mode=0)
  1611. {
  1612. global $langs;
  1613. $langs->load('users');
  1614. if ($mode == 0)
  1615. {
  1616. $prefix='';
  1617. if ($statut == 1) return $langs->trans('Enabled');
  1618. if ($statut == 0) return $langs->trans('Disabled');
  1619. }
  1620. if ($mode == 1)
  1621. {
  1622. if ($statut == 1) return $langs->trans('Enabled');
  1623. if ($statut == 0) return $langs->trans('Disabled');
  1624. }
  1625. if ($mode == 2)
  1626. {
  1627. if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
  1628. if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
  1629. }
  1630. if ($mode == 3)
  1631. {
  1632. if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4');
  1633. if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5');
  1634. }
  1635. if ($mode == 4)
  1636. {
  1637. if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
  1638. if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
  1639. }
  1640. if ($mode == 5)
  1641. {
  1642. if ($statut == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
  1643. if ($statut == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
  1644. }
  1645. }
  1646. /**
  1647. * Retourne chaine DN complete dans l'annuaire LDAP pour l'objet
  1648. *
  1649. * @param array $info Info array loaded by _load_ldap_info
  1650. * @param int $mode 0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb)
  1651. * 1=
  1652. * 2=Return key only (uid=qqq)
  1653. * @return string DN
  1654. */
  1655. function _load_ldap_dn($info,$mode=0)
  1656. {
  1657. global $conf;
  1658. $dn='';
  1659. if ($mode==0) $dn=$conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS].",".$conf->global->LDAP_USER_DN;
  1660. if ($mode==1) $dn=$conf->global->LDAP_USER_DN;
  1661. if ($mode==2) $dn=$conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS];
  1662. return $dn;
  1663. }
  1664. /**
  1665. * Initialize the info array (array of LDAP values) that will be used to call LDAP functions
  1666. *
  1667. * @return array Tableau info des attributs
  1668. */
  1669. function _load_ldap_info()
  1670. {
  1671. global $conf,$langs;
  1672. $info=array();
  1673. // Object classes
  1674. $info["objectclass"]=explode(',',$conf->global->LDAP_USER_OBJECT_CLASS);
  1675. $this->fullname=$this->getFullName($langs);
  1676. // Champs
  1677. if ($this->fullname && ! empty($conf->global->LDAP_FIELD_FULLNAME)) $info[$conf->global->LDAP_FIELD_FULLNAME] = $this->fullname;
  1678. if ($this->lastname && ! empty($conf->global->LDAP_FIELD_NAME)) $info[$conf->global->LDAP_FIELD_NAME] = $this->lastname;
  1679. if ($this->firstname && ! empty($conf->global->LDAP_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_FIELD_FIRSTNAME] = $this->firstname;
  1680. if ($this->login && ! empty($conf->global->LDAP_FIELD_LOGIN)) $info[$conf->global->LDAP_FIELD_LOGIN] = $this->login;
  1681. if ($this->login && ! empty($conf->global->LDAP_FIELD_LOGIN_SAMBA)) $info[$conf->global->LDAP_FIELD_LOGIN_SAMBA] = $this->login;
  1682. if ($this->pass && ! empty($conf->global->LDAP_FIELD_PASSWORD)) $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte
  1683. if ($this->ldap_sid && ! empty($conf->global->LDAP_FIELD_SID)) $info[$conf->global->LDAP_FIELD_SID] = $this->ldap_sid;
  1684. if ($this->societe_id > 0)
  1685. {
  1686. $soc = new Societe($this->db);
  1687. $soc->fetch($this->societe_id);
  1688. $info["o"] = $soc->lastname;
  1689. if ($soc->client == 1) $info["businessCategory"] = "Customers";
  1690. if ($soc->client == 2) $info["businessCategory"] = "Prospects";
  1691. if ($soc->fournisseur == 1) $info["businessCategory"] = "Suppliers";
  1692. }
  1693. if ($this->address && ! empty($conf->global->LDAP_FIELD_ADDRESS)) $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address;
  1694. if ($this->zip && ! empty($conf->global->LDAP_FIELD_ZIP)) $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip;
  1695. if ($this->town && ! empty($conf->global->LDAP_FIELD_TOWN)) $info[$conf->global->LDAP_FIELD_TOWN] = $this->town;
  1696. if ($this->office_phone && ! empty($conf->global->LDAP_FIELD_PHONE)) $info[$conf->global->LDAP_FIELD_PHONE] = $this->office_phone;
  1697. if ($this->user_mobile && ! empty($conf->global->LDAP_FIELD_MOBILE)) $info[$conf->global->LDAP_FIELD_MOBILE] = $this->user_mobile;
  1698. if ($this->office_fax && ! empty($conf->global->LDAP_FIELD_FAX)) $info[$conf->global->LDAP_FIELD_FAX] = $this->office_fax;
  1699. if ($this->note && ! empty($conf->global->LDAP_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_FIELD_DESCRIPTION] = $this->note;
  1700. if ($this->email && ! empty($conf->global->LDAP_FIELD_MAIL)) $info[$conf->global->LDAP_FIELD_MAIL] = $this->email;
  1701. if ($this->skype && ! empty($conf->global->LDAP_FIELD_SKYPE)) $info[$conf->global->LDAP_FIELD_SKYPE] = $this->skype;
  1702. if ($conf->global->LDAP_SERVER_TYPE == 'egroupware')
  1703. {
  1704. $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
  1705. $info['uidnumber'] = $this->id;
  1706. $info['phpgwTz'] = 0;
  1707. $info['phpgwMailType'] = 'INTERNET';
  1708. $info['phpgwMailHomeType'] = 'INTERNET';
  1709. $info["phpgwContactTypeId"] = 'n';
  1710. $info["phpgwContactCatId"] = 0;
  1711. $info["phpgwContactAccess"] = "public";
  1712. if (dol_strlen($this->egroupware_id) == 0)
  1713. {
  1714. $this->egroupware_id = 1;
  1715. }
  1716. $info["phpgwContactOwner"] = $this->egroupware_id;
  1717. if ($this->email) $info["rfc822Mailbox"] = $this->email;
  1718. if ($this->phone_mobile) $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
  1719. }
  1720. return $info;
  1721. }
  1722. /**
  1723. * Initialise an instance with random values.
  1724. * Used to build previews or test instances.
  1725. * id must be 0 if object instance is a specimen.
  1726. *
  1727. * @return void
  1728. */
  1729. function initAsSpecimen()
  1730. {
  1731. global $user,$langs;
  1732. $now=dol_now();
  1733. // Initialise parametres
  1734. $this->id=0;
  1735. $this->ref = 'SPECIMEN';
  1736. $this->specimen=1;
  1737. $this->lastname='DOLIBARR';
  1738. $this->firstname='SPECIMEN';
  1739. $this->note='This is a note';
  1740. $this->email='email@specimen.com';
  1741. $this->skype='tom.hanson';
  1742. $this->office_phone='0999999999';
  1743. $this->office_fax='0999999998';
  1744. $this->user_mobile='0999999997';
  1745. $this->admin=0;
  1746. $this->login='dolibspec';
  1747. $this->pass='dolibspec';
  1748. //$this->pass_indatabase='dolibspec'; Set after a fetch
  1749. //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
  1750. $this->datec=$now;
  1751. $this->datem=$now;
  1752. $this->datelastlogin=$now;
  1753. $this->datepreviouslogin=$now;
  1754. $this->statut=1;
  1755. //$this->societe_id = 1; For external users
  1756. //$this->contact_id = 1; For external users
  1757. $this->entity = 1;
  1758. }
  1759. /**
  1760. * Load info of user object
  1761. *
  1762. * @param int $id Id of user to load
  1763. * @return void
  1764. */
  1765. function info($id)
  1766. {
  1767. $sql = "SELECT u.rowid, u.login as ref, u.datec,";
  1768. $sql.= " u.tms as date_modification, u.entity";
  1769. $sql.= " FROM ".MAIN_DB_PREFIX."user as u";
  1770. $sql.= " WHERE u.rowid = ".$id;
  1771. $result=$this->db->query($sql);
  1772. if ($result)
  1773. {
  1774. if ($this->db->num_rows($result))
  1775. {
  1776. $obj = $this->db->fetch_object($result);
  1777. $this->id = $obj->rowid;
  1778. $this->ref = (! $obj->ref) ? $obj->rowid : $obj->ref;
  1779. $this->date_creation = $this->db->jdate($obj->datec);
  1780. $this->date_modification = $this->db->jdate($obj->date_modification);
  1781. $this->entity = $obj->entity;
  1782. }
  1783. $this->db->free($result);
  1784. }
  1785. else
  1786. {
  1787. dol_print_error($this->db);
  1788. }
  1789. }
  1790. /**
  1791. * Return number of mass Emailing received by this contacts with its email
  1792. *
  1793. * @return int Number of EMailings
  1794. */
  1795. function getNbOfEMailings()
  1796. {
  1797. $sql = "SELECT count(mc.email) as nb";
  1798. $sql.= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
  1799. $sql.= " WHERE mc.email = '".$this->db->escape($this->email)."'";
  1800. $sql.= " AND mc.statut=1"; // -1 erreur, 0 non envoye, 1 envoye avec succes
  1801. $resql=$this->db->query($sql);
  1802. if ($resql)
  1803. {
  1804. $obj = $this->db->fetch_object($resql);
  1805. $nb=$obj->nb;
  1806. $this->db->free($resql);
  1807. return $nb;
  1808. }
  1809. else
  1810. {
  1811. $this->error=$this->db->error();
  1812. return -1;
  1813. }
  1814. }
  1815. /**
  1816. * Return number of existing users
  1817. *
  1818. * @param string $limitTo Limit to 'active' or 'superadmin' users
  1819. * @param bool $all Return for all entities
  1820. * @return int Number of users
  1821. */
  1822. function getNbOfUsers($limitTo='active', $all=false)
  1823. {
  1824. global $conf;
  1825. $sql = "SELECT count(rowid) as nb";
  1826. $sql.= " FROM ".MAIN_DB_PREFIX."user";
  1827. if ($limitTo == 'superadmin')
  1828. {
  1829. $sql.= " WHERE entity = 0";
  1830. }
  1831. else
  1832. {
  1833. if ($all) $sql.= " WHERE entity > 0"; // all users except superadmins
  1834. else $sql.= " WHERE entity = ".$conf->entity;
  1835. if ($limitTo == 'active') $sql.= " AND statut = 1";
  1836. }
  1837. $resql=$this->db->query($sql);
  1838. if ($resql)
  1839. {
  1840. $obj = $this->db->fetch_object($resql);
  1841. $nb=$obj->nb;
  1842. $this->db->free($resql);
  1843. return $nb;
  1844. }
  1845. else
  1846. {
  1847. $this->error=$this->db->error();
  1848. return -1;
  1849. }
  1850. }
  1851. /**
  1852. * Update user using data from the LDAP
  1853. *
  1854. * @param ldapuser $ldapuser Ladp User
  1855. *
  1856. * @return int <0 if KO, >0 if OK
  1857. */
  1858. function update_ldap2dolibarr(&$ldapuser)
  1859. {
  1860. // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
  1861. global $user, $conf;
  1862. $this->firstname=$ldapuser->{$conf->global->LDAP_FIELD_FIRSTNAME};
  1863. $this->lastname=$ldapuser->{$conf->global->LDAP_FIELD_NAME};
  1864. $this->login=$ldapuser->{$conf->global->LDAP_FIELD_LOGIN};
  1865. $this->pass=$ldapuser->{$conf->global->LDAP_FIELD_PASSWORD};
  1866. $this->pass_indatabase_crypted=$ldapuser->{$conf->global->LDAP_FIELD_PASSWORD_CRYPTED};
  1867. $this->office_phone=$ldapuser->{$conf->global->LDAP_FIELD_PHONE};
  1868. $this->user_mobile=$ldapuser->{$conf->global->LDAP_FIELD_MOBILE};
  1869. $this->office_fax=$ldapuser->{$conf->global->LDAP_FIELD_FAX};
  1870. $this->email=$ldapuser->{$conf->global->LDAP_FIELD_MAIL};
  1871. $this->skype=$ldapuser->{$conf->global->LDAP_FIELD_SKYPE};
  1872. $this->ldap_sid=$ldapuser->{$conf->global->LDAP_FIELD_SID};
  1873. $this->job=$ldapuser->{$conf->global->LDAP_FIELD_TITLE};
  1874. $this->note=$ldapuser->{$conf->global->LDAP_FIELD_DESCRIPTION};
  1875. $result = $this->update($user);
  1876. dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
  1877. return $result;
  1878. }
  1879. /**
  1880. * Return and array with all instanciated children users of current user
  1881. *
  1882. * @return void
  1883. */
  1884. function get_children()
  1885. {
  1886. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."user";
  1887. $sql.= " WHERE fk_user = ".$this->id;
  1888. dol_syslog(get_class($this)."::get_children result=".$result, LOG_DEBUG);
  1889. $res = $this->db->query($sql);
  1890. if ($res)
  1891. {
  1892. $users = array ();
  1893. while ($rec = $this->db->fetch_array($res))
  1894. {
  1895. $user = new User($this->db);
  1896. $user->fetch($rec['rowid']);
  1897. $users[] = $user;
  1898. }
  1899. return $users;
  1900. }
  1901. else
  1902. {
  1903. dol_print_error($this->db);
  1904. return -1;
  1905. }
  1906. }
  1907. /**
  1908. * Load this->parentof that is array(id_son=>id_parent, ...)
  1909. *
  1910. * @return int <0 if KO, >0 if OK
  1911. */
  1912. private function load_parentof()
  1913. {
  1914. global $conf;
  1915. $this->parentof=array();
  1916. // Load array[child]=parent
  1917. $sql = "SELECT fk_user as id_parent, rowid as id_son";
  1918. $sql.= " FROM ".MAIN_DB_PREFIX."user";
  1919. $sql.= " WHERE fk_user <> 0";
  1920. $sql.= " AND entity IN (".getEntity('user',1).")";
  1921. dol_syslog(get_class($this)."::load_parentof", LOG_DEBUG);
  1922. $resql = $this->db->query($sql);
  1923. if ($resql)
  1924. {
  1925. while ($obj= $this->db->fetch_object($resql))
  1926. {
  1927. $this->parentof[$obj->id_son]=$obj->id_parent;
  1928. }
  1929. return 1;
  1930. }
  1931. else
  1932. {
  1933. dol_print_error($this->db);
  1934. return -1;
  1935. }
  1936. }
  1937. /**
  1938. * Reconstruit l'arborescence hierarchique des users sous la forme d'un tableau
  1939. * Set and return this->users that is an array sorted according to tree with arrays of:
  1940. * id = id user
  1941. * lastname
  1942. * firstname
  1943. * fullname = nom avec chemin complet du user
  1944. * fullpath = chemin complet compose des id: "_grandparentid_parentid_id"
  1945. *
  1946. * @param int $deleteafterid Removed all users including the leaf $deleteafterid (and all its child) in user tree.
  1947. * @return array Array of users $this->users. Note: $this->parentof is also set.
  1948. */
  1949. function get_full_tree($deleteafterid=0)
  1950. {
  1951. global $conf,$user;
  1952. $this->users = array();
  1953. // Init this->parentof that is array(id_son=>id_parent, ...)
  1954. $this->load_parentof();
  1955. // Init $this->users array
  1956. $sql = "SELECT DISTINCT u.rowid, u.firstname, u.lastname, u.fk_user, u.login, u.statut, u.entity"; // Distinct reduce pb with old tables with duplicates
  1957. $sql.= " FROM ".MAIN_DB_PREFIX."user as u";
  1958. if(! empty($conf->multicompany->enabled) && $conf->entity == 1 && (! empty($conf->multicompany->transverse_mode) || (! empty($user->admin) && empty($user->entity))))
  1959. {
  1960. $sql.= " WHERE u.entity IS NOT NULL";
  1961. }
  1962. else
  1963. {
  1964. $sql.= " WHERE u.entity IN (".getEntity('user',1).")";
  1965. }
  1966. dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
  1967. $resql = $this->db->query($sql);
  1968. if ($resql)
  1969. {
  1970. $i=0;
  1971. while ($obj = $this->db->fetch_object($resql))
  1972. {
  1973. $this->users[$obj->rowid]['rowid'] = $obj->rowid;
  1974. $this->users[$obj->rowid]['id'] = $obj->rowid;
  1975. $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
  1976. $this->users[$obj->rowid]['firstname'] = $obj->firstname;
  1977. $this->users[$obj->rowid]['lastname'] = $obj->lastname;
  1978. $this->users[$obj->rowid]['login'] = $obj->login;
  1979. $this->users[$obj->rowid]['statut'] = $obj->statut;
  1980. $this->users[$obj->rowid]['entity'] = $obj->entity;
  1981. $i++;
  1982. }
  1983. }
  1984. else
  1985. {
  1986. dol_print_error($this->db);
  1987. return -1;
  1988. }
  1989. // We add the fullpath property to each elements of first level (no parent exists)
  1990. dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
  1991. foreach($this->users as $key => $val)
  1992. {
  1993. $this->build_path_from_id_user($key,0); // Process a branch from the root user key (this user has no parent)
  1994. }
  1995. // Exclude leaf including $deleteafterid from tree
  1996. if ($deleteafterid)
  1997. {
  1998. //print "Look to discard user ".$deleteafterid."\n";
  1999. $keyfilter1='^'.$deleteafterid.'$';
  2000. $keyfilter2='_'.$deleteafterid.'$';
  2001. $keyfilter3='^'.$deleteafterid.'_';
  2002. $keyfilter4='_'.$deleteafterid.'_';
  2003. foreach($this->users as $key => $val)
  2004. {
  2005. if (preg_match('/'.$keyfilter1.'/',$val['fullpath']) || preg_match('/'.$keyfilter2.'/',$val['fullpath'])
  2006. || preg_match('/'.$keyfilter3.'/',$val['fullpath']) || preg_match('/'.$keyfilter4.'/',$val['fullpath']))
  2007. {
  2008. unset($this->users[$key]);
  2009. }
  2010. }
  2011. }
  2012. dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
  2013. $this->users=dol_sort_array($this->users, 'fullname', 'asc', true, false);
  2014. //var_dump($this->users);
  2015. return $this->users;
  2016. }
  2017. /**
  2018. * Return list of all childs users in herarchy.
  2019. *
  2020. * @return array Array of user id lower than user. This overwrite this->users.
  2021. */
  2022. function getAllChildIds()
  2023. {
  2024. // Init this->users
  2025. $this->get_full_tree();
  2026. $idtoscan=$this->id;
  2027. $childids=array();
  2028. dol_syslog("Build childid for id = ".$idtoscan);
  2029. foreach($this->users as $id => $val)
  2030. {
  2031. //var_dump($val['fullpath']);
  2032. if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) $childids[$val['id']]=$val['id'];
  2033. }
  2034. return $childids;
  2035. }
  2036. /**
  2037. * For user id_user and its childs available in this->users, define property fullpath and fullname
  2038. *
  2039. * @param int $id_user id_user entry to update
  2040. * @param int $protection Deep counter to avoid infinite loop
  2041. * @return void
  2042. */
  2043. function build_path_from_id_user($id_user,$protection=1000)
  2044. {
  2045. dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
  2046. if (! empty($this->users[$id_user]['fullpath']))
  2047. {
  2048. // Already defined
  2049. dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
  2050. return;
  2051. }
  2052. // Define fullpath and fullname
  2053. $this->users[$id_user]['fullpath'] = '_'.$id_user;
  2054. $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
  2055. $i=0; $cursor_user=$id_user;
  2056. while ((empty($protection) || $i < $protection) && ! empty($this->parentof[$cursor_user]))
  2057. {
  2058. $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
  2059. $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
  2060. $i++; $cursor_user=$this->parentof[$cursor_user];
  2061. }
  2062. // We count number of _ to have level
  2063. $this->users[$id_user]['level']=dol_strlen(preg_replace('/[^_]/i','',$this->users[$id_user]['fullpath']));
  2064. return;
  2065. }
  2066. }