dolibarr  13.0.2
user.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (c) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
4  * Copyright (c) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
5  * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6  * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
7  * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8  * Copyright (C) 2005 Lionel Cousteix <etm_ltd@tiscali.co.uk>
9  * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
10  * Copyright (C) 2013-2019 Philippe Grand <philippe.grand@atoo-net.com>
11  * Copyright (C) 2013-2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
12  * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
13  * Copyright (C) 2018 charlene Benke <charlie@patas-monkey.com>
14  * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
15  * Copyright (C) 2019-2020 Frédéric France <frederic.france@netlogic.fr>
16  * Copyright (C) 2019 Abbes Bahfir <dolipar@dolipar.org>
17  *
18  * This program is free software; you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation; either version 3 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program. If not, see <https://www.gnu.org/licenses/>.
30  */
31 
38 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
39 require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
40 
44 class User extends CommonObject
45 {
49  public $element = 'user';
50 
54  public $table_element = 'user';
55 
59  public $fk_element = 'fk_user';
60 
65  public $ismultientitymanaged = 1;
66 
70  public $picto = 'user';
71 
72  public $id = 0;
73  public $statut;
74  public $ldap_sid;
75  public $search_sid;
76  public $employee;
77  public $civility_code;
78 
82  public $gender;
83  public $birth;
84 
88  public $email;
89 
93  public $personal_email;
94 
98  public $socialnetworks;
99 
104  public $skype;
105 
110  public $twitter;
111 
116  public $facebook;
117 
122  public $linkedin;
123 
127  public $job;
128 
132  public $signature;
133 
137  public $address;
138 
142  public $zip;
143 
147  public $town;
148  public $state_id; // The state/department
149  public $state_code;
150  public $state;
151 
155  public $office_phone;
156 
160  public $office_fax;
161 
165  public $user_mobile;
166 
170  public $personal_mobile;
171 
175  public $admin;
176 
180  public $login;
181 
185  public $api_key;
186 
190  public $entity;
191 
195  public $pass;
196 
200  public $pass_indatabase;
201 
205  public $pass_indatabase_crypted;
206 
210  public $pass_temp;
211 
217  public $datec;
218 
224  public $datem;
225 
229  public $socid;
230 
234  public $contact_id;
235 
239  public $fk_member;
240 
244  public $fk_user;
245 
249  public $fk_user_expense_validator;
250 
254  public $fk_user_holiday_validator;
255 
260 
264  public $clicktodial_login;
265 
269  public $clicktodial_password;
270 
274  public $clicktodial_poste;
275 
276  public $datelastlogin;
277  public $datepreviouslogin;
278  public $datestartvalidity;
279  public $dateendvalidity;
280 
284  public $photo;
285  public $lang;
286 
290  public $rights;
291 
295  public $all_permissions_are_loaded;
296 
300  public $nb_rights;
301 
305  private $_tab_loaded = array();
306 
310  public $conf;
311  public $default_values; // To store default values for user
312  public $lastsearch_values_tmp; // To store current search criterias for user
313  public $lastsearch_values; // To store last saved search criterias for user
314 
315  public $users = array(); // To store all tree of users hierarchy
316  public $parentof; // To store an array of all parents for all ids.
317  private $cache_childids; // Cache array of already loaded childs
318 
319  public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
320 
321  public $thm; // Average cost of employee - Used for valuation of time spent
322  public $tjm; // Average cost of employee
323 
324  public $salary; // Monthly salary - Denormalized value from llx_user_employment
325  public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment
326  public $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment
327 
331  public $color;
332 
333  public $dateemployment; // Define date of employment by company
334  public $dateemploymentend; // Define date of employment end by company
335 
336  public $default_c_exp_tax_cat;
337  public $default_range;
338 
342  public $fk_warehouse;
343 
344  public $fields = array(
345  'rowid'=>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
346  'lastname'=>array('type'=>'varchar(50)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>20, 'searchall'=>1),
347  'firstname'=>array('type'=>'varchar(50)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1),
348  );
349 
350 
351  const STATUS_DISABLED = 0;
352  const STATUS_ENABLED = 1;
353 
354 
355 
361  public function __construct($db)
362  {
363  $this->db = $db;
364 
365  // User preference
366  $this->liste_limit = 0;
367  $this->clicktodial_loaded = 0;
368 
369  // For cache usage
370  $this->all_permissions_are_loaded = 0;
371  $this->nb_rights = 0;
372 
373  // Force some default values
374  $this->admin = 0;
375  $this->employee = 1;
376 
377  $this->conf = new stdClass();
378  $this->rights = new stdClass();
379  $this->rights->user = new stdClass();
380  $this->rights->user->user = new stdClass();
381  $this->rights->user->self = new stdClass();
382  }
383 
396  public function fetch($id = '', $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1, $email = '')
397  {
398  global $conf, $user;
399 
400  // Clean parameters
401  $login = trim($login);
402 
403  // Get user
404  $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,";
405  $sql .= " u.socialnetworks,";
406  $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile, u.personal_mobile,";
407  $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
408  $sql .= " u.admin, u.login, u.note as note_private, u.note_public,";
409  $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.api_key,";
410  $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,";
411  $sql .= " u.statut, u.lang, u.entity,";
412  $sql .= " u.datec as datec,";
413  $sql .= " u.tms as datem,";
414  $sql .= " u.datelastlogin as datel,";
415  $sql .= " u.datepreviouslogin as datep,";
416  $sql .= " u.datelastpassvalidation,";
417  $sql .= " u.datestartvalidity,";
418  $sql .= " u.dateendvalidity,";
419  $sql .= " u.photo as photo,";
420  $sql .= " u.openid as openid,";
421  $sql .= " u.accountancy_code,";
422  $sql .= " u.thm,";
423  $sql .= " u.tjm,";
424  $sql .= " u.salary,";
425  $sql .= " u.salaryextra,";
426  $sql .= " u.weeklyhours,";
427  $sql .= " u.color,";
428  $sql .= " u.dateemployment, u.dateemploymentend,";
429  $sql .= " u.fk_warehouse,";
430  $sql .= " u.ref_ext,";
431  $sql .= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode
432  $sql .= " c.code as country_code, c.label as country,";
433  $sql .= " d.code_departement as state_code, d.nom as state";
434  $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
435  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON u.fk_country = c.rowid";
436  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as d ON u.fk_state = d.rowid";
437 
438  if ($entity < 0) {
439  if ((empty($conf->multicompany->enabled) || empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) && (!empty($user->entity))) {
440  $sql .= " WHERE u.entity IN (0,".$conf->entity.")";
441  } else {
442  $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
443  }
444  } else {
445  // The fetch was forced on an entity
446  if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
447  $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
448  } else {
449  $sql .= " WHERE u.entity IN (0, ".(($entity != '' && $entity >= 0) ? $entity : $conf->entity).")"; // search in entity provided in parameter
450  }
451  }
452 
453  if ($sid) { // permet une recherche du user par son SID ActiveDirectory ou Samba
454  $sql .= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."') LIMIT 1";
455  } elseif ($login) {
456  $sql .= " AND u.login = '".$this->db->escape($login)."'";
457  } elseif ($email) {
458  $sql .= " AND u.email = '".$this->db->escape($email)."'";
459  } else {
460  $sql .= " AND u.rowid = ".$id;
461  }
462  $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
463 
464  $result = $this->db->query($sql);
465  if ($result) {
466  $obj = $this->db->fetch_object($result);
467  if ($obj) {
468  $this->id = $obj->rowid;
469  $this->ref = $obj->rowid;
470 
471  $this->ref_ext = $obj->ref_ext;
472 
473  $this->ldap_sid = $obj->ldap_sid;
474  $this->civility_code = $obj->civility_code;
475  $this->lastname = $obj->lastname;
476  $this->firstname = $obj->firstname;
477 
478  $this->employee = $obj->employee;
479 
480  $this->login = $obj->login;
481  $this->gender = $obj->gender;
482  $this->birth = $this->db->jdate($obj->birth);
483  $this->pass_indatabase = $obj->pass;
484  $this->pass_indatabase_crypted = $obj->pass_crypted;
485  $this->pass = $obj->pass;
486  $this->pass_temp = $obj->pass_temp;
487  $this->api_key = $obj->api_key;
488 
489  $this->address = $obj->address;
490  $this->zip = $obj->zip;
491  $this->town = $obj->town;
492 
493  $this->country_id = $obj->country_id;
494  $this->country_code = $obj->country_id ? $obj->country_code : '';
495  //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
496 
497  $this->state_id = $obj->state_id;
498  $this->state_code = $obj->state_code;
499  $this->state = ($obj->state != '-' ? $obj->state : '');
500 
501  $this->office_phone = $obj->office_phone;
502  $this->office_fax = $obj->office_fax;
503  $this->user_mobile = $obj->user_mobile;
504  $this->personal_mobile = $obj->personal_mobile;
505  $this->email = $obj->email;
506  $this->personal_email = $obj->personal_email;
507  $this->socialnetworks = (array) json_decode($obj->socialnetworks, true);
508  $this->job = $obj->job;
509  $this->signature = $obj->signature;
510  $this->admin = $obj->admin;
511  $this->note_public = $obj->note_public;
512  $this->note_private = $obj->note_private;
513  $this->note = $obj->note_private;
514  $this->statut = $obj->statut;
515  $this->photo = $obj->photo;
516  $this->openid = $obj->openid;
517  $this->lang = $obj->lang;
518  $this->entity = $obj->entity;
519  $this->accountancy_code = $obj->accountancy_code;
520  $this->thm = $obj->thm;
521  $this->tjm = $obj->tjm;
522  $this->salary = $obj->salary;
523  $this->salaryextra = $obj->salaryextra;
524  $this->weeklyhours = $obj->weeklyhours;
525  $this->color = $obj->color;
526  $this->dateemployment = $this->db->jdate($obj->dateemployment);
527  $this->dateemploymentend = $this->db->jdate($obj->dateemploymentend);
528 
529  $this->datec = $this->db->jdate($obj->datec);
530  $this->datem = $this->db->jdate($obj->datem);
531  $this->datelastlogin = $this->db->jdate($obj->datel);
532  $this->datepreviouslogin = $this->db->jdate($obj->datep);
533  $this->datestartvalidity = $this->db->jdate($obj->datestartvalidity);
534  $this->dateendvalidity = $this->db->jdate($obj->dateendvalidity);
535 
536  $this->socid = $obj->fk_soc;
537  $this->contact_id = $obj->fk_socpeople;
538  $this->fk_member = $obj->fk_member;
539  $this->fk_user = $obj->fk_user;
540  $this->fk_user_expense_validator = $obj->fk_user_expense_validator;
541  $this->fk_user_holiday_validator = $obj->fk_user_holiday_validator;
542 
543  $this->default_range = $obj->default_range;
544  $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
545  $this->fk_warehouse = $obj->fk_warehouse;
546 
547  // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
548  // in such case, this admin user must be admin for ALL entities.
549  if (empty($conf->multicompany->enabled) && $this->admin && $this->entity == 1) {
550  $this->entity = 0;
551  }
552 
553  // Retrieve all extrafield
554  // fetch optionals attributes and labels
555  $this->fetch_optionals();
556 
557  $this->db->free($result);
558  } else {
559  $this->error = "USERNOTFOUND";
560  dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
561 
562  $this->db->free($result);
563  return 0;
564  }
565  } else {
566  $this->error = $this->db->lasterror();
567  return -1;
568  }
569 
570  // To get back the global configuration unique to the user
571  if ($loadpersonalconf) {
572  // Load user->conf for user
573  $sql = "SELECT param, value FROM ".MAIN_DB_PREFIX."user_param";
574  $sql .= " WHERE fk_user = ".$this->id;
575  $sql .= " AND entity = ".$conf->entity;
576  //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
577  $resql = $this->db->query($sql);
578  if ($resql) {
579  $num = $this->db->num_rows($resql);
580  $i = 0;
581  while ($i < $num) {
582  $obj = $this->db->fetch_object($resql);
583  $p = (!empty($obj->param) ? $obj->param : '');
584  if (!empty($p)) {
585  $this->conf->$p = $obj->value;
586  }
587  $i++;
588  }
589  $this->db->free($resql);
590  } else {
591  $this->error = $this->db->lasterror();
592  return -2;
593  }
594 
595  $result = $this->loadDefaultValues();
596 
597  if ($result < 0) {
598  $this->error = $this->db->lasterror();
599  return -3;
600  }
601  }
602 
603  return 1;
604  }
605 
611  public function loadDefaultValues()
612  {
613  global $conf;
614 
615  // Load user->default_values for user. TODO Save this in memcached ?
616  $sql = "SELECT rowid, entity, type, page, param, value";
617  $sql .= " FROM ".MAIN_DB_PREFIX."default_values";
618  $sql .= " WHERE entity IN (".($this->entity > 0 ? $this->entity.", " : "").$conf->entity.")"; // Entity of user (if defined) + current entity
619  $sql .= " AND user_id IN (0".($this->id > 0 ? ", ".$this->id : "").")"; // User 0 (all) + me (if defined)
620  $resql = $this->db->query($sql);
621  if ($resql) {
622  while ($obj = $this->db->fetch_object($resql)) {
623  if (!empty($obj->page) && !empty($obj->type) && !empty($obj->param)) {
624  // $obj->page is relative URL with or without params
625  // $obj->type can be 'filters', 'sortorder', 'createform', ...
626  // $obj->param is key or param
627  $pagewithoutquerystring = $obj->page;
628  $pagequeries = '';
629  $reg = array();
630  if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
631  $pagewithoutquerystring = $reg[1];
632  $pagequeries = $reg[2];
633  }
634  $this->default_values[$pagewithoutquerystring][$obj->type][$pagequeries ? $pagequeries : '_noquery_'][$obj->param] = $obj->value;
635  //if ($pagequeries) $this->default_values[$pagewithoutquerystring][$obj->type.'_queries']=$pagequeries;
636  }
637  }
638  // Sort by key, so _noquery_ is last
639  if (!empty($this->default_values)) {
640  foreach ($this->default_values as $a => $b) {
641  foreach ($b as $c => $d) {
642  krsort($this->default_values[$a][$c]);
643  }
644  }
645  }
646  $this->db->free($resql);
647 
648  return 1;
649  } else {
650  dol_print_error($this->db);
651  return -1;
652  }
653  }
654 
666  public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
667  {
668  global $conf, $user, $langs;
669 
670  $entity = (!empty($entity) ? $entity : $conf->entity);
671 
672  dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity");
673  $error = 0;
674  $whereforadd = '';
675 
676  $this->db->begin();
677 
678  if (!empty($rid)) {
679  $module = $perms = $subperms = '';
680 
681  // Si on a demande ajout d'un droit en particulier, on recupere
682  // les caracteristiques (module, perms et subperms) de ce droit.
683  $sql = "SELECT module, perms, subperms";
684  $sql .= " FROM ".MAIN_DB_PREFIX."rights_def";
685  $sql .= " WHERE id = ".((int) $rid);
686  $sql .= " AND entity = ".((int) $entity);
687 
688  $result = $this->db->query($sql);
689  if ($result) {
690  $obj = $this->db->fetch_object($result);
691 
692  if ($obj) {
693  $module = $obj->module;
694  $perms = $obj->perms;
695  $subperms = $obj->subperms;
696  }
697  } else {
698  $error++;
699  dol_print_error($this->db);
700  }
701 
702  // Where pour la liste des droits a ajouter
703  $whereforadd = "id=".((int) $rid);
704  // Ajout des droits induits
705  if (!empty($subperms)) {
706  $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))";
707  } elseif (!empty($perms)) {
708  $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND subperms IS NULL)";
709  }
710  } else {
711  // On a pas demande un droit en particulier mais une liste de droits
712  // sur la base d'un nom de module de de perms
713  // Where pour la liste des droits a ajouter
714  if (!empty($allmodule)) {
715  if ($allmodule == 'allmodules') {
716  $whereforadd = 'allmodules';
717  } else {
718  $whereforadd = "module='".$this->db->escape($allmodule)."'";
719  if (!empty($allperms)) {
720  $whereforadd .= " AND perms='".$this->db->escape($allperms)."'";
721  }
722  }
723  }
724  }
725 
726  // Ajout des droits trouves grace au critere whereforadd
727  if (!empty($whereforadd)) {
728  //print "$module-$perms-$subperms";
729  $sql = "SELECT id";
730  $sql .= " FROM ".MAIN_DB_PREFIX."rights_def";
731  $sql .= " WHERE entity = ".$entity;
732  if (!empty($whereforadd) && $whereforadd != 'allmodules') {
733  $sql .= " AND ".$whereforadd;
734  }
735 
736  $result = $this->db->query($sql);
737  if ($result) {
738  $num = $this->db->num_rows($result);
739  $i = 0;
740  while ($i < $num) {
741  $obj = $this->db->fetch_object($result);
742  $nid = $obj->id;
743 
744  $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = ".$this->id." AND fk_id=".$nid." AND entity = ".$entity;
745  if (!$this->db->query($sql)) {
746  $error++;
747  }
748  $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rights (entity, fk_user, fk_id) VALUES (".$entity.", ".$this->id.", ".$nid.")";
749  if (!$this->db->query($sql)) {
750  $error++;
751  }
752 
753  $i++;
754  }
755  } else {
756  $error++;
757  dol_print_error($this->db);
758  }
759  }
760 
761  if (!$error && !$notrigger) {
762  $langs->load("other");
763  $this->context = array('audit'=>$langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : ''));
764 
765  // Call trigger
766  $result = $this->call_trigger('USER_MODIFY', $user);
767  if ($result < 0) {
768  $error++;
769  }
770  // End call triggers
771  }
772 
773  if ($error) {
774  $this->db->rollback();
775  return -$error;
776  } else {
777  $this->db->commit();
778  return 1;
779  }
780  }
781 
782 
794  public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
795  {
796  global $conf, $user, $langs;
797 
798  $error = 0;
799  $wherefordel = '';
800  $entity = (!empty($entity) ? $entity : $conf->entity);
801 
802  $this->db->begin();
803 
804  if (!empty($rid)) {
805  $module = $perms = $subperms = '';
806 
807  // Si on a demande supression d'un droit en particulier, on recupere
808  // les caracteristiques module, perms et subperms de ce droit.
809  $sql = "SELECT module, perms, subperms";
810  $sql .= " FROM ".MAIN_DB_PREFIX."rights_def";
811  $sql .= " WHERE id = '".$this->db->escape($rid)."'";
812  $sql .= " AND entity = ".$entity;
813 
814  $result = $this->db->query($sql);
815  if ($result) {
816  $obj = $this->db->fetch_object($result);
817 
818  if ($obj) {
819  $module = $obj->module;
820  $perms = $obj->perms;
821  $subperms = $obj->subperms;
822  }
823  } else {
824  $error++;
825  dol_print_error($this->db);
826  }
827 
828  // Where pour la liste des droits a supprimer
829  $wherefordel = "id=".((int) $rid);
830  // Suppression des droits induits
831  if ($subperms == 'lire' || $subperms == 'read') {
832  $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)";
833  }
834  if ($perms == 'lire' || $perms == 'read') {
835  $wherefordel .= " OR (module='".$this->db->escape($module)."')";
836  }
837  } else {
838  // On a demande suppression d'un droit sur la base d'un nom de module ou perms
839  // Where pour la liste des droits a supprimer
840  if (!empty($allmodule)) {
841  if ($allmodule == 'allmodules') {
842  $wherefordel = 'allmodules';
843  } else {
844  $wherefordel = "module='".$this->db->escape($allmodule)."'";
845  if (!empty($allperms)) {
846  $wherefordel .= " AND perms='".$this->db->escape($allperms)."'";
847  }
848  }
849  }
850  }
851 
852  // Suppression des droits selon critere defini dans wherefordel
853  if (!empty($wherefordel)) {
854  //print "$module-$perms-$subperms";
855  $sql = "SELECT id";
856  $sql .= " FROM ".MAIN_DB_PREFIX."rights_def";
857  $sql .= " WHERE entity = ".$entity;
858  if (!empty($wherefordel) && $wherefordel != 'allmodules') {
859  $sql .= " AND ".$wherefordel;
860  }
861 
862  // avoid admin can remove his own important rights
863  if ($this->admin == 1) {
864  $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
865  $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
866  $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
867  $sql .= " AND id NOT IN (358)"; // user export
868  }
869 
870  $result = $this->db->query($sql);
871  if ($result) {
872  $num = $this->db->num_rows($result);
873  $i = 0;
874  while ($i < $num) {
875  $obj = $this->db->fetch_object($result);
876  $nid = $obj->id;
877 
878  $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights";
879  $sql .= " WHERE fk_user = ".$this->id." AND fk_id=".$nid;
880  $sql .= " AND entity = ".$entity;
881  if (!$this->db->query($sql)) {
882  $error++;
883  }
884 
885  $i++;
886  }
887  } else {
888  $error++;
889  dol_print_error($this->db);
890  }
891  }
892 
893  if (!$error && !$notrigger) {
894  $langs->load("other");
895  $this->context = array('audit'=>$langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : ''));
896 
897  // Call trigger
898  $result = $this->call_trigger('USER_MODIFY', $user);
899  if ($result < 0) {
900  $error++;
901  }
902  // End call triggers
903  }
904 
905  if ($error) {
906  $this->db->rollback();
907  return -$error;
908  } else {
909  $this->db->commit();
910  return 1;
911  }
912  }
913 
914 
921  public function clearrights()
922  {
923  dol_syslog(get_class($this)."::clearrights reset user->rights");
924  $this->rights = null;
925  $this->nb_rights = 0;
926  $this->all_permissions_are_loaded = 0;
927  $this->_tab_loaded = array();
928  }
929 
930 
939  public function getrights($moduletag = '', $forcereload = 0)
940  {
941  global $conf;
942 
943  if (empty($forcereload)) {
944  if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
945  // Rights for this module are already loaded, so we leave
946  return;
947  }
948 
949  if (!empty($this->all_permissions_are_loaded)) {
950  // We already loaded all rights for this user, so we leave
951  return;
952  }
953  }
954 
955  // Get permission of users + Get permissions of groups
956 
957  // First user permissions
958  $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
959  $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur";
960  $sql .= ", ".MAIN_DB_PREFIX."rights_def as r";
961  $sql .= " WHERE r.id = ur.fk_id";
962  if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
963  $sql .= " AND r.entity IN (0,".(!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) ? "1," : "").$conf->entity.")";
964  } else {
965  $sql .= " AND ur.entity = ".$conf->entity;
966  }
967  $sql .= " AND ur.fk_user= ".$this->id;
968  $sql .= " AND r.perms IS NOT NULL";
969  if ($moduletag) {
970  $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
971  }
972 
973  $resql = $this->db->query($sql);
974  if ($resql) {
975  $num = $this->db->num_rows($resql);
976  $i = 0;
977 
978  while ($i < $num) {
979  $obj = $this->db->fetch_object($resql);
980 
981  if ($obj) {
982  $module = $obj->module;
983  $perms = $obj->perms;
984  $subperms = $obj->subperms;
985 
986  if (!empty($perms)) {
987  if (!isset($this->rights) || !is_object($this->rights)) {
988  $this->rights = new stdClass(); // For avoid error
989  }
990  if (!empty($module)) {
991  if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
992  $this->rights->$module = new stdClass();
993  }
994  if (!empty($subperms)) {
995  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
996  $this->rights->$module->$perms = new stdClass();
997  }
998  if (empty($this->rights->$module->$perms->$subperms)) {
999  $this->nb_rights++;
1000  }
1001  $this->rights->$module->$perms->$subperms = 1;
1002  } else {
1003  if (empty($this->rights->$module->$perms)) {
1004  $this->nb_rights++;
1005  }
1006  $this->rights->$module->$perms = 1;
1007  }
1008  }
1009  }
1010  }
1011  $i++;
1012  }
1013  $this->db->free($resql);
1014  }
1015 
1016  // Now permissions of groups
1017  $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1018  $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_rights as gr,";
1019  $sql .= " ".MAIN_DB_PREFIX."usergroup_user as gu,";
1020  $sql .= " ".MAIN_DB_PREFIX."rights_def as r";
1021  $sql .= " WHERE r.id = gr.fk_id";
1022  if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
1023  if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1024  $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1025  } else {
1026  $sql .= " AND r.entity = ".$conf->entity;
1027  }
1028  } else {
1029  $sql .= " AND gr.entity = ".$conf->entity;
1030  $sql .= " AND gu.entity = ".$conf->entity;
1031  $sql .= " AND r.entity = ".$conf->entity;
1032  }
1033  $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
1034  $sql .= " AND gu.fk_user = ".$this->id;
1035  $sql .= " AND r.perms IS NOT NULL";
1036  if ($moduletag) {
1037  $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1038  }
1039 
1040  $resql = $this->db->query($sql);
1041  if ($resql) {
1042  $num = $this->db->num_rows($resql);
1043  $i = 0;
1044  while ($i < $num) {
1045  $obj = $this->db->fetch_object($resql);
1046 
1047  if ($obj) {
1048  $module = $obj->module;
1049  $perms = $obj->perms;
1050  $subperms = $obj->subperms;
1051 
1052  if (!empty($perms)) {
1053  if (!isset($this->rights) || !is_object($this->rights)) {
1054  $this->rights = new stdClass(); // For avoid error
1055  }
1056  if (!empty($module)) {
1057  if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1058  $this->rights->$module = new stdClass();
1059  }
1060  if (!empty($subperms)) {
1061  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1062  $this->rights->$module->$perms = new stdClass();
1063  }
1064  if (empty($this->rights->$module->$perms->$subperms)) {
1065  $this->nb_rights++;
1066  }
1067  $this->rights->$module->$perms->$subperms = 1;
1068  } else {
1069  if (empty($this->rights->$module->$perms)) {
1070  $this->nb_rights++;
1071  }
1072  // 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
1073  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1074  $this->rights->$module->$perms = 1;
1075  }
1076  }
1077  }
1078  }
1079  }
1080  $i++;
1081  }
1082  $this->db->free($resql);
1083  }
1084 
1085  // For backward compatibility
1086  if (isset($this->rights->propale) && !isset($this->rights->propal)) {
1087  $this->rights->propal = $this->rights->propale;
1088  }
1089  if (isset($this->rights->propal) && !isset($this->rights->propale)) {
1090  $this->rights->propale = $this->rights->propal;
1091  }
1092 
1093  if (!$moduletag) {
1094  // Si module etait non defini, alors on a tout charge, on peut donc considerer
1095  // que les droits sont en cache (car tous charges) pour cet instance de user
1096  $this->all_permissions_are_loaded = 1;
1097  } else {
1098  // If module defined, we flag it as loaded into cache
1099  $this->_tab_loaded[$moduletag] = 1;
1100  }
1101  }
1102 
1109  public function setstatus($status)
1110  {
1111  global $conf, $langs, $user;
1112 
1113  $error = 0;
1114 
1115  // Check parameters
1116  if ($this->statut == $status) {
1117  return 0;
1118  } else {
1119  $this->statut = $status;
1120  }
1121 
1122  $this->db->begin();
1123 
1124  // Save in database
1125  $sql = "UPDATE ".MAIN_DB_PREFIX."user";
1126  $sql .= " SET statut = ".$this->statut;
1127  $sql .= " WHERE rowid = ".$this->id;
1128  $result = $this->db->query($sql);
1129 
1130  dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1131  if ($result) {
1132  // Call trigger
1133  $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
1134  if ($result < 0) {
1135  $error++;
1136  }
1137  // End call triggers
1138  }
1139 
1140  if ($error) {
1141  $this->db->rollback();
1142  return -$error;
1143  } else {
1144  $this->db->commit();
1145  return 1;
1146  }
1147  }
1148 
1159  public function setCategories($categories)
1160  {
1161  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1162 
1163  $type_categ = Categorie::TYPE_USER;
1164 
1165  // Handle single category
1166  if (!is_array($categories)) {
1167  $categories = array($categories);
1168  }
1169 
1170  // Get current categories
1171  $c = new Categorie($this->db);
1172  $existing = $c->containing($this->id, $type_categ, 'id');
1173 
1174  // Diff
1175  if (is_array($existing)) {
1176  $to_del = array_diff($existing, $categories);
1177  $to_add = array_diff($categories, $existing);
1178  } else {
1179  $to_del = array(); // Nothing to delete
1180  $to_add = $categories;
1181  }
1182 
1183  // Process
1184  foreach ($to_del as $del) {
1185  if ($c->fetch($del) > 0) {
1186  $c->del_type($this, $type_categ);
1187  }
1188  }
1189  foreach ($to_add as $add) {
1190  if ($c->fetch($add) > 0) {
1191  $c->add_type($this, $type_categ);
1192  }
1193  }
1194 
1195  return;
1196  }
1197 
1204  public function delete(User $user)
1205  {
1206  global $conf, $langs;
1207 
1208  $error = 0;
1209 
1210  $this->db->begin();
1211 
1212  $this->fetch($this->id);
1213 
1214  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1215 
1216  // Remove rights
1217  $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = ".$this->id;
1218 
1219  if (!$error && !$this->db->query($sql)) {
1220  $error++;
1221  $this->error = $this->db->lasterror();
1222  }
1223 
1224  // Remove group
1225  $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user WHERE fk_user = ".$this->id;
1226  if (!$error && !$this->db->query($sql)) {
1227  $error++;
1228  $this->error = $this->db->lasterror();
1229  }
1230 
1231  // Remove params
1232  $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param WHERE fk_user = ".$this->id;
1233  if (!$error && !$this->db->query($sql)) {
1234  $error++;
1235  $this->error = $this->db->lasterror();
1236  }
1237 
1238  // If contact, remove link
1239  if ($this->contact_id > 0) {
1240  $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET fk_user_creat = null WHERE rowid = ".$this->contact_id;
1241  if (!$error && !$this->db->query($sql)) {
1242  $error++;
1243  $this->error = $this->db->lasterror();
1244  }
1245  }
1246 
1247  // Remove extrafields
1248  if (!$error) {
1249  $result = $this->deleteExtraFields();
1250  if ($result < 0) {
1251  $error++;
1252  dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1253  }
1254  }
1255 
1256  // Remove user
1257  if (!$error) {
1258  $sql = "DELETE FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->id;
1259  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1260  if (!$this->db->query($sql)) {
1261  $error++;
1262  $this->error = $this->db->lasterror();
1263  }
1264  }
1265 
1266  if (!$error) {
1267  // Call trigger
1268  $result = $this->call_trigger('USER_DELETE', $user);
1269  if ($result < 0) {
1270  $error++;
1271  $this->db->rollback();
1272  return -1;
1273  }
1274  // End call triggers
1275 
1276  $this->db->commit();
1277  return 1;
1278  } else {
1279  $this->db->rollback();
1280  return -1;
1281  }
1282  }
1283 
1291  public function create($user, $notrigger = 0)
1292  {
1293  global $conf, $langs;
1294  global $mysoc;
1295 
1296  // Clean parameters
1297  $this->setUpperOrLowerCase();
1298 
1299  $this->civility_code = trim($this->civility_code);
1300  $this->login = trim($this->login);
1301  if (!isset($this->entity)) {
1302  $this->entity = $conf->entity; // If not defined, we use default value
1303  }
1304 
1305  dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1306 
1307  // Check parameters
1308  if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
1309  $langs->load("errors");
1310  $this->error = $langs->trans("ErrorBadEMail", $this->email);
1311  return -1;
1312  }
1313  if (empty($this->login)) {
1314  $langs->load("errors");
1315  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1316  return -1;
1317  }
1318 
1319  $this->datec = dol_now();
1320 
1321  $error = 0;
1322  $this->db->begin();
1323 
1324  $sql = "SELECT login FROM ".MAIN_DB_PREFIX."user";
1325  $sql .= " WHERE login ='".$this->db->escape($this->login)."'";
1326  $sql .= " AND entity IN (0,".$this->db->escape($conf->entity).")";
1327 
1328  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1329  $resql = $this->db->query($sql);
1330  if ($resql) {
1331  $num = $this->db->num_rows($resql);
1332  $this->db->free($resql);
1333 
1334  if ($num) {
1335  $this->error = 'ErrorLoginAlreadyExists';
1336  dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
1337  $this->db->rollback();
1338  return -6;
1339  } else {
1340  $sql = "INSERT INTO ".MAIN_DB_PREFIX."user (datec,login,ldap_sid,entity)";
1341  $sql .= " VALUES('".$this->db->idate($this->datec)."','".$this->db->escape($this->login)."','".$this->db->escape($this->ldap_sid)."',".$this->db->escape($this->entity).")";
1342  $result = $this->db->query($sql);
1343 
1344  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1345  if ($result) {
1346  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."user");
1347 
1348  // Set default rights
1349  if ($this->set_default_rights() < 0) {
1350  $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1351  $this->db->rollback();
1352  return -5;
1353  }
1354 
1355  if (!empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER) && !empty($conf->global->STOCK_USERSTOCK_AUTOCREATE)) {
1356  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1357  $langs->load("stocks");
1358  $entrepot = new Entrepot($this->db);
1359  $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1360  $entrepot->libelle = $entrepot->label; // For backward compatibility
1361  $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1362  $entrepot->statut = 1;
1363  $entrepot->country_id = $mysoc->country_id;
1364  $warehouseid = $entrepot->create($user);
1365 
1366  $this->fk_warehouse = $warehouseid;
1367  }
1368 
1369  // Update minor fields
1370  $result = $this->update($user, 1, 1);
1371  if ($result < 0) {
1372  $this->db->rollback();
1373  return -4;
1374  }
1375 
1376  if (!$notrigger) {
1377  // Call trigger
1378  $result = $this->call_trigger('USER_CREATE', $user);
1379  if ($result < 0) {
1380  $error++;
1381  }
1382  // End call triggers
1383  }
1384 
1385  if (!$error) {
1386  $this->db->commit();
1387  return $this->id;
1388  } else {
1389  //$this->error=$interface->error;
1390  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1391  $this->db->rollback();
1392  return -3;
1393  }
1394  } else {
1395  $this->error = $this->db->lasterror();
1396  $this->db->rollback();
1397  return -2;
1398  }
1399  }
1400  } else {
1401  $this->error = $this->db->lasterror();
1402  $this->db->rollback();
1403  return -1;
1404  }
1405  }
1406 
1407 
1408  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1417  public function create_from_contact($contact, $login = '', $password = '')
1418  {
1419  // phpcs:enable
1420  global $conf, $user, $langs;
1421 
1422  $error = 0;
1423 
1424  // Define parameters
1425  $this->admin = 0;
1426  $this->civility_code = $contact->civility_code;
1427  $this->lastname = $contact->lastname;
1428  $this->firstname = $contact->firstname;
1429  $this->gender = $contact->gender;
1430  $this->email = $contact->email;
1431  $this->socialnetworks = $contact->socialnetworks;
1432  $this->office_phone = $contact->phone_pro;
1433  $this->office_fax = $contact->fax;
1434  $this->user_mobile = $contact->phone_mobile;
1435  $this->address = $contact->address;
1436  $this->zip = $contact->zip;
1437  $this->town = $contact->town;
1438  $this->state_id = $contact->state_id;
1439  $this->country_id = $contact->country_id;
1440  $this->employee = 0;
1441 
1442  if (empty($login)) {
1443  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1444  $login = dol_buildlogin($contact->lastname, $contact->firstname);
1445  }
1446  $this->login = $login;
1447 
1448  $this->db->begin();
1449 
1450  // Create user and set $this->id. Trigger is disabled because executed later.
1451  $result = $this->create($user, 1);
1452  if ($result > 0) {
1453  $sql = "UPDATE ".MAIN_DB_PREFIX."user";
1454  $sql .= " SET fk_socpeople=".$contact->id;
1455  $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
1456  if ($contact->socid > 0) {
1457  $sql .= ", fk_soc=".$contact->socid;
1458  }
1459  $sql .= " WHERE rowid=".((int) $this->id);
1460  $resql = $this->db->query($sql);
1461 
1462  dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1463  if ($resql) {
1464  $this->context['createfromcontact'] = 'createfromcontact';
1465 
1466  // Call trigger
1467  $result = $this->call_trigger('USER_CREATE', $user);
1468  if ($result < 0) {
1469  $error++; $this->db->rollback(); return -1;
1470  }
1471  // End call triggers
1472 
1473  $this->db->commit();
1474  return $this->id;
1475  } else {
1476  $this->error = $this->db->error();
1477 
1478  $this->db->rollback();
1479  return -1;
1480  }
1481  } else {
1482  // $this->error deja positionne
1483  dol_syslog(get_class($this)."::create_from_contact - 0");
1484 
1485  $this->db->rollback();
1486  return $result;
1487  }
1488  }
1489 
1490  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1499  public function create_from_member($member, $login = '')
1500  {
1501  // phpcs:enable
1502  global $conf, $user, $langs;
1503 
1504  // Set properties on new user
1505  $this->admin = 0;
1506  $this->civility_code = $member->civility_id;
1507  $this->lastname = $member->lastname;
1508  $this->firstname = $member->firstname;
1509  $this->gender = $member->gender;
1510  $this->email = $member->email;
1511  $this->fk_member = $member->id;
1512  $this->address = $member->address;
1513  $this->zip = $member->zip;
1514  $this->town = $member->town;
1515  $this->state_id = $member->state_id;
1516  $this->country_id = $member->country_id;
1517  $this->socialnetworks = $member->socialnetworks;
1518 
1519  $this->pass = $member->pass;
1520  $this->pass_crypted = $member->pass_indatabase_crypted;
1521 
1522  if (empty($login)) {
1523  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1524  $login = dol_buildlogin($member->lastname, $member->firstname);
1525  }
1526  $this->login = $login;
1527 
1528  $this->db->begin();
1529 
1530  // Create and set $this->id
1531  $result = $this->create($user);
1532  if ($result > 0) {
1533  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
1534  $newpass = $this->setPassword($user, $this->pass);
1535  if (is_numeric($newpass) && $newpass < 0) {
1536  $result = -2;
1537  }
1538  } 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.
1539  $sql = "UPDATE ".MAIN_DB_PREFIX."user";
1540  $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
1541  $sql .= " WHERE rowid=".$this->id;
1542 
1543  $resql = $this->db->query($sql);
1544  if (!$resql) {
1545  $result = -1;
1546  }
1547  }
1548 
1549  if ($result > 0 && $member->fk_soc) { // If member is linked to a thirdparty
1550  $sql = "UPDATE ".MAIN_DB_PREFIX."user";
1551  $sql .= " SET fk_soc=".$member->fk_soc;
1552  $sql .= " WHERE rowid=".$this->id;
1553 
1554  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
1555  $resql = $this->db->query($sql);
1556  if ($resql) {
1557  $this->db->commit();
1558  return $this->id;
1559  } else {
1560  $this->error = $this->db->lasterror();
1561 
1562  $this->db->rollback();
1563  return -1;
1564  }
1565  }
1566  }
1567 
1568  if ($result > 0) {
1569  $this->db->commit();
1570  return $this->id;
1571  } else {
1572  // $this->error deja positionne
1573  $this->db->rollback();
1574  return -2;
1575  }
1576  }
1577 
1578  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1584  public function set_default_rights()
1585  {
1586  // phpcs:enable
1587  global $conf;
1588 
1589  $rd = array();
1590  $num = 0;
1591  $sql = "SELECT id FROM ".MAIN_DB_PREFIX."rights_def";
1592  $sql .= " WHERE bydefault = 1";
1593  $sql .= " AND entity = ".$conf->entity;
1594 
1595  $resql = $this->db->query($sql);
1596  if ($resql) {
1597  $num = $this->db->num_rows($resql);
1598  $i = 0;
1599  while ($i < $num) {
1600  $row = $this->db->fetch_row($resql);
1601  $rd[$i] = $row[0];
1602  $i++;
1603  }
1604  $this->db->free($resql);
1605  }
1606  $i = 0;
1607  while ($i < $num) {
1608  $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
1609  $result = $this->db->query($sql);
1610 
1611  $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
1612  $result = $this->db->query($sql);
1613  if (!$result) {
1614  return -1;
1615  }
1616  $i++;
1617  }
1618 
1619  return $i;
1620  }
1621 
1632  public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
1633  {
1634  global $conf, $langs;
1635 
1636  $nbrowsaffected = 0;
1637  $error = 0;
1638 
1639  dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
1640 
1641  // Clean parameters
1642  $this->civility_code = trim($this->civility_code);
1643  $this->lastname = trim($this->lastname);
1644  $this->firstname = trim($this->firstname);
1645  $this->employee = $this->employee ? $this->employee : 0;
1646  $this->login = trim($this->login);
1647  $this->gender = trim($this->gender);
1648  $this->pass = trim($this->pass);
1649  $this->api_key = trim($this->api_key);
1650  $this->address = $this->address ? trim($this->address) : trim($this->address);
1651  $this->zip = $this->zip ? trim($this->zip) : trim($this->zip);
1652  $this->town = $this->town ? trim($this->town) : trim($this->town);
1653  $this->setUpperOrLowerCase();
1654  $this->state_id = trim($this->state_id);
1655  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1656  $this->office_phone = trim($this->office_phone);
1657  $this->office_fax = trim($this->office_fax);
1658  $this->user_mobile = trim($this->user_mobile);
1659  $this->personal_mobile = trim($this->personal_mobile);
1660  $this->email = trim($this->email);
1661  $this->personal_email = trim($this->personal_email);
1662 
1663  $this->job = trim($this->job);
1664  $this->signature = trim($this->signature);
1665  $this->note_public = trim($this->note_public);
1666  $this->note_private = trim($this->note_private);
1667  $this->openid = trim(empty($this->openid) ? '' : $this->openid); // Avoid warning
1668  $this->admin = $this->admin ? $this->admin : 0;
1669  $this->address = empty($this->address) ? '' : $this->address;
1670  $this->zip = empty($this->zip) ? '' : $this->zip;
1671  $this->town = empty($this->town) ? '' : $this->town;
1672  $this->accountancy_code = trim($this->accountancy_code);
1673  $this->color = empty($this->color) ? '' : $this->color;
1674  $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
1675  $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
1676  $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
1677  $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
1678  $this->birth = trim($this->birth);
1679  $this->fk_warehouse = (int) $this->fk_warehouse;
1680 
1681  // Check parameters
1682  if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
1683  $langs->load("errors");
1684  $this->error = $langs->trans("ErrorBadEMail", $this->email);
1685  return -1;
1686  }
1687  if (empty($this->login)) {
1688  $langs->load("errors");
1689  $this->error = $langs->trans("ErrorFieldRequired", 'Login');
1690  return -1;
1691  }
1692 
1693  $this->db->begin();
1694 
1695  // Update datas
1696  $sql = "UPDATE ".MAIN_DB_PREFIX."user SET";
1697  $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
1698  $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
1699  $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
1700  $sql .= ", employee = ".(int) $this->employee;
1701  $sql .= ", login = '".$this->db->escape($this->login)."'";
1702  $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape($this->api_key)."'" : "null");
1703  $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman'
1704  $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth)."'" : 'null');
1705  if (!empty($user->admin)) {
1706  $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
1707  }
1708  $sql .= ", address = '".$this->db->escape($this->address)."'";
1709  $sql .= ", zip = '".$this->db->escape($this->zip)."'";
1710  $sql .= ", town = '".$this->db->escape($this->town)."'";
1711  $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".$this->db->escape($this->state_id)."'" : "null");
1712  $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".$this->db->escape($this->country_id)."'" : "null");
1713  $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
1714  $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
1715  $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
1716  $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
1717  $sql .= ", email = '".$this->db->escape($this->email)."'";
1718  $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
1719  $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1720  $sql .= ", job = '".$this->db->escape($this->job)."'";
1721  $sql .= ", signature = '".$this->db->escape($this->signature)."'";
1722  $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
1723  $sql .= ", color = '".$this->db->escape($this->color)."'";
1724  $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
1725  $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
1726  $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
1727  $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
1728  $sql .= ", note = '".$this->db->escape($this->note_private)."'";
1729  $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
1730  $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
1731  $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
1732  $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".$this->db->escape($this->fk_user)."'" : "null");
1733  $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".$this->db->escape($this->fk_user_expense_validator)."'" : "null");
1734  $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".$this->db->escape($this->fk_user_holiday_validator)."'" : "null");
1735  if (isset($this->thm) || $this->thm != '') {
1736  $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
1737  }
1738  if (isset($this->tjm) || $this->tjm != '') {
1739  $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
1740  }
1741  if (isset($this->salary) || $this->salary != '') {
1742  $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
1743  }
1744  if (isset($this->salaryextra) || $this->salaryextra != '') {
1745  $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
1746  }
1747  $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
1748  $sql .= ", entity = '".$this->db->escape($this->entity)."'";
1749  $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
1750  $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
1751  $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
1752  $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
1753  $sql .= " WHERE rowid = ".$this->id;
1754 
1755  dol_syslog(get_class($this)."::update", LOG_DEBUG);
1756  $resql = $this->db->query($sql);
1757  if ($resql) {
1758  $nbrowsaffected += $this->db->affected_rows($resql);
1759 
1760  // Update password
1761  if (!empty($this->pass)) {
1762  if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted) {
1763  // Si mot de passe saisi et different de celui en base
1764  $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass);
1765  if (!$nbrowsaffected) {
1766  $nbrowsaffected++;
1767  }
1768  }
1769  }
1770 
1771  // If user is linked to a member, remove old link to this member
1772  if ($this->fk_member > 0) {
1773  dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
1774  $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL where fk_member = ".$this->fk_member;
1775  $resql = $this->db->query($sql);
1776  if (!$resql) {
1777  $this->error = $this->db->error(); $this->db->rollback(); return -5;
1778  }
1779  }
1780  // Set link to user
1781  dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
1782  $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member =".($this->fk_member > 0 ? $this->fk_member : 'null')." where rowid = ".$this->id;
1783  $resql = $this->db->query($sql);
1784  if (!$resql) {
1785  $this->error = $this->db->error(); $this->db->rollback(); return -5;
1786  }
1787 
1788  if ($nbrowsaffected) { // If something has changed in data
1789  if ($this->fk_member > 0 && !$nosyncmember) {
1790  dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
1791 
1792  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1793 
1794  // This user is linked with a member, so we also update member information
1795  // if this is an update.
1796  $adh = new Adherent($this->db);
1797  $result = $adh->fetch($this->fk_member);
1798 
1799  if ($result > 0) {
1800  $adh->civility_code = $this->civility_code;
1801  $adh->firstname = $this->firstname;
1802  $adh->lastname = $this->lastname;
1803  $adh->login = $this->login;
1804  $adh->gender = $this->gender;
1805  $adh->birth = $this->birth;
1806 
1807  $adh->pass = $this->pass;
1808 
1809  //$adh->societe = (empty($adh->societe) && $this->societe_id ? $this->societe_id : $adh->societe);
1810 
1811  $adh->address = $this->address;
1812  $adh->town = $this->town;
1813  $adh->zip = $this->zip;
1814  $adh->state_id = $this->state_id;
1815  $adh->country_id = $this->country_id;
1816 
1817  $adh->email = $this->email;
1818 
1819  $adh->socialnetworks = $this->socialnetworks;
1820 
1821  $adh->phone = $this->office_phone;
1822  $adh->phone_mobile = $this->user_mobile;
1823 
1824  $adh->user_id = $this->id;
1825  $adh->user_login = $this->login;
1826 
1827  $result = $adh->update($user, 0, 1, 0);
1828  if ($result < 0) {
1829  $this->error = $adh->error;
1830  $this->errors = $adh->errors;
1831  dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
1832  $error++;
1833  }
1834  } elseif ($result < 0) {
1835  $this->error = $adh->error;
1836  $this->errors = $adh->errors;
1837  $error++;
1838  }
1839  }
1840 
1841  if ($this->contact_id > 0 && !$nosynccontact) {
1842  dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
1843 
1844  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1845 
1846  // This user is linked with a contact, so we also update contact information if this is an update.
1847  $tmpobj = new Contact($this->db);
1848  $result = $tmpobj->fetch($this->contact_id);
1849 
1850  if ($result >= 0) {
1851  $tmpobj->civility_code = $this->civility_code;
1852  $tmpobj->firstname = $this->firstname;
1853  $tmpobj->lastname = $this->lastname;
1854  $tmpobj->login = $this->login;
1855  $tmpobj->gender = $this->gender;
1856  $tmpobj->birth = $this->birth;
1857 
1858  //$tmpobj->pass=$this->pass;
1859 
1860  //$tmpobj->societe=(empty($tmpobj->societe) && $this->societe_id ? $this->societe_id : $tmpobj->societe);
1861 
1862  $tmpobj->email = $this->email;
1863 
1864  $tmpobj->socialnetworks = $this->socialnetworks;
1865 
1866  $tmpobj->phone_pro = $this->office_phone;
1867  $tmpobj->phone_mobile = $this->user_mobile;
1868  $tmpobj->fax = $this->office_fax;
1869 
1870  $tmpobj->address = $this->address;
1871  $tmpobj->town = $this->town;
1872  $tmpobj->zip = $this->zip;
1873  $tmpobj->state_id = $this->state_id;
1874  $tmpobj->country_id = $this->country_id;
1875 
1876  $tmpobj->user_id = $this->id;
1877  $tmpobj->user_login = $this->login;
1878 
1879  $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
1880  if ($result < 0) {
1881  $this->error = $tmpobj->error;
1882  $this->errors = $tmpobj->errors;
1883  dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
1884  $error++;
1885  }
1886  } else {
1887  $this->error = $tmpobj->error;
1888  $this->errors = $tmpobj->errors;
1889  $error++;
1890  }
1891  }
1892  }
1893 
1894  $action = 'update';
1895 
1896  // Actions on extra fields
1897  if (!$error) {
1898  $result = $this->insertExtraFields();
1899  if ($result < 0) {
1900  $error++;
1901  }
1902  }
1903 
1904  if (!$error && !$notrigger) {
1905  // Call trigger
1906  $result = $this->call_trigger('USER_MODIFY', $user);
1907  if ($result < 0) {
1908  $error++;
1909  }
1910  // End call triggers
1911  }
1912 
1913  if (!$error) {
1914  $this->db->commit();
1915  return $nbrowsaffected;
1916  } else {
1917  dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
1918  $this->db->rollback();
1919  return -1;
1920  }
1921  } else {
1922  $this->error = $this->db->lasterror();
1923  $this->db->rollback();
1924  return -2;
1925  }
1926  }
1927 
1928  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1935  public function update_last_login_date()
1936  {
1937  // phpcs:enable
1938  $now = dol_now();
1939 
1940  $sql = "UPDATE ".MAIN_DB_PREFIX."user SET";
1941  $sql .= " datepreviouslogin = datelastlogin,";
1942  $sql .= " datelastlogin = '".$this->db->idate($now)."',";
1943  $sql .= " tms = tms"; // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
1944  $sql .= " WHERE rowid = ".$this->id;
1945 
1946  dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
1947  $resql = $this->db->query($sql);
1948  if ($resql) {
1949  $this->datepreviouslogin = $this->datelastlogin;
1950  $this->datelastlogin = $now;
1951  return 1;
1952  } else {
1953  $this->error = $this->db->lasterror().' sql='.$sql;
1954  return -1;
1955  }
1956  }
1957 
1958 
1969  public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0)
1970  {
1971  global $conf, $langs;
1972  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1973 
1974  $error = 0;
1975 
1976  dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
1977 
1978  // If new password not provided, we generate one
1979  if (!$password) {
1980  $password = getRandomPassword(false);
1981  }
1982 
1983  // Crypt password
1984  $password_crypted = dol_hash($password);
1985 
1986  // Mise a jour
1987  if (!$changelater) {
1988  if (!is_object($this->oldcopy)) {
1989  $this->oldcopy = clone $this;
1990  }
1991 
1992  $this->db->begin();
1993 
1994  $sql = "UPDATE ".MAIN_DB_PREFIX."user";
1995  $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
1996  $sql .= " pass_temp = null";
1997  if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
1998  $sql .= ", pass = null";
1999  } else {
2000  $sql .= ", pass = '".$this->db->escape($password)."'";
2001  }
2002  $sql .= " WHERE rowid = ".$this->id;
2003 
2004  dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2005  $result = $this->db->query($sql);
2006  if ($result) {
2007  if ($this->db->affected_rows($result)) {
2008  $this->pass = $password;
2009  $this->pass_indatabase = $password;
2010  $this->pass_indatabase_crypted = $password_crypted;
2011 
2012  if ($this->fk_member && !$nosyncmember) {
2013  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2014 
2015  // This user is linked with a member, so we also update members informations
2016  // if this is an update.
2017  $adh = new Adherent($this->db);
2018  $result = $adh->fetch($this->fk_member);
2019 
2020  if ($result >= 0) {
2021  $result = $adh->setPassword($user, $this->pass, (empty($conf->global->DATABASE_PWD_ENCRYPTED) ? 0 : 1), 1); // Cryptage non gere dans module adherent
2022  if ($result < 0) {
2023  $this->error = $adh->error;
2024  dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2025  $error++;
2026  }
2027  } else {
2028  $this->error = $adh->error;
2029  $error++;
2030  }
2031  }
2032 
2033  dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2034 
2035  if (!$error && !$notrigger) {
2036  // Call trigger
2037  $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2038  if ($result < 0) {
2039  $error++; $this->db->rollback(); return -1;
2040  }
2041  // End call triggers
2042  }
2043 
2044  $this->db->commit();
2045  return $this->pass;
2046  } else {
2047  $this->db->rollback();
2048  return 0;
2049  }
2050  } else {
2051  $this->db->rollback();
2052  dol_print_error($this->db);
2053  return -1;
2054  }
2055  } else {
2056  // We store clear password in password temporary field.
2057  // After receiving confirmation link, we will crypt it and store it in pass_crypted
2058  $sql = "UPDATE ".MAIN_DB_PREFIX."user";
2059  $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2060  $sql .= " WHERE rowid = ".$this->id;
2061 
2062  dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2063  $result = $this->db->query($sql);
2064  if ($result) {
2065  return $password;
2066  } else {
2067  dol_print_error($this->db);
2068  return -3;
2069  }
2070  }
2071  }
2072 
2073 
2074  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2083  public function send_password($user, $password = '', $changelater = 0)
2084  {
2085  // phpcs:enable
2086  global $conf, $langs;
2087  global $dolibarr_main_url_root;
2088 
2089  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2090 
2091  $msgishtml = 0;
2092 
2093  // Define $msg
2094  $mesg = '';
2095 
2096  $outputlangs = new Translate("", $conf);
2097 
2098  if (isset($this->conf->MAIN_LANG_DEFAULT)
2099  && $this->conf->MAIN_LANG_DEFAULT != 'auto') { // If user has defined its own language (rare because in most cases, auto is used)
2100  $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2101  }
2102 
2103  if ($this->conf->MAIN_LANG_DEFAULT) {
2104  $outputlangs->setDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2105  } else { // If user has not defined its own language, we used current language
2106  $outputlangs = $langs;
2107  }
2108 
2109  // Load translation files required by the page
2110  $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2111 
2112  $appli = constant('DOL_APPLICATION_TITLE');
2113  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
2114  $appli = $conf->global->MAIN_APPLICATION_TITLE;
2115  }
2116 
2117  $subject = $outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2118 
2119  // Define $urlwithroot
2120  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2121  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2122 
2123  if (!$changelater) {
2124  $url = $urlwithroot.'/';
2125  $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2126  $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2127  $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2128  $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2129  $mesg .= "\n";
2130 
2131  $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2132  $mesg .= "--\n";
2133  $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2134 
2135  dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2136  } else {
2137  $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword&username='.urlencode($this->login)."&passwordhash=".dol_hash($password);
2138 
2139  $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."\n";
2140  $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :\n\n";
2141  $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2142  $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2143  $mesg .= "\n";
2144  $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :\n";
2145  $mesg .= $url."\n\n";
2146  $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."\n\n";
2147 
2148  dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2149  }
2150 
2151  $trackid = 'use'.$this->id;
2152 
2153  $mailfile = new CMailFile(
2154  $subject,
2155  $this->email,
2156  $conf->global->MAIN_MAIL_EMAIL_FROM,
2157  $mesg,
2158  array(),
2159  array(),
2160  array(),
2161  '',
2162  '',
2163  0,
2164  $msgishtml,
2165  '',
2166  '',
2167  $trackid
2168  );
2169 
2170  if ($mailfile->sendfile()) {
2171  return 1;
2172  } else {
2173  $langs->trans("errors");
2174  $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2175  return -1;
2176  }
2177  }
2178 
2184  public function error()
2185  {
2186  return $this->error;
2187  }
2188 
2189 
2190  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2196  public function fetch_clicktodial()
2197  {
2198  // phpcs:enable
2199  $sql = "SELECT url, login, pass, poste ";
2200  $sql .= " FROM ".MAIN_DB_PREFIX."user_clicktodial as u";
2201  $sql .= " WHERE u.fk_user = ".$this->id;
2202 
2203  $resql = $this->db->query($sql);
2204  if ($resql) {
2205  if ($this->db->num_rows($resql)) {
2206  $obj = $this->db->fetch_object($resql);
2207 
2208  $this->clicktodial_url = $obj->url;
2209  $this->clicktodial_login = $obj->login;
2210  $this->clicktodial_password = $obj->pass;
2211  $this->clicktodial_poste = $obj->poste;
2212  }
2213 
2214  $this->clicktodial_loaded = 1; // Data loaded (found or not)
2215 
2216  $this->db->free($resql);
2217  return 1;
2218  } else {
2219  $this->error = $this->db->error();
2220  return -1;
2221  }
2222  }
2223 
2224  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2230  public function update_clicktodial()
2231  {
2232  // phpcs:enable
2233  $this->db->begin();
2234 
2235  $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_clicktodial";
2236  $sql .= " WHERE fk_user = ".$this->id;
2237 
2238  dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2239  $result = $this->db->query($sql);
2240 
2241  $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_clicktodial";
2242  $sql .= " (fk_user,url,login,pass,poste)";
2243  $sql .= " VALUES (".$this->id;
2244  $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2245  $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2246  $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2247  $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2248 
2249  dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2250  $result = $this->db->query($sql);
2251  if ($result) {
2252  $this->db->commit();
2253  return 1;
2254  } else {
2255  $this->db->rollback();
2256  $this->error = $this->db->lasterror();
2257  return -1;
2258  }
2259  }
2260 
2261 
2262  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2271  public function SetInGroup($group, $entity, $notrigger = 0)
2272  {
2273  // phpcs:enable
2274  global $conf, $langs, $user;
2275 
2276  $error = 0;
2277 
2278  $this->db->begin();
2279 
2280  $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user";
2281  $sql .= " WHERE fk_user = ".$this->id;
2282  $sql .= " AND fk_usergroup = ".$group;
2283  $sql .= " AND entity = ".$entity;
2284 
2285  $result = $this->db->query($sql);
2286 
2287  $sql = "INSERT INTO ".MAIN_DB_PREFIX."usergroup_user (entity, fk_user, fk_usergroup)";
2288  $sql .= " VALUES (".$entity.",".$this->id.",".$group.")";
2289 
2290  $result = $this->db->query($sql);
2291  if ($result) {
2292  if (!$error && !$notrigger) {
2293  $this->newgroupid = $group; // deprecated. Remove this.
2294  $this->context = array('audit'=>$langs->trans("UserSetInGroup"), 'newgroupid'=>$group);
2295 
2296  // Call trigger
2297  $result = $this->call_trigger('USER_MODIFY', $user);
2298  if ($result < 0) {
2299  $error++;
2300  }
2301  // End call triggers
2302  }
2303 
2304  if (!$error) {
2305  $this->db->commit();
2306  return 1;
2307  } else {
2308  dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2309  $this->db->rollback();
2310  return -2;
2311  }
2312  } else {
2313  $this->error = $this->db->lasterror();
2314  $this->db->rollback();
2315  return -1;
2316  }
2317  }
2318 
2319  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2328  public function RemoveFromGroup($group, $entity, $notrigger = 0)
2329  {
2330  // phpcs:enable
2331  global $conf, $langs, $user;
2332 
2333  $error = 0;
2334 
2335  $this->db->begin();
2336 
2337  $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user";
2338  $sql .= " WHERE fk_user = ".$this->id;
2339  $sql .= " AND fk_usergroup = ".$group;
2340  $sql .= " AND entity = ".$entity;
2341 
2342  $result = $this->db->query($sql);
2343  if ($result) {
2344  if (!$error && !$notrigger) {
2345  $this->oldgroupid = $group; // deprecated. Remove this.
2346  $this->context = array('audit'=>$langs->trans("UserRemovedFromGroup"), 'oldgroupid'=>$group);
2347 
2348  // Call trigger
2349  $result = $this->call_trigger('USER_MODIFY', $user);
2350  if ($result < 0) {
2351  $error++;
2352  }
2353  // End call triggers
2354  }
2355 
2356  if (!$error) {
2357  $this->db->commit();
2358  return 1;
2359  } else {
2360  dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2361  $this->db->rollback();
2362  return -2;
2363  }
2364  } else {
2365  $this->error = $this->db->lasterror();
2366  $this->db->rollback();
2367  return -1;
2368  }
2369  }
2370 
2371 
2382  public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
2383  {
2384  $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2385  $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
2386  $result .= '</a>';
2387 
2388  return $result;
2389  }
2390 
2406  public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
2407  {
2408  global $langs, $conf, $db, $hookmanager, $user;
2409  global $dolibarr_main_authentication, $dolibarr_main_demo;
2410  global $menumanager;
2411 
2412  if (!$user->rights->user->user->lire && $user->id != $this->id) {
2413  $option = 'nolink';
2414  }
2415 
2416  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) {
2417  $withpictoimg = 0;
2418  }
2419 
2420  $result = ''; $label = '';
2421  $companylink = '';
2422 
2423  if (!empty($this->photo)) {
2424  $label .= '<div class="photointooltip">';
2425  $label .= Form::showphoto('userphoto', $this, 0, 60, 0, 'photowithmargin photologintooltip', 'small', 0, 1); // Force height to 60 so we total height of tooltip can be calculated and collision can be managed
2426  $label .= '</div><div style="clear: both;"></div>';
2427  }
2428 
2429  // Info Login
2430  $label .= '<div class="centpercent">';
2431  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u>';
2432  $label .= ' '.$this->getLibStatut(4);
2433  $label .= '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs, ''));
2434  if (!empty($this->login)) {
2435  $label .= '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
2436  }
2437  if (!empty($this->job)) {
2438  $label .= '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
2439  }
2440  $label .= '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
2441  if (!empty($this->phone)) {
2442  $label .= '<br><b>'.$langs->trans("Phone").':</b> '.dol_string_nohtmltag($this->phone);
2443  }
2444  if (!empty($this->admin)) {
2445  $label .= '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
2446  }
2447  $company = '';
2448  if (!empty($this->socid)) { // Add thirdparty for external users
2449  $thirdpartystatic = new Societe($db);
2450  $thirdpartystatic->fetch($this->socid);
2451  if (empty($hidethirdpartylogo)) {
2452  $companylink = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2453  }
2454  $company = ' ('.$langs->trans("Company").': '.dol_string_nohtmltag($thirdpartystatic->name).')';
2455  }
2456  $type = ($this->socid ? $langs->trans("External").$company : $langs->trans("Internal"));
2457  $label .= '<br><b>'.$langs->trans("Type").':</b> '.dol_string_nohtmltag($type);
2458  $label .= '</div>';
2459  if ($infologin > 0) {
2460  $label .= '<br>';
2461  $label .= '<br><u>'.$langs->trans("Session").'</u>';
2462  $label .= '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
2463  if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) {
2464  $label .= '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
2465  }
2466  $label .= '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
2467  $label .= '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
2468  $label .= '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
2469  $label .= '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
2470  $label .= '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
2471  $s = picto_from_langcode($langs->getDefaultLang());
2472  $label .= '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
2473  $label .= '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
2474  $label .= '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
2475  $label .= '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
2476  if ($conf->browser->layout == 'phone') {
2477  $label .= '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
2478  }
2479  if (!empty($_SESSION["disablemodules"])) {
2480  $label .= '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(join(', ', explode(',', $_SESSION["disablemodules"])));
2481  }
2482  }
2483  if ($infologin < 0) {
2484  $label = '';
2485  }
2486 
2487  $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id;
2488  if ($option == 'leave') {
2489  $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id;
2490  }
2491 
2492  if ($option != 'nolink') {
2493  // Add param to save lastsearch_values or not
2494  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2495  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2496  $add_save_lastsearch_values = 1;
2497  }
2498  if ($add_save_lastsearch_values) {
2499  $url .= '&save_lastsearch_values=1';
2500  }
2501  }
2502 
2503  $linkstart = '<a href="'.$url.'"';
2504  $linkclose = "";
2505  if (empty($notooltip)) {
2506  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2507  $langs->load("users");
2508  $label = $langs->trans("ShowUser");
2509  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2510  }
2511  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
2512  $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
2513 
2514  /*
2515  $hookmanager->initHooks(array('userdao'));
2516  $parameters=array('id'=>$this->id);
2517  $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
2518  if ($reshook > 0) $linkclose = $hookmanager->resPrint;
2519  */
2520  }
2521 
2522  $linkstart .= $linkclose.'>';
2523  $linkend = '</a>';
2524 
2525  //if ($withpictoimg == -1) $result.='<div class="nowrap">';
2526  $result .= (($option == 'nolink') ? '' : $linkstart);
2527  if ($withpictoimg) {
2528  $paddafterimage = '';
2529  if (abs($withpictoimg) == 1) {
2530  $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
2531  }
2532  // Only picto
2533  if ($withpictoimg > 0) {
2534  $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
2535  }
2536  // Picto must be a photo
2537  else {
2538  $picto = '<!-- picto photo user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'"'.($paddafterimage ? ' '.$paddafterimage : '').'>'.Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1).'</span>';
2539  }
2540  $result .= $picto;
2541  }
2542  if ($withpictoimg > -2 && $withpictoimg != 2) {
2543  if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2544  $result .= '<span class="nopadding usertext'.((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
2545  }
2546  if ($mode == 'login') {
2547  $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
2548  } else {
2549  $result .= dol_string_nohtmltag($this->getFullName($langs, '', ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
2550  }
2551  if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2552  $result .= '</span>';
2553  }
2554  }
2555  $result .= (($option == 'nolink') ? '' : $linkend);
2556  //if ($withpictoimg == -1) $result.='</div>';
2557 
2558  $result .= $companylink;
2559 
2560  global $action;
2561  $hookmanager->initHooks(array('userdao'));
2562  $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
2563  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2564  if ($reshook > 0) {
2565  $result = $hookmanager->resPrint;
2566  } else {
2567  $result .= $hookmanager->resPrint;
2568  }
2569 
2570  return $result;
2571  }
2572 
2580  public function getLoginUrl($withpicto = 0, $option = '')
2581  {
2582  global $langs, $user;
2583 
2584  $result = '';
2585 
2586  $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2587  $linkend = '</a>';
2588 
2589  //Check user's rights to see an other user
2590  if ((!$user->rights->user->user->lire && $this->id != $user->id)) {
2591  $option = 'nolink';
2592  }
2593 
2594  if ($option == 'xxx') {
2595  $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2596  $linkend = '</a>';
2597  }
2598 
2599  if ($option == 'nolink') {
2600  $linkstart = '';
2601  $linkend = '';
2602  }
2603 
2604  $result .= $linkstart;
2605  if ($withpicto) {
2606  $result .= img_object($langs->trans("ShowUser"), 'user', 'class="paddingright"');
2607  }
2608  $result .= $this->login;
2609  $result .= $linkend;
2610  return $result;
2611  }
2612 
2619  public function getLibStatut($mode = 0)
2620  {
2621  return $this->LibStatut($this->statut, $mode);
2622  }
2623 
2624  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2632  public function LibStatut($status, $mode = 0)
2633  {
2634  // phpcs:enable
2635  global $langs;
2636 
2637  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2638  global $langs;
2639  //$langs->load("mymodule");
2640  $this->labelStatus[self::STATUS_ENABLED] = $langs->trans('Enabled');
2641  $this->labelStatus[self::STATUS_DISABLED] = $langs->trans('Disabled');
2642  $this->labelStatusShort[self::STATUS_ENABLED] = $langs->trans('Enabled');
2643  $this->labelStatusShort[self::STATUS_DISABLED] = $langs->trans('Disabled');
2644  }
2645 
2646  $statusType = 'status5';
2647  if ($status == self::STATUS_ENABLED) {
2648  $statusType = 'status4';
2649  }
2650 
2651  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2652  }
2653 
2654 
2655  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2656  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2666  public function _load_ldap_dn($info, $mode = 0)
2667  {
2668  // phpcs:enable
2669  global $conf;
2670  $dn = '';
2671  if ($mode == 0) {
2672  $dn = $conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS].",".$conf->global->LDAP_USER_DN;
2673  } elseif ($mode == 1) {
2674  $dn = $conf->global->LDAP_USER_DN;
2675  } elseif ($mode == 2) {
2676  $dn = $conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS];
2677  }
2678  return $dn;
2679  }
2680 
2681  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2682  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2688  public function _load_ldap_info()
2689  {
2690  // phpcs:enable
2691  global $conf, $langs;
2692 
2693  $info = array();
2694 
2695  $socialnetworks = getArrayOfSocialNetworks();
2696 
2697  $keymodified = false;
2698 
2699  // Object classes
2700  $info["objectclass"] = explode(',', $conf->global->LDAP_USER_OBJECT_CLASS);
2701 
2702  $this->fullname = $this->getFullName($langs);
2703 
2704  // Possible LDAP KEY (constname => varname)
2705  $ldapkey = array(
2706  'LDAP_FIELD_FULLNAME' => 'fullname',
2707  'LDAP_FIELD_NAME' => 'lastname',
2708  'LDAP_FIELD_FIRSTNAME' => 'firstname',
2709  'LDAP_FIELD_LOGIN' => 'login',
2710  'LDAP_FIELD_LOGIN_SAMBA'=> 'login',
2711  'LDAP_FIELD_PHONE' => 'office_phone',
2712  'LDAP_FIELD_MOBILE' => 'user_mobile',
2713  'LDAP_FIELD_FAX' => 'office_fax',
2714  'LDAP_FIELD_MAIL' => 'email',
2715  'LDAP_FIELD_SID' => 'ldap_sid',
2716  );
2717 
2718  // Champs
2719  foreach ($ldapkey as $constname => $varname) {
2720  if (!empty($this->$varname) && !empty($conf->global->$constname)) {
2721  $info[$conf->global->$constname] = $this->$varname;
2722 
2723  // Check if it is the LDAP key and if its value has been changed
2724  if (!empty($conf->global->LDAP_KEY_USERS) && $conf->global->LDAP_KEY_USERS == $conf->global->$constname) {
2725  if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
2726  $keymodified = true; // For check if LDAP key has been modified
2727  }
2728  }
2729  }
2730  }
2731  foreach ($socialnetworks as $key => $value) {
2732  if ($this->socialnetworks[$value['label']] && !empty($conf->global->{'LDAP_FIELD_'.strtoupper($value['label'])})) {
2733  $info[$conf->global->{'LDAP_FIELD_'.strtoupper($value['label'])}] = $this->socialnetworks[$value['label']];
2734  }
2735  }
2736  if ($this->address && !empty($conf->global->LDAP_FIELD_ADDRESS)) {
2737  $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address;
2738  }
2739  if ($this->zip && !empty($conf->global->LDAP_FIELD_ZIP)) {
2740  $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip;
2741  }
2742  if ($this->town && !empty($conf->global->LDAP_FIELD_TOWN)) {
2743  $info[$conf->global->LDAP_FIELD_TOWN] = $this->town;
2744  }
2745  if ($this->note_public && !empty($conf->global->LDAP_FIELD_DESCRIPTION)) {
2746  $info[$conf->global->LDAP_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_public, 2);
2747  }
2748  if ($this->socid > 0) {
2749  $soc = new Societe($this->db);
2750  $soc->fetch($this->socid);
2751 
2752  $info[$conf->global->LDAP_FIELD_COMPANY] = $soc->name;
2753  if ($soc->client == 1) {
2754  $info["businessCategory"] = "Customers";
2755  }
2756  if ($soc->client == 2) {
2757  $info["businessCategory"] = "Prospects";
2758  }
2759  if ($soc->fournisseur == 1) {
2760  $info["businessCategory"] = "Suppliers";
2761  }
2762  }
2763 
2764  // When password is modified
2765  if (!empty($this->pass)) {
2766  if (!empty($conf->global->LDAP_FIELD_PASSWORD)) {
2767  $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte
2768  }
2769  if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
2770  $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption)
2771  }
2772  }
2773  // Set LDAP password if possible
2774  elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') { // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
2775  if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
2776  // Just for the default MD5 !
2777  if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) {
2778  if ($this->pass_indatabase_crypted && !empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
2779  $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase_crypted, 5); // Create OpenLDAP MD5 password from Dolibarr MD5 password
2780  }
2781  }
2782  }
2783  // Use $this->pass_indatabase value if exists
2784  elseif (!empty($this->pass_indatabase)) {
2785  if (!empty($conf->global->LDAP_FIELD_PASSWORD)) {
2786  $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte
2787  }
2788  if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
2789  $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption
2790  }
2791  }
2792  }
2793 
2794  if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') {
2795  $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
2796 
2797  $info['uidnumber'] = $this->id;
2798 
2799  $info['phpgwTz'] = 0;
2800  $info['phpgwMailType'] = 'INTERNET';
2801  $info['phpgwMailHomeType'] = 'INTERNET';
2802 
2803  $info["phpgwContactTypeId"] = 'n';
2804  $info["phpgwContactCatId"] = 0;
2805  $info["phpgwContactAccess"] = "public";
2806 
2807  if (dol_strlen($this->egroupware_id) == 0) {
2808  $this->egroupware_id = 1;
2809  }
2810 
2811  $info["phpgwContactOwner"] = $this->egroupware_id;
2812 
2813  if ($this->email) {
2814  $info["rfc822Mailbox"] = $this->email;
2815  }
2816  if ($this->phone_mobile) {
2817  $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
2818  }
2819  }
2820 
2821  if (!empty($conf->global->LDAP_FIELD_USERID)) {
2822  $info[$conf->global->LDAP_FIELD_USERID] = $this->id;
2823  }
2824  if (!empty($info[$conf->global->LDAP_FIELD_GROUPID])) {
2825  $usergroup = new UserGroup($this->db);
2826  $groupslist = $usergroup->listGroupsForUser($this->id);
2827  $info[$conf->global->LDAP_FIELD_GROUPID] = '1';
2828  if (!empty($groupslist)) {
2829  foreach ($groupslist as $groupforuser) {
2830  $info[$conf->global->LDAP_FIELD_GROUPID] = $groupforuser->id; //Select first group in list
2831  break;
2832  }
2833  }
2834  }
2835  if (!empty($this->firstname) && !empty($conf->global->LDAP_FIELD_HOMEDIRECTORY) && !empty($conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX)) {
2836  $info[$conf->global->LDAP_FIELD_HOMEDIRECTORY] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->firstname";
2837  }
2838 
2839  return $info;
2840  }
2841 
2842 
2850  public function initAsSpecimen()
2851  {
2852  global $user, $langs;
2853 
2854  $now = dol_now();
2855 
2856  // Initialise parametres
2857  $this->id = 0;
2858  $this->ref = 'SPECIMEN';
2859  $this->specimen = 1;
2860 
2861  $this->lastname = 'DOLIBARR';
2862  $this->firstname = 'SPECIMEN';
2863  $this->gender = 'man';
2864  $this->note_public = 'This is a note public';
2865  $this->note_private = 'This is a note private';
2866  $this->email = 'email@specimen.com';
2867  $this->personal_email = 'personalemail@specimen.com';
2868  $this->socialnetworks = array(
2869  'skype' => 'skypepseudo',
2870  'twitter' => 'twitterpseudo',
2871  'facebook' => 'facebookpseudo',
2872  'linkedin' => 'linkedinpseudo',
2873  );
2874  $this->office_phone = '0999999999';
2875  $this->office_fax = '0999999998';
2876  $this->user_mobile = '0999999997';
2877  $this->personal_mobile = '0999999996';
2878  $this->admin = 0;
2879  $this->login = 'dolibspec';
2880  $this->pass = 'dolibspec';
2881  //$this->pass_indatabase='dolibspec'; Set after a fetch
2882  //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
2883  $this->datec = $now;
2884  $this->datem = $now;
2885 
2886  $this->datelastlogin = $now;
2887  $this->datepreviouslogin = $now;
2888  $this->statut = 1;
2889 
2890  $this->entity = 1;
2891  return 1;
2892  }
2893 
2900  public function info($id)
2901  {
2902  $sql = "SELECT u.rowid, u.login as ref, u.datec,";
2903  $sql .= " u.tms as date_modification, u.entity";
2904  $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2905  $sql .= " WHERE u.rowid = ".$id;
2906 
2907  $result = $this->db->query($sql);
2908  if ($result) {
2909  if ($this->db->num_rows($result)) {
2910  $obj = $this->db->fetch_object($result);
2911 
2912  $this->id = $obj->rowid;
2913 
2914  $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2915  $this->date_creation = $this->db->jdate($obj->datec);
2916  $this->date_modification = $this->db->jdate($obj->date_modification);
2917  $this->entity = $obj->entity;
2918  }
2919 
2920  $this->db->free($result);
2921  } else {
2922  dol_print_error($this->db);
2923  }
2924  }
2925 
2926 
2932  public function getNbOfEMailings()
2933  {
2934  $sql = "SELECT count(mc.email) as nb";
2935  $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
2936  $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
2937  $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes
2938 
2939  $resql = $this->db->query($sql);
2940  if ($resql) {
2941  $obj = $this->db->fetch_object($resql);
2942  $nb = $obj->nb;
2943 
2944  $this->db->free($resql);
2945  return $nb;
2946  } else {
2947  $this->error = $this->db->error();
2948  return -1;
2949  }
2950  }
2951 
2960  public function getNbOfUsers($limitTo, $option = '', $admin = -1)
2961  {
2962  global $conf;
2963 
2964  $sql = "SELECT count(rowid) as nb";
2965  $sql .= " FROM ".MAIN_DB_PREFIX."user";
2966  if ($option == 'superadmin') {
2967  $sql .= " WHERE entity = 0";
2968  } else {
2969  $sql .= " WHERE entity IN (".getEntity('user', 0).")";
2970  if ($limitTo == 'active') {
2971  $sql .= " AND statut = 1";
2972  }
2973  }
2974  if ($admin >= 0) {
2975  $sql .= " AND admin = ".(int) $admin;
2976  }
2977 
2978  $resql = $this->db->query($sql);
2979  if ($resql) {
2980  $obj = $this->db->fetch_object($resql);
2981  $nb = (int) $obj->nb;
2982 
2983  $this->db->free($resql);
2984  return $nb;
2985  } else {
2986  $this->error = $this->db->lasterror();
2987  return -1;
2988  }
2989  }
2990 
2991  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2998  public function update_ldap2dolibarr(&$ldapuser)
2999  {
3000  // phpcs:enable
3001  // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3002  global $user, $conf;
3003 
3004  $socialnetworks = getArrayOfSocialNetworks();
3005 
3006  $this->firstname = $ldapuser->{$conf->global->LDAP_FIELD_FIRSTNAME};
3007  $this->lastname = $ldapuser->{$conf->global->LDAP_FIELD_NAME};
3008  $this->login = $ldapuser->{$conf->global->LDAP_FIELD_LOGIN};
3009  $this->pass = $ldapuser->{$conf->global->LDAP_FIELD_PASSWORD};
3010  $this->pass_indatabase_crypted = $ldapuser->{$conf->global->LDAP_FIELD_PASSWORD_CRYPTED};
3011 
3012  $this->office_phone = $ldapuser->{$conf->global->LDAP_FIELD_PHONE};
3013  $this->user_mobile = $ldapuser->{$conf->global->LDAP_FIELD_MOBILE};
3014  $this->office_fax = $ldapuser->{$conf->global->LDAP_FIELD_FAX};
3015  $this->email = $ldapuser->{$conf->global->LDAP_FIELD_MAIL};
3016  foreach ($socialnetworks as $key => $value) {
3017  $tmpkey = 'LDAP_FIELD_'.strtoupper($value['label']);
3018  $this->socialnetworks[$value['label']] = $ldapuser->{$conf->global->$tmpkey};
3019  }
3020  $this->ldap_sid = $ldapuser->{$conf->global->LDAP_FIELD_SID};
3021 
3022  $this->job = $ldapuser->{$conf->global->LDAP_FIELD_TITLE};
3023  $this->note_public = $ldapuser->{$conf->global->LDAP_FIELD_DESCRIPTION};
3024 
3025  $result = $this->update($user);
3026 
3027  dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3028 
3029  return $result;
3030  }
3031 
3032 
3033  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3040  public function get_children()
3041  {
3042  // phpcs:enable
3043  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."user";
3044  $sql .= " WHERE fk_user = ".$this->id;
3045 
3046  dol_syslog(get_class($this)."::get_children sql=".$sql, LOG_DEBUG);
3047  $res = $this->db->query($sql);
3048  if ($res) {
3049  $users = array();
3050  while ($rec = $this->db->fetch_array($res)) {
3051  $user = new User($this->db);
3052  $user->fetch($rec['rowid']);
3053  $users[] = $user;
3054  }
3055  return $users;
3056  } else {
3057  dol_print_error($this->db);
3058  return -1;
3059  }
3060  }
3061 
3062 
3068  private function loadParentOf()
3069  {
3070  global $conf;
3071 
3072  $this->parentof = array();
3073 
3074  // Load array[child]=parent
3075  $sql = "SELECT fk_user as id_parent, rowid as id_son";
3076  $sql .= " FROM ".MAIN_DB_PREFIX."user";
3077  $sql .= " WHERE fk_user <> 0";
3078  $sql .= " AND entity IN (".getEntity('user').")";
3079 
3080  dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3081  $resql = $this->db->query($sql);
3082  if ($resql) {
3083  while ($obj = $this->db->fetch_object($resql)) {
3084  $this->parentof[$obj->id_son] = $obj->id_parent;
3085  }
3086  return 1;
3087  } else {
3088  dol_print_error($this->db);
3089  return -1;
3090  }
3091  }
3092 
3093  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3107  public function get_full_tree($deleteafterid = 0, $filter = '')
3108  {
3109  // phpcs:enable
3110  global $conf, $user;
3111  global $hookmanager;
3112 
3113  // Actions hooked (by external module)
3114  $hookmanager->initHooks(array('userdao'));
3115 
3116  $this->users = array();
3117 
3118  // Init this->parentof that is array(id_son=>id_parent, ...)
3119  $this->loadParentOf();
3120 
3121  // Init $this->users array
3122  $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
3123  $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
3124  // Add fields from hooks
3125  $parameters = array();
3126  $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3127  if ($reshook > 0) {
3128  $sql .= $hookmanager->resPrint;
3129  } else {
3130  $sql .= " WHERE u.entity IN (".getEntity('user').")";
3131  }
3132  if ($filter) {
3133  $sql .= " AND ".$filter;
3134  }
3135 
3136  dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3137  $resql = $this->db->query($sql);
3138  if ($resql) {
3139  $i = 0;
3140  while ($obj = $this->db->fetch_object($resql)) {
3141  $this->users[$obj->rowid]['rowid'] = $obj->rowid;
3142  $this->users[$obj->rowid]['id'] = $obj->rowid;
3143  $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
3144  $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
3145  $this->users[$obj->rowid]['firstname'] = $obj->firstname;
3146  $this->users[$obj->rowid]['lastname'] = $obj->lastname;
3147  $this->users[$obj->rowid]['login'] = $obj->login;
3148  $this->users[$obj->rowid]['statut'] = $obj->statut;
3149  $this->users[$obj->rowid]['entity'] = $obj->entity;
3150  $this->users[$obj->rowid]['email'] = $obj->email;
3151  $this->users[$obj->rowid]['gender'] = $obj->gender;
3152  $this->users[$obj->rowid]['admin'] = $obj->admin;
3153  $this->users[$obj->rowid]['photo'] = $obj->photo;
3154  $i++;
3155  }
3156  } else {
3157  dol_print_error($this->db);
3158  return -1;
3159  }
3160 
3161  // We add the fullpath property to each elements of first level (no parent exists)
3162  dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3163  foreach ($this->users as $key => $val) {
3164  $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3165  if ($result < 0) {
3166  $this->error = 'ErrorLoopInHierarchy';
3167  return -1;
3168  }
3169  }
3170 
3171  // Exclude leaf including $deleteafterid from tree
3172  if ($deleteafterid) {
3173  //print "Look to discard user ".$deleteafterid."\n";
3174  $keyfilter1 = '^'.$deleteafterid.'$';
3175  $keyfilter2 = '_'.$deleteafterid.'$';
3176  $keyfilter3 = '^'.$deleteafterid.'_';
3177  $keyfilter4 = '_'.$deleteafterid.'_';
3178  foreach ($this->users as $key => $val) {
3179  if (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath'])
3180  || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])) {
3181  unset($this->users[$key]);
3182  }
3183  }
3184  }
3185 
3186  dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
3187  $this->users = dol_sort_array($this->users, 'fullname', 'asc', true, false);
3188 
3189  //var_dump($this->users);
3190 
3191  return $this->users;
3192  }
3193 
3202  public function getAllChildIds($addcurrentuser = 0)
3203  {
3204  $childids = array();
3205 
3206  if (isset($this->cache_childids[$this->id])) {
3207  $childids = $this->cache_childids[$this->id];
3208  } else {
3209  // Init this->users
3210  $this->get_full_tree();
3211 
3212  $idtoscan = $this->id;
3213 
3214  dol_syslog("Build childid for id = ".$idtoscan);
3215  foreach ($this->users as $id => $val) {
3216  //var_dump($val['fullpath']);
3217  if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
3218  $childids[$val['id']] = $val['id'];
3219  }
3220  }
3221  }
3222  $this->cache_childids[$this->id] = $childids;
3223 
3224  if ($addcurrentuser) {
3225  $childids[$this->id] = $this->id;
3226  }
3227 
3228  return $childids;
3229  }
3230 
3231  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3240  public function build_path_from_id_user($id_user, $protection = 0)
3241  {
3242  // phpcs:enable
3243  //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
3244 
3245  if (!empty($this->users[$id_user]['fullpath'])) {
3246  // Already defined
3247  dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
3248  return 0;
3249  }
3250 
3251  // Define fullpath and fullname
3252  $this->users[$id_user]['fullpath'] = '_'.$id_user;
3253  $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
3254  $i = 0; $cursor_user = $id_user;
3255 
3256  $useridfound = array($id_user);
3257  while (!empty($this->parentof[$cursor_user])) {
3258  if (in_array($this->parentof[$cursor_user], $useridfound)) {
3259  dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
3260  return -1; // Should not happen. Protection against looping hierarchy
3261  }
3262  $useridfound[] = $this->parentof[$cursor_user];
3263  $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
3264  $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
3265  $i++; $cursor_user = $this->parentof[$cursor_user];
3266  }
3267 
3268  // We count number of _ to have level
3269  $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
3270 
3271  return 1;
3272  }
3273 
3282  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
3283  {
3284  $tables = array(
3285  'user',
3286  );
3287 
3288  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
3289  }
3290 
3291 
3292  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3298  public function load_state_board()
3299  {
3300  // phpcs:enable
3301 
3302  $this->nb = array();
3303 
3304  $sql = "SELECT count(u.rowid) as nb";
3305  $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
3306  $sql .= " WHERE u.statut > 0";
3307  //$sql.= " AND employee != 0";
3308  $sql .= " AND u.entity IN (".getEntity('user').")";
3309 
3310  $resql = $this->db->query($sql);
3311  if ($resql) {
3312  while ($obj = $this->db->fetch_object($resql)) {
3313  $this->nb["users"] = $obj->nb;
3314  }
3315  $this->db->free($resql);
3316  return 1;
3317  } else {
3318  dol_print_error($this->db);
3319  $this->error = $this->db->error();
3320  return -1;
3321  }
3322  }
3323 
3335  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3336  {
3337  global $conf, $user, $langs;
3338 
3339  $langs->load("user");
3340 
3341  // Positionne le modele sur le nom du modele a utiliser
3342  if (!dol_strlen($modele)) {
3343  if (!empty($conf->global->USER_ADDON_PDF)) {
3344  $modele = $conf->global->USER_ADDON_PDF;
3345  } else {
3346  $modele = 'bluesky';
3347  }
3348  }
3349 
3350  $modelpath = "core/modules/user/doc/";
3351 
3352  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3353  }
3354 
3355  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3363  public function user_get_property($rowid, $mode)
3364  {
3365  // phpcs:enable
3366  $user_property = '';
3367 
3368  if (empty($rowid)) {
3369  return '';
3370  }
3371 
3372  $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
3373  $sql .= " FROM ".MAIN_DB_PREFIX."user";
3374  $sql .= " WHERE rowid = ".((int) $rowid);
3375 
3376  $resql = $this->db->query($sql);
3377  if ($resql) {
3378  $nump = $this->db->num_rows($resql);
3379 
3380  if ($nump) {
3381  $obj = $this->db->fetch_object($resql);
3382 
3383  if ($mode == 'email') {
3384  $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
3385  } elseif ($mode == 'mobile') {
3386  $user_property = $obj->user_mobile;
3387  }
3388  }
3389  return $user_property;
3390  } else {
3391  dol_print_error($this->db);
3392  }
3393  }
3394 
3407  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = array(), $filtermode = 'AND', $entityfilter = false)
3408  {
3409  global $conf, $user;
3410 
3411  $sql = "SELECT t.rowid";
3412  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t ';
3413 
3414  if ($entityfilter) {
3415  if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
3416  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
3417  $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
3418  } else {
3419  $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
3420  $sql .= " WHERE ((ug.fk_user = t.rowid";
3421  $sql .= " AND ug.entity IN (".getEntity('user')."))";
3422  $sql .= " OR t.entity = 0)"; // Show always superadmin
3423  }
3424  } else {
3425  $sql .= " WHERE t.entity IN (".getEntity('user').")";
3426  }
3427  } else {
3428  $sql .= " WHERE 1";
3429  }
3430 
3431  // Manage filter
3432  $sqlwhere = array();
3433  if (!empty($filter)) {
3434  foreach ($filter as $key => $value) {
3435  if ($key == 't.rowid') {
3436  $sqlwhere[] = $key.'='.$value;
3437  } elseif (strpos($key, 'date') !== false) {
3438  $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
3439  } elseif ($key == 'customsql') {
3440  $sqlwhere[] = $value;
3441  } else {
3442  $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
3443  }
3444  }
3445  }
3446  if (count($sqlwhere) > 0) {
3447  $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')';
3448  }
3449  $sql .= $this->db->order($sortfield, $sortorder);
3450  if ($limit) {
3451  $sql .= $this->db->plimit($limit + 1, $offset);
3452  }
3453 
3454  dol_syslog(__METHOD__, LOG_DEBUG);
3455 
3456  $resql = $this->db->query($sql);
3457  if ($resql) {
3458  $this->users = array();
3459  $num = $this->db->num_rows($resql);
3460  if ($num) {
3461  while ($obj = $this->db->fetch_object($resql)) {
3462  $line = new self($this->db);
3463  $result = $line->fetch($obj->rowid);
3464  if ($result > 0 && !empty($line->id)) {
3465  $this->users[$obj->rowid] = clone $line;
3466  }
3467  }
3468  $this->db->free($resql);
3469  }
3470  return $num;
3471  } else {
3472  $this->errors[] = $this->db->lasterror();
3473  return -1;
3474  }
3475  }
3476 
3484  private $findUserIdByEmailCache;
3485 
3496  public function findUserIdByEmail($email)
3497  {
3498  if ($this->findUserIdByEmailCache[$email]) {
3499  return $this->findUserIdByEmailCache[$email];
3500  }
3501 
3502  $this->findUserIdByEmailCache[$email] = -1;
3503 
3504  global $conf;
3505 
3506  $sql = 'SELECT rowid';
3507  $sql .= ' FROM '.MAIN_DB_PREFIX.'user';
3508 
3509  if (!empty($conf->global->AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR)) {
3510  $sql .= ' WHERE email LIKE "%'.$email.'%"';
3511  } else {
3512  $sql .= ' WHERE email = "'.$email.'"';
3513  }
3514 
3515  $sql .= ' LIMIT 1';
3516 
3517  $resql = $this->db->query($sql);
3518  if (!$resql) {
3519  return -1;
3520  }
3521 
3522  $obj = $this->db->fetch_object($resql);
3523  if (!$obj) {
3524  return -1;
3525  }
3526 
3527  $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
3528 
3529  return $this->findUserIdByEmailCache[$email];
3530  }
3531 }
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
loadParentOf()
Load this-&gt;parentof that is array(id_son=&gt;id_parent, ...)
user_get_property($rowid, $mode)
Return property of user from its id.
__construct($db)
Constructor of the class.
Definition: user.class.php:361
SetInGroup($group, $entity, $notrigger=0)
Add user into a group.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto= 'UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
_load_ldap_info()
Initialize the info array (array of LDAP values) that will be used to call LDAP functions.
dol_hash($chain, $type= '0')
Returns a hash of a string.
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
addrights($rid, $allmodule= '', $allperms= '', $entity=0, $notrigger=0)
Add a right to the user.
Definition: user.class.php:666
create($user, $notrigger=0)
Create a user into database.
getUserRemoteIP()
Return the IP of remote user.
update_ldap2dolibarr(&$ldapuser)
Update user using data from the LDAP.
if(!empty($arrayfields['u.datec']['checked'])) print_liste_field_titre("DateCreationShort"u if(!empty($arrayfields['u.tms']['checked'])) print_liste_field_titre("DateModificationShort"u if(!empty($arrayfields['u.statut']['checked'])) print_liste_field_titre("Status"u statut
Definition: list.php:632
create_from_contact($contact, $login= '', $password= '')
Create a user from a contact object.
fetchAll($sortorder= '', $sortfield= '', $limit=0, $offset=0, $filter=array(), $filtermode= 'AND', $entityfilter=false)
Load all objects into $this-&gt;users.
getLibStatut($mode=0)
Return the label of the status of user (active, inactive)
setPassword($user, $password= '', $changelater=0, $notrigger=0, $nosyncmember=0)
Change password of a user.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
update($user, $notrigger=0, $nosyncmember=0, $nosyncmemberpass=0, $nosynccontact=0)
Update a user into database (and also password if this-&gt;pass is defined)
conf($dolibarr_main_document_root)
Load conf file (file must exists)
Definition: inc.php:262
Class to manage contact/addresses.
getArrayOfSocialNetworks()
Get array of social network dictionary.
getAllChildIds($addcurrentuser=0)
Return list of all child users id in herarchy (all sublevels).
set_default_rights()
Assign rights by default.
dol_now($mode= 'auto')
Return date for now.
Class to manage Dolibarr users.
Definition: user.class.php:44
Class to manage Dolibarr database access.
update_clicktodial()
Update clicktodial info.
Class to manage user groups.
LibStatut($status, $mode=0)
Return the label of a status of user (active, inactive)
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+&#39; &#39;+name+&#39; &#39;+lastname)
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
get_children()
Return and array with all instanciated first level children users of current user.
findUserIdByEmail($email)
Find a user by the given e-mail and return it&#39;s user id when found.
fetch_clicktodial()
Read clicktodial information for user.
$conf db
API class for accounts.
Definition: inc.php:54
send_password($user, $password= '', $changelater=0)
Send new password by email.
$clicktodial_url
clicktodial url
Definition: user.class.php:259
info($id)
Load info of user object.
getPhotoUrl($width, $height, $cssclass= '', $imagesize= '')
Return a link with photo Use this-&gt;id,this-&gt;photo.
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
getNomUrl($withpictoimg=0, $option= '', $infologin=0, $notooltip=0, $maxlen=24, $hidethirdpartylogo=0, $mode= '', $morecss= '', $save_lastsearch_value=-1)
Return a link to the user card (with optionaly the picto) Use this-&gt;id,this-&gt;lastname, this-&gt;firstname.
load_state_board()
Load metrics this-&gt;nb for dashboard.
RemoveFromGroup($group, $entity, $notrigger=0)
Remove a user from a group.
Class to manage third parties objects (customers, suppliers, prospects...)
initAsSpecimen()
Initialise an instance with random values.
Class to manage categories.
setstatus($status)
Change status of a user.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
loadDefaultValues()
Load default value in property -&gt;default_values.
Definition: user.class.php:611
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext,$replyto); $mailfile-&gt;sendfile();.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
Class to manage members of a foundation.
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
deleteExtraFields()
Delete all extra fields values for the current object.
Class to manage translations.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this-&gt;array_options This method is in most cases call...
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass= 'photowithmargin', $imagesize= '', $addlinktofullsize=1, $cache=0, $forcecapture= '', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
_load_ldap_dn($info, $mode=0)
Retourne chaine DN complete dans l&#39;annuaire LDAP pour l&#39;objet.
print $_SERVER["PHP_SELF"]
Edit parameters.
setCategories($categories)
Sets object to supplied categories.
build_path_from_id_user($id_user, $protection=0)
For user id_user and its childs available in this-&gt;users, define property fullpath and fullname...
delrights($rid, $allmodule= '', $allperms= '', $entity=0, $notrigger=0)
Remove a right to the user.
Definition: user.class.php:794
dol_sort_array(&$array, $index, $order= 'asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by second index function, which produces ascending (default) or descending output...
clearrights()
Clear all permissions array of user.
Definition: user.class.php:921
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
getNbOfUsers($limitTo, $option= '', $admin=-1)
Return number of existing users.
call_trigger($triggerName, $user)
Call trigger based on this instance.
fetch($id= '', $login= '', $sid= '', $loadpersonalconf=0, $entity=-1, $email= '')
Load a user from database with its id or ref (login).
Definition: user.class.php:396
getrights($moduletag= '', $forcereload=0)
Load permissions granted to user into object user.
Definition: user.class.php:939
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;...&#39; if string larger than length.
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
get_full_tree($deleteafterid=0, $filter= '')
Build the hierarchy/tree of users into an array.
create_from_member($member, $login= '')
Create a user into database from a member object.
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
update_last_login_date()
Mise a jour en base de la date de derniere connexion d&#39;un utilisateur Fonction appelee lors d&#39;une nou...
picto_from_langcode($codelang, $moreatt= '')
Return img flag of country for a language code or country code.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
error()
Renvoie la derniere erreur fonctionnelle de manipulation de l&#39;objet.
if(!empty($search_group)) natural_search(array("g.nom"g note
Definition: list.php:122
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
getLoginUrl($withpicto=0, $option= '')
Return clickable link of login (eventualy with picto)
Class to manage warehouses.