dolibarr  18.0.0-beta
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-2021 Nicolas ZABOURI <info@inovea-conseil.com>
15  * Copyright (C) 2019-2023 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/lib/security.lib.php';
39 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
40 require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
42 
43 
47 class User extends CommonObject
48 {
49  use CommonPeople;
50 
54  public $element = 'user';
55 
59  public $table_element = 'user';
60 
64  public $fk_element = 'fk_user';
65 
70  public $ismultientitymanaged = 1;
71 
75  public $isextrafieldmanaged = 1;
76 
80  public $picto = 'user';
81 
82  public $id = 0;
83  public $statut;
84  public $ldap_sid;
85  public $search_sid;
86  public $employee;
87  public $civility_code;
88 
92  public $fullname;
93 
97  public $gender;
98 
99  public $birth;
100 
104  public $email;
105 
109  public $personal_email;
110 
114  public $socialnetworks;
115 
119  public $job;
120 
124  public $signature;
125 
129  public $address;
130 
134  public $zip;
135 
139  public $town;
140  public $state_id; // The state/department
141  public $state_code;
142  public $state;
143 
147  public $office_phone;
148 
152  public $office_fax;
153 
157  public $user_mobile;
158 
162  public $personal_mobile;
163 
167  public $admin;
168 
172  public $login;
173 
177  public $api_key;
178 
182  public $entity;
183 
187  public $pass;
188 
192  public $pass_indatabase;
193 
197  public $pass_indatabase_crypted;
198 
202  public $pass_temp;
203 
209  public $datec;
210 
216  public $datem;
217 
221  public $socid;
222 
226  public $contact_id;
227 
231  public $fk_member;
232 
236  public $fk_user;
237 
241  public $fk_user_expense_validator;
242 
246  public $fk_user_holiday_validator;
247 
252 
256  public $clicktodial_login;
257 
261  public $clicktodial_password;
262 
266  public $clicktodial_poste;
267 
271  public $clicktodial_loaded;
272 
273 
274  public $datelastlogin;
275  public $datepreviouslogin;
276  public $flagdelsessionsbefore;
277  public $iplastlogin;
278  public $ippreviouslogin;
279  public $datestartvalidity;
280  public $dateendvalidity;
281 
285  public $photo;
286  public $lang;
287 
291  public $rights;
292 
296  public $all_permissions_are_loaded;
297 
301  public $nb_rights;
302 
306  public $user_group_list;
307 
311  private $_tab_loaded = array();
312 
316  public $conf;
317 
318  public $default_values; // To store default values for user. Loaded by loadDefaultValues().
319 
320  public $lastsearch_values_tmp; // To store current search criterias for user
321  public $lastsearch_values; // To store last saved search criterias for user
322 
323  public $users = array(); // To store all tree of users hierarchy
324  public $parentof; // To store an array of all parents for all ids.
325  private $cache_childids; // Cache array of already loaded childs
326 
327  public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
328 
329  public $thm; // Average cost of employee - Used for valuation of time spent
330  public $tjm; // Average cost of employee
331 
332  public $salary; // Monthly salary - Denormalized value from llx_user_employment
333  public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment
334  public $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment
335 
339  public $color;
340 
341  public $dateemployment; // Define date of employment by company
342  public $dateemploymentend; // Define date of employment end by company
343 
344  public $default_c_exp_tax_cat;
345 
349  public $ref_employee;
350 
354  public $national_registration_number;
355 
356  public $default_range;
357 
361  public $fk_warehouse;
362 
363 
364  public $fields = array(
365  'rowid'=>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
366  'lastname'=>array('type'=>'varchar(50)', 'label'=>'LastName', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>20, 'searchall'=>1),
367  'firstname'=>array('type'=>'varchar(50)', 'label'=>'FirstName', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1),
368  'ref_employee'=>array('type'=>'varchar(50)', 'label'=>'RefEmployee', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>30, 'searchall'=>1),
369  'national_registration_number'=>array('type'=>'varchar(50)', 'label'=>'NationalRegistrationNumber', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>40, 'searchall'=>1)
370  );
371 
372 
373  const STATUS_DISABLED = 0;
374  const STATUS_ENABLED = 1;
375 
376 
377 
383  public function __construct($db)
384  {
385  $this->db = $db;
386 
387  // User preference
388  $this->liste_limit = 0;
389  $this->clicktodial_loaded = 0;
390 
391  // For cache usage
392  $this->all_permissions_are_loaded = 0;
393  $this->nb_rights = 0;
394 
395  // Force some default values
396  $this->admin = 0;
397  $this->employee = 1;
398 
399  $this->conf = new stdClass();
400  $this->rights = new stdClass();
401  $this->rights->user = new stdClass();
402  $this->rights->user->user = new stdClass();
403  $this->rights->user->self = new stdClass();
404  $this->rights->user->user_advance = new stdClass();
405  $this->rights->user->self_advance = new stdClass();
406  $this->rights->user->group_advance = new stdClass();
407  }
408 
422  public function fetch($id = '', $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1, $email = '', $fk_socpeople = 0)
423  {
424  global $conf, $user;
425 
426  // Clean parameters
427  $login = trim($login);
428 
429  // Get user
430  $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,";
431  $sql .= " u.socialnetworks,";
432  $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile, u.personal_mobile,";
433  $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
434  $sql .= " u.admin, u.login, u.note_private, u.note_public,";
435  $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.api_key,";
436  $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,";
437  $sql .= " u.statut as status, u.lang, u.entity,";
438  $sql .= " u.datec as datec,";
439  $sql .= " u.tms as datem,";
440  $sql .= " u.datelastlogin as datel,";
441  $sql .= " u.datepreviouslogin as datep,";
442  $sql .= " u.flagdelsessionsbefore,";
443  $sql .= " u.iplastlogin,";
444  $sql .= " u.ippreviouslogin,";
445  $sql .= " u.datelastpassvalidation,";
446  $sql .= " u.datestartvalidity,";
447  $sql .= " u.dateendvalidity,";
448  $sql .= " u.photo as photo,";
449  $sql .= " u.openid as openid,";
450  $sql .= " u.accountancy_code,";
451  $sql .= " u.thm,";
452  $sql .= " u.tjm,";
453  $sql .= " u.salary,";
454  $sql .= " u.salaryextra,";
455  $sql .= " u.weeklyhours,";
456  $sql .= " u.color,";
457  $sql .= " u.dateemployment, u.dateemploymentend,";
458  $sql .= " u.fk_warehouse,";
459  $sql .= " u.ref_ext,";
460  $sql .= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode
461  $sql .= " u.national_registration_number,";
462  $sql .= " u.ref_employee,";
463  $sql .= " c.code as country_code, c.label as country,";
464  $sql .= " d.code_departement as state_code, d.nom as state";
465  $sql .= " FROM ".$this->db->prefix()."user as u";
466  $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as c ON u.fk_country = c.rowid";
467  $sql .= " LEFT JOIN ".$this->db->prefix()."c_departements as d ON u.fk_state = d.rowid";
468 
469  if ($entity < 0) {
470  if ((!isModEnabled('multicompany') || empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) && (!empty($user->entity))) {
471  $sql .= " WHERE u.entity IN (0, ".((int) $conf->entity).")";
472  } else {
473  $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
474  }
475  } else {
476  // The fetch was forced on an entity
477  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
478  $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
479  } else {
480  $sql .= " WHERE u.entity IN (0, ".((int) (($entity != '' && $entity >= 0) ? $entity : $conf->entity)).")"; // search in entity provided in parameter
481  }
482  }
483 
484  if ($sid) {
485  // permet une recherche du user par son SID ActiveDirectory ou Samba
486  $sql .= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."')";
487  } elseif ($login) {
488  $sql .= " AND u.login = '".$this->db->escape($login)."'";
489  } elseif ($email) {
490  $sql .= " AND u.email = '".$this->db->escape($email)."'";
491  } elseif ($fk_socpeople > 0) {
492  $sql .= " AND u.fk_socpeople = ".((int) $fk_socpeople);
493  } else {
494  $sql .= " AND u.rowid = ".((int) $id);
495  }
496  $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
497 
498  if ($sid) {
499  // permet une recherche du user par son SID ActiveDirectory ou Samba
500  $sql .= ' '.$this->db->plimit(1);
501  }
502 
503  $result = $this->db->query($sql);
504  if ($result) {
505  $obj = $this->db->fetch_object($result);
506  if ($obj) {
507  $this->id = $obj->rowid;
508  $this->ref = $obj->rowid;
509 
510  $this->ref_ext = $obj->ref_ext;
511 
512  $this->ldap_sid = $obj->ldap_sid;
513  $this->civility_code = $obj->civility_code;
514  $this->lastname = $obj->lastname;
515  $this->firstname = $obj->firstname;
516  $this->ref_employee = $obj->ref_employee;
517  $this->national_registration_number = $obj->national_registration_number;
518 
519  $this->employee = $obj->employee;
520 
521  $this->login = $obj->login;
522  $this->gender = $obj->gender;
523  $this->birth = $this->db->jdate($obj->birth);
524  $this->pass_indatabase = $obj->pass;
525  $this->pass_indatabase_crypted = $obj->pass_crypted;
526  $this->pass = $obj->pass;
527  $this->pass_temp = $obj->pass_temp;
528  $this->api_key = dolDecrypt($obj->api_key);
529 
530  $this->address = $obj->address;
531  $this->zip = $obj->zip;
532  $this->town = $obj->town;
533 
534  $this->country_id = $obj->country_id;
535  $this->country_code = $obj->country_id ? $obj->country_code : '';
536  //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
537 
538  $this->state_id = $obj->state_id;
539  $this->state_code = $obj->state_code;
540  $this->state = ($obj->state != '-' ? $obj->state : '');
541 
542  $this->office_phone = $obj->office_phone;
543  $this->office_fax = $obj->office_fax;
544  $this->user_mobile = $obj->user_mobile;
545  $this->personal_mobile = $obj->personal_mobile;
546  $this->email = $obj->email;
547  $this->personal_email = $obj->personal_email;
548  $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
549  $this->job = $obj->job;
550  $this->signature = $obj->signature;
551  $this->admin = $obj->admin;
552  $this->note_public = $obj->note_public;
553  $this->note_private = $obj->note_private;
554  $this->note = $obj->note_private; // deprecated
555 
556  $this->statut = $obj->status; // deprecated
557  $this->status = $obj->status;
558 
559  $this->photo = $obj->photo;
560  $this->openid = $obj->openid;
561  $this->lang = $obj->lang;
562  $this->entity = $obj->entity;
563  $this->accountancy_code = $obj->accountancy_code;
564  $this->thm = $obj->thm;
565  $this->tjm = $obj->tjm;
566  $this->salary = $obj->salary;
567  $this->salaryextra = $obj->salaryextra;
568  $this->weeklyhours = $obj->weeklyhours;
569  $this->color = $obj->color;
570  $this->dateemployment = $this->db->jdate($obj->dateemployment);
571  $this->dateemploymentend = $this->db->jdate($obj->dateemploymentend);
572 
573  $this->datec = $this->db->jdate($obj->datec);
574  $this->datem = $this->db->jdate($obj->datem);
575  $this->datelastlogin = $this->db->jdate($obj->datel);
576  $this->datepreviouslogin = $this->db->jdate($obj->datep);
577  $this->flagdelsessionsbefore = $this->db->jdate($obj->flagdelsessionsbefore, 'gmt');
578  $this->iplastlogin = $obj->iplastlogin;
579  $this->ippreviouslogin = $obj->ippreviouslogin;
580  $this->datestartvalidity = $this->db->jdate($obj->datestartvalidity);
581  $this->dateendvalidity = $this->db->jdate($obj->dateendvalidity);
582 
583  $this->socid = $obj->fk_soc;
584  $this->contact_id = $obj->fk_socpeople;
585  $this->fk_member = $obj->fk_member;
586  $this->fk_user = $obj->fk_user;
587  $this->fk_user_expense_validator = $obj->fk_user_expense_validator;
588  $this->fk_user_holiday_validator = $obj->fk_user_holiday_validator;
589 
590  $this->default_range = $obj->default_range;
591  $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
592  $this->fk_warehouse = $obj->fk_warehouse;
593 
594  // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
595  // in such case, this admin user must be admin for ALL entities.
596  if (!isModEnabled('multicompany') && $this->admin && $this->entity == 1) {
597  $this->entity = 0;
598  }
599 
600  // Retrieve all extrafield
601  // fetch optionals attributes and labels
602  $this->fetch_optionals();
603 
604  $this->db->free($result);
605  } else {
606  $this->error = "USERNOTFOUND";
607  dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
608 
609  $this->db->free($result);
610  return 0;
611  }
612  } else {
613  $this->error = $this->db->lasterror();
614  return -1;
615  }
616 
617  // To get back the global configuration unique to the user
618  if ($loadpersonalconf) {
619  // Load user->conf for user
620  $sql = "SELECT param, value FROM ".$this->db->prefix()."user_param";
621  $sql .= " WHERE fk_user = ".((int) $this->id);
622  $sql .= " AND entity = ".((int) $conf->entity);
623  //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
624  $resql = $this->db->query($sql);
625  if ($resql) {
626  $num = $this->db->num_rows($resql);
627  $i = 0;
628  while ($i < $num) {
629  $obj = $this->db->fetch_object($resql);
630  $p = (!empty($obj->param) ? $obj->param : '');
631  if (!empty($p)) {
632  $this->conf->$p = $obj->value;
633  }
634  $i++;
635  }
636  $this->db->free($resql);
637  } else {
638  $this->error = $this->db->lasterror();
639  return -2;
640  }
641 
642  $result = $this->loadDefaultValues();
643 
644  if ($result < 0) {
645  $this->error = $this->db->lasterror();
646  return -3;
647  }
648  }
649 
650  return 1;
651  }
652 
658  public function loadDefaultValues()
659  {
660  global $conf;
661  if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
662  // Load user->default_values for user. TODO Save this in memcached ?
663  require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php';
664 
665  $defaultValues = new DefaultValues($this->db);
666  $result = $defaultValues->fetchAll('', '', 0, 0, array('t.user_id'=>array(0, $this->id), 'entity'=>array((isset($this->entity) ? $this->entity : $conf->entity), $conf->entity))); // User 0 (all) + me (if defined)
667 
668  if (!is_array($result) && $result < 0) {
669  setEventMessages($defaultValues->error, $defaultValues->errors, 'errors');
670  dol_print_error($this->db);
671  return -1;
672  } elseif (count($result) > 0) {
673  foreach ($result as $defval) {
674  if (!empty($defval->page) && !empty($defval->type) && !empty($defval->param)) {
675  $pagewithoutquerystring = $defval->page;
676  $pagequeries = '';
677  $reg = array();
678  if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
679  $pagewithoutquerystring = $reg[1];
680  $pagequeries = $reg[2];
681  }
682  $this->default_values[$pagewithoutquerystring][$defval->type][$pagequeries ? $pagequeries : '_noquery_'][$defval->param] = $defval->value;
683  }
684  }
685  }
686  if (!empty($this->default_values)) {
687  foreach ($this->default_values as $a => $b) {
688  foreach ($b as $c => $d) {
689  krsort($this->default_values[$a][$c]);
690  }
691  }
692  }
693  }
694  return 1;
695  }
696 
708  public function hasRight($module, $permlevel1, $permlevel2 = '')
709  {
710  global $conf;
711  // For compatibility with bad naming permissions on module
712  $moduletomoduletouse = array(
713  'compta' => 'comptabilite',
714  'contract' => 'contrat',
715  'member' => 'adherent',
716  'mo' => 'mrp',
717  'order' => 'commande',
718  'produit' => 'product',
719  'project' => 'projet',
720  'propale' => 'propal',
721  'shipping' => 'expedition',
722  'task' => 'task@projet',
723  'fichinter' => 'ficheinter',
724  'inventory' => 'stock',
725  'invoice' => 'facture',
726  'invoice_supplier' => 'fournisseur',
727  'order_supplier' => 'fournisseur',
728  'knowledgerecord' => 'knowledgerecord@knowledgemanagement',
729  'skill@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
730  'job@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
731  'position@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
732  'facturerec' => 'facture',
733  'margins' => 'margin',
734  );
735 
736  if (!empty($moduletomoduletouse[$module])) {
737  $module = $moduletomoduletouse[$module];
738  }
739 
740  $moduleRightsMapping = array(
741  'product' => 'produit', // We must check $user->rights->produit...
742  'margin' => 'margins',
743  'comptabilite' => 'compta'
744  );
745 
746  $rightsPath = $module;
747  if (!empty($moduleRightsMapping[$rightsPath])) {
748  $rightsPath = $moduleRightsMapping[$rightsPath];
749  }
750 
751  // If module is abc@module, we check permission user->rights->module->abc->permlevel1
752  $tmp = explode('@', $rightsPath, 2);
753  if (!empty($tmp[1])) {
754  if (strpos($module, '@') !== false) {
755  $module = $tmp[1];
756  }
757  $rightsPath = $tmp[1];
758  $permlevel2 = $permlevel1;
759  $permlevel1 = $tmp[0];
760  }
761 
762  // In $conf->modules, we have 'accounting', 'product', 'facture', ...
763  // In $user->rights, we have 'accounting', 'produit', 'facture', ...
764  //var_dump($module);
765  //var_dump($rightsPath);
766  //var_dump($this->rights->$rightsPath);
767  //var_dump($conf->modules);
768  //var_dump($module.' '.isModEnabled($module).' '.$rightsPath.' '.$permlevel1.' '.$permlevel2);
769  if (!isModEnabled($module)) {
770  return 0;
771  }
772 
773  // For compatibility with bad naming permissions on permlevel1
774  if ($permlevel1 == 'propale') {
775  $permlevel1 = 'propal';
776  }
777  if ($permlevel1 == 'member') {
778  $permlevel1 = 'adherent';
779  }
780  if ($permlevel1 == 'recruitmentcandidature') {
781  $permlevel1 = 'recruitmentjobposition';
782  }
783 
784  //var_dump($this->rights);
785  //var_dump($rightsPath.' '.$permlevel1.' '.$permlevel2);
786  if (empty($rightsPath) || empty($this->rights) || empty($this->rights->$rightsPath) || empty($permlevel1)) {
787  return 0;
788  }
789 
790  if ($permlevel2) {
791  if (!empty($this->rights->$rightsPath->$permlevel1)) {
792  if (!empty($this->rights->$rightsPath->$permlevel1->$permlevel2)) {
793  return $this->rights->$rightsPath->$permlevel1->$permlevel2;
794  }
795  // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
796  // instead of "read", "write", "delete"
797  if ($permlevel2 == 'read' && !empty($this->rights->$rightsPath->$permlevel1->lire)) {
798  return $this->rights->$rightsPath->$permlevel1->lire;
799  }
800  if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->creer)) {
801  return $this->rights->$rightsPath->$permlevel1->creer;
802  }
803  if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->create)) {
804  return $this->rights->$rightsPath->$permlevel1->create;
805  }
806  if ($permlevel2 == 'delete' && !empty($this->rights->$rightsPath->$permlevel1->supprimer)) {
807  return $this->rights->$rightsPath->$permlevel1->supprimer;
808  }
809  }
810  } else {
811  if (!empty($this->rights->$rightsPath->$permlevel1)) {
812  return $this->rights->$rightsPath->$permlevel1;
813  }
814  // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
815  // instead of "read", "write", "delete"
816  if ($permlevel1 == 'read' && !empty($this->rights->$rightsPath->lire)) {
817  return $this->rights->$rightsPath->lire;
818  }
819  if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->creer)) {
820  return $this->rights->$rightsPath->creer;
821  }
822  if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->create)) {
823  return $this->rights->$rightsPath->create;
824  }
825  if ($permlevel1 == 'delete' && !empty($this->rights->$rightsPath->supprimer)) {
826  return $this->rights->$rightsPath->supprimer;
827  }
828  }
829 
830  return 0;
831  }
832 
844  public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
845  {
846  global $conf, $user, $langs;
847 
848  $entity = (empty($entity) ? $conf->entity : $entity);
849 
850  dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity, $notrigger for user id=".$this->id);
851 
852  if (empty($this->id)) {
853  $error++;
854  $this->error = 'Try to call addrights on an object user with an empty id';
855  return -1;
856  }
857 
858  $error = 0;
859  $whereforadd = '';
860 
861  $this->db->begin();
862 
863  if (!empty($rid)) {
864  $module = $perms = $subperms = '';
865 
866  // If we ask to add a given permission, we first load properties of this permission (module, perms and subperms).
867  $sql = "SELECT module, perms, subperms";
868  $sql .= " FROM ".$this->db->prefix()."rights_def";
869  $sql .= " WHERE id = ".((int) $rid);
870  $sql .= " AND entity = ".((int) $entity);
871 
872  $result = $this->db->query($sql);
873  if ($result) {
874  $obj = $this->db->fetch_object($result);
875 
876  if ($obj) {
877  $module = $obj->module;
878  $perms = $obj->perms;
879  $subperms = $obj->subperms;
880  }
881  } else {
882  $error++;
883  dol_print_error($this->db);
884  }
885 
886  // Define the where for the permission to add
887  $whereforadd = "id=".((int) $rid);
888  // Add also inherited permissions
889  if (!empty($subperms)) {
890  $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))";
891  } elseif (!empty($perms)) {
892  $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND subperms IS NULL)";
893  }
894  } else {
895  // On a pas demande un droit en particulier mais une liste de droits
896  // sur la base d'un nom de module de de perms
897  // Where pour la liste des droits a ajouter
898  if (!empty($allmodule)) {
899  if ($allmodule == 'allmodules') {
900  $whereforadd = 'allmodules';
901  } else {
902  $whereforadd = "module='".$this->db->escape($allmodule)."'";
903  if (!empty($allperms)) {
904  $whereforadd .= " AND perms='".$this->db->escape($allperms)."'";
905  }
906  }
907  }
908  }
909 
910  // Add automatically other permission using the criteria whereforadd
911  // $whereforadd can be a SQL filter or the string 'allmodules'
912  if (!empty($whereforadd)) {
913  //print "$module-$perms-$subperms";
914  $sql = "SELECT id";
915  $sql .= " FROM ".$this->db->prefix()."rights_def";
916  $sql .= " WHERE entity = ".((int) $entity);
917  if (!empty($whereforadd) && $whereforadd != 'allmodules') {
918  $sql .= " AND (".$whereforadd.")"; // Note: parenthesis are important because whereforadd can contains OR. Also note that $whereforadd is already sanitized
919  }
920 
921  $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
922  $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
923  $sqldelete .= $sql;
924  $sqldelete .= ") AND entity = ".((int) $entity);
925  if (!$this->db->query($sqldelete)) {
926  $error++;
927  }
928 
929  if (!$error) {
930  $resql = $this->db->query($sql);
931  if ($resql) {
932  $num = $this->db->num_rows($resql);
933  $i = 0;
934  while ($i < $num) {
935  $obj = $this->db->fetch_object($resql);
936 
937  if ($obj) {
938  $nid = $obj->id;
939 
940  $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id) VALUES (".((int) $entity).", ".((int) $this->id).", ".((int) $nid).")";
941  if (!$this->db->query($sql)) {
942  $error++;
943  }
944  }
945 
946  $i++;
947  }
948  } else {
949  $error++;
950  dol_print_error($this->db);
951  }
952  }
953  }
954 
955  if (!$error && !$notrigger) {
956  $langs->load("other");
957  $this->context = array('audit'=>$langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : ''));
958 
959  // Call trigger
960  $result = $this->call_trigger('USER_MODIFY', $user);
961  if ($result < 0) {
962  $error++;
963  }
964  // End call triggers
965  }
966 
967  if ($error) {
968  $this->db->rollback();
969  return -$error;
970  } else {
971  $this->db->commit();
972  return 1;
973  }
974  }
975 
976 
988  public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
989  {
990  global $conf, $user, $langs;
991 
992  $error = 0;
993  $wherefordel = '';
994  $entity = (!empty($entity) ? $entity : $conf->entity);
995 
996  $this->db->begin();
997 
998  if (!empty($rid)) {
999  $module = $perms = $subperms = '';
1000 
1001  // Si on a demande supression d'un droit en particulier, on recupere
1002  // les caracteristiques module, perms et subperms de ce droit.
1003  $sql = "SELECT module, perms, subperms";
1004  $sql .= " FROM ".$this->db->prefix()."rights_def";
1005  $sql .= " WHERE id = '".$this->db->escape($rid)."'";
1006  $sql .= " AND entity = ".((int) $entity);
1007 
1008  $result = $this->db->query($sql);
1009  if ($result) {
1010  $obj = $this->db->fetch_object($result);
1011 
1012  if ($obj) {
1013  $module = $obj->module;
1014  $perms = $obj->perms;
1015  $subperms = $obj->subperms;
1016  }
1017  } else {
1018  $error++;
1019  dol_print_error($this->db);
1020  }
1021 
1022  // Where pour la liste des droits a supprimer
1023  $wherefordel = "id=".((int) $rid);
1024  // Suppression des droits induits
1025  if ($subperms == 'lire' || $subperms == 'read') {
1026  $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)";
1027  }
1028  if ($perms == 'lire' || $perms == 'read') {
1029  $wherefordel .= " OR (module='".$this->db->escape($module)."')";
1030  }
1031  } else {
1032  // On a demande suppression d'un droit sur la base d'un nom de module ou perms
1033  // Where pour la liste des droits a supprimer
1034  if (!empty($allmodule)) {
1035  if ($allmodule == 'allmodules') {
1036  $wherefordel = 'allmodules';
1037  } else {
1038  $wherefordel = "module='".$this->db->escape($allmodule)."'";
1039  if (!empty($allperms)) {
1040  $wherefordel .= " AND perms='".$this->db->escape($allperms)."'";
1041  }
1042  }
1043  }
1044  }
1045 
1046  // Suppression des droits selon critere defini dans wherefordel
1047  if (!empty($wherefordel)) {
1048  //print "$module-$perms-$subperms";
1049  $sql = "SELECT id";
1050  $sql .= " FROM ".$this->db->prefix()."rights_def";
1051  $sql .= " WHERE entity = ".((int) $entity);
1052  if (!empty($wherefordel) && $wherefordel != 'allmodules') {
1053  $sql .= " AND (".$wherefordel.")"; // Note: parenthesis are important because wherefordel can contains OR. Also note that $wherefordel is already sanitized
1054  }
1055 
1056  // avoid admin can remove his own important rights
1057  if ($this->admin == 1) {
1058  $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
1059  $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
1060  $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
1061  $sql .= " AND id NOT IN (358)"; // user export
1062  }
1063 
1064  $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1065  $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1066  $sqldelete .= $sql;
1067  $sqldelete .= ")";
1068  $sqldelete .= " AND entity = ".((int) $entity);
1069 
1070  $resql = $this->db->query($sqldelete);
1071  if (!$resql) {
1072  $error++;
1073  dol_print_error($this->db);
1074  }
1075  }
1076 
1077  if (!$error && !$notrigger) {
1078  $langs->load("other");
1079  $this->context = array('audit'=>$langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : ''));
1080 
1081  // Call trigger
1082  $result = $this->call_trigger('USER_MODIFY', $user);
1083  if ($result < 0) {
1084  $error++;
1085  }
1086  // End call triggers
1087  }
1088 
1089  if ($error) {
1090  $this->db->rollback();
1091  return -$error;
1092  } else {
1093  $this->db->commit();
1094  return 1;
1095  }
1096  }
1097 
1098 
1105  public function clearrights()
1106  {
1107  dol_syslog(get_class($this)."::clearrights reset user->rights");
1108  $this->rights = null;
1109  $this->nb_rights = 0;
1110  $this->all_permissions_are_loaded = 0;
1111  $this->_tab_loaded = array();
1112  }
1113 
1114 
1123  public function getrights($moduletag = '', $forcereload = 0)
1124  {
1125  global $conf;
1126 
1127  if (empty($forcereload)) {
1128  if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
1129  // Rights for this module are already loaded, so we leave
1130  return;
1131  }
1132 
1133  if (!empty($this->all_permissions_are_loaded)) {
1134  // We already loaded all rights for this user, so we leave
1135  return;
1136  }
1137  }
1138 
1139  // For avoid error
1140  if (!isset($this->rights) || !is_object($this->rights)) {
1141  $this->rights = new stdClass(); // For avoid error
1142  }
1143  if (!isset($this->rights->user) || !is_object($this->rights->user)) {
1144  $this->rights->user = new stdClass(); // For avoid error
1145  }
1146 
1147  // Get permission of users + Get permissions of groups
1148 
1149  // First user permissions
1150  $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1151  $sql .= " FROM ".$this->db->prefix()."user_rights as ur,";
1152  $sql .= " ".$this->db->prefix()."rights_def as r";
1153  $sql .= " WHERE r.id = ur.fk_id";
1154  if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
1155  // on old version, we use entity defined into table r only
1156  $sql .= " AND r.entity IN (0,".(isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) ? "1," : "").$conf->entity.")";
1157  } else {
1158  // On table r=rights_def, the unique key is (id, entity) because id is hard coded into module descriptor and insert during module activation.
1159  // So we must include the filter on entity on both table r. and ur.
1160  $sql .= " AND r.entity = ".((int) $conf->entity)." AND ur.entity = ".((int) $conf->entity);
1161  }
1162  $sql .= " AND ur.fk_user= ".((int) $this->id);
1163  $sql .= " AND r.perms IS NOT NULL";
1164  if ($moduletag) {
1165  $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1166  }
1167 
1168  $resql = $this->db->query($sql);
1169  if ($resql) {
1170  $num = $this->db->num_rows($resql);
1171  $i = 0;
1172  while ($i < $num) {
1173  $obj = $this->db->fetch_object($resql);
1174 
1175  if ($obj) {
1176  $module = $obj->module;
1177  $perms = $obj->perms;
1178  $subperms = $obj->subperms;
1179 
1180  if (!empty($perms)) {
1181  if (!empty($module)) {
1182  if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1183  $this->rights->$module = new stdClass();
1184  }
1185  if (!empty($subperms)) {
1186  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1187  $this->rights->$module->$perms = new stdClass();
1188  }
1189  if (empty($this->rights->$module->$perms->$subperms)) {
1190  $this->nb_rights++;
1191  }
1192  $this->rights->$module->$perms->$subperms = 1;
1193  } else {
1194  if (empty($this->rights->$module->$perms)) {
1195  $this->nb_rights++;
1196  }
1197  $this->rights->$module->$perms = 1;
1198  }
1199  }
1200  }
1201  }
1202  $i++;
1203  }
1204  $this->db->free($resql);
1205  }
1206 
1207  // Now permissions of groups
1208  $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1209  $sql .= " FROM ".$this->db->prefix()."usergroup_rights as gr,";
1210  $sql .= " ".$this->db->prefix()."usergroup_user as gu,";
1211  $sql .= " ".$this->db->prefix()."rights_def as r";
1212  $sql .= " WHERE r.id = gr.fk_id";
1213  // A very strange business rules. Must be same than into user->getrights() user/perms.php and user/group/perms.php
1214  if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
1215  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1216  $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1217  } else {
1218  $sql .= " AND r.entity = ".((int) $conf->entity);
1219  }
1220  } else {
1221  $sql .= " AND gr.entity = ".((int) $conf->entity); // Only groups created in current entity
1222  // The entity on the table usergroup_user should be useless and should never be used because it is alreay into gr and r.
1223  // but when using MULTICOMPANY_TRANSVERSE_MODE, we may insert record that make rubbish result due to duplicate record of
1224  // other entities, so we are forced to add a filter here
1225  $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1226  $sql .= " AND r.entity = ".((int) $conf->entity); // Only permission of modules enabled in current entity
1227  }
1228  // End of strange business rule
1229  $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
1230  $sql .= " AND gu.fk_user = ".((int) $this->id);
1231  $sql .= " AND r.perms IS NOT NULL";
1232  if ($moduletag) {
1233  $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1234  }
1235 
1236  $resql = $this->db->query($sql);
1237  if ($resql) {
1238  $num = $this->db->num_rows($resql);
1239  $i = 0;
1240  while ($i < $num) {
1241  $obj = $this->db->fetch_object($resql);
1242 
1243  if ($obj) {
1244  $module = $obj->module;
1245  $perms = $obj->perms;
1246  $subperms = $obj->subperms;
1247 
1248  if (!empty($perms)) {
1249  if (!empty($module)) {
1250  if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1251  $this->rights->$module = new stdClass();
1252  }
1253  if (!empty($subperms)) {
1254  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1255  $this->rights->$module->$perms = new stdClass();
1256  }
1257  if (empty($this->rights->$module->$perms->$subperms)) {
1258  $this->nb_rights++;
1259  }
1260  $this->rights->$module->$perms->$subperms = 1;
1261  } else {
1262  if (empty($this->rights->$module->$perms)) {
1263  $this->nb_rights++;
1264  }
1265  // 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
1266  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1267  $this->rights->$module->$perms = 1;
1268  }
1269  }
1270  }
1271  }
1272  }
1273  $i++;
1274  }
1275  $this->db->free($resql);
1276  }
1277 
1278  // Force permission on user for admin
1279  if (!empty($this->admin)) {
1280  if (empty($this->rights->user->user)) {
1281  $this->rights->user->user = new stdClass();
1282  }
1283  $listofpermtotest = array('lire', 'creer', 'password', 'supprimer', 'export');
1284  foreach ($listofpermtotest as $permtotest) {
1285  if (empty($this->rights->user->user->$permtotest)) {
1286  $this->rights->user->user->$permtotest = 1;
1287  $this->nb_rights++;
1288  }
1289  }
1290  if (empty($this->rights->user->self)) {
1291  $this->rights->user->self = new stdClass();
1292  }
1293  $listofpermtotest = array('creer', 'password');
1294  foreach ($listofpermtotest as $permtotest) {
1295  if (empty($this->rights->user->self->$permtotest)) {
1296  $this->rights->user->self->$permtotest = 1;
1297  $this->nb_rights++;
1298  }
1299  }
1300  // Add test on advanced permissions
1301  if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
1302  if (empty($this->rights->user->user_advance)) {
1303  $this->rights->user->user_advance = new stdClass();
1304  }
1305  $listofpermtotest = array('readperms', 'write');
1306  foreach ($listofpermtotest as $permtotest) {
1307  if (empty($this->rights->user->user_advance->$permtotest)) {
1308  $this->rights->user->user_advance->$permtotest = 1;
1309  $this->nb_rights++;
1310  }
1311  }
1312  if (empty($this->rights->user->self_advance)) {
1313  $this->rights->user->self_advance = new stdClass();
1314  }
1315  $listofpermtotest = array('readperms', 'writeperms');
1316  foreach ($listofpermtotest as $permtotest) {
1317  if (empty($this->rights->user->self_advance->$permtotest)) {
1318  $this->rights->user->self_advance->$permtotest = 1;
1319  $this->nb_rights++;
1320  }
1321  }
1322  if (empty($this->rights->user->group_advance)) {
1323  $this->rights->user->group_advance = new stdClass();
1324  }
1325  $listofpermtotest = array('read', 'readperms', 'write', 'delete');
1326  foreach ($listofpermtotest as $permtotest) {
1327  if (empty($this->rights->user) || empty($this->rights->user->group_advance->$permtotest)) {
1328  $this->rights->user->group_advance->$permtotest = 1;
1329  $this->nb_rights++;
1330  }
1331  }
1332  }
1333  }
1334 
1335  // For backward compatibility
1336  if (isset($this->rights->propale) && !isset($this->rights->propal)) {
1337  $this->rights->propal = $this->rights->propale;
1338  }
1339  if (isset($this->rights->propal) && !isset($this->rights->propale)) {
1340  $this->rights->propale = $this->rights->propal;
1341  }
1342 
1343  if (!$moduletag) {
1344  // Si module etait non defini, alors on a tout charge, on peut donc considerer
1345  // que les droits sont en cache (car tous charges) pour cet instance de user
1346  $this->all_permissions_are_loaded = 1;
1347  } else {
1348  // If module defined, we flag it as loaded into cache
1349  $this->_tab_loaded[$moduletag] = 1;
1350  }
1351  }
1352 
1359  public function setstatus($status)
1360  {
1361  global $conf, $langs, $user;
1362 
1363  $error = 0;
1364 
1365  // Check parameters
1366  if (isset($this->statut)) {
1367  if ($this->statut == $status) {
1368  return 0;
1369  }
1370  } elseif (isset($this->status) && $this->status == $status) {
1371  return 0;
1372  }
1373 
1374  $this->db->begin();
1375 
1376  // Save in database
1377  $sql = "UPDATE ".$this->db->prefix()."user";
1378  $sql .= " SET statut = ".((int) $status);
1379  $sql .= " WHERE rowid = ".((int) $this->id);
1380  $result = $this->db->query($sql);
1381 
1382  dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1383  if ($result) {
1384  // Call trigger
1385  $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
1386  if ($result < 0) {
1387  $error++;
1388  }
1389  // End call triggers
1390  }
1391 
1392  if ($error) {
1393  $this->db->rollback();
1394  return -$error;
1395  } else {
1396  $this->status = $status;
1397  $this->statut = $status;
1398  $this->db->commit();
1399  return 1;
1400  }
1401  }
1402 
1413  public function setCategories($categories)
1414  {
1415  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1416  return parent::setCategoriesCommon($categories, Categorie::TYPE_USER);
1417  }
1418 
1425  public function delete(User $user)
1426  {
1427  global $conf, $langs;
1428 
1429  $error = 0;
1430 
1431  $this->db->begin();
1432 
1433  $this->fetch($this->id);
1434 
1435  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1436 
1437  // Remove rights
1438  $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1439 
1440  if (!$error && !$this->db->query($sql)) {
1441  $error++;
1442  $this->error = $this->db->lasterror();
1443  }
1444 
1445  // Remove group
1446  $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1447  if (!$error && !$this->db->query($sql)) {
1448  $error++;
1449  $this->error = $this->db->lasterror();
1450  }
1451 
1452  // Remove params
1453  $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1454  if (!$error && !$this->db->query($sql)) {
1455  $error++;
1456  $this->error = $this->db->lasterror();
1457  }
1458 
1459  // If contact, remove link
1460  if ($this->contact_id > 0) {
1461  $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1462  if (!$error && !$this->db->query($sql)) {
1463  $error++;
1464  $this->error = $this->db->lasterror();
1465  }
1466  }
1467 
1468  // Remove extrafields
1469  if (!$error) {
1470  $result = $this->deleteExtraFields();
1471  if ($result < 0) {
1472  $error++;
1473  dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1474  }
1475  }
1476 
1477  // Remove user
1478  if (!$error) {
1479  $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1480  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1481  if (!$this->db->query($sql)) {
1482  $error++;
1483  $this->error = $this->db->lasterror();
1484  }
1485  }
1486 
1487  if (!$error) {
1488  // Call trigger
1489  $result = $this->call_trigger('USER_DELETE', $user);
1490  if ($result < 0) {
1491  $error++;
1492  $this->db->rollback();
1493  return -1;
1494  }
1495  // End call triggers
1496 
1497  $this->db->commit();
1498  return 1;
1499  } else {
1500  $this->db->rollback();
1501  return -1;
1502  }
1503  }
1504 
1512  public function create($user, $notrigger = 0)
1513  {
1514  global $conf, $langs;
1515  global $mysoc;
1516 
1517  // Clean parameters
1518  $this->setUpperOrLowerCase();
1519 
1520  $this->civility_code = trim((string) $this->civility_code);
1521  $this->login = trim((string) $this->login);
1522  if (!isset($this->entity)) {
1523  $this->entity = $conf->entity; // If not defined, we use default value
1524  }
1525 
1526  dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1527 
1528  $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1529 
1530  // Check parameters
1531  if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
1532  $langs->load("errors");
1533  $this->error = $langs->trans("ErrorBadEMail", $this->email);
1534  return -1;
1535  }
1536  if (empty($this->login)) {
1537  $langs->load("errors");
1538  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1539  return -1;
1540  } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1541  $langs->load("errors");
1542  $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1543  return -1;
1544  }
1545 
1546  $this->datec = dol_now();
1547 
1548  $error = 0;
1549  $this->db->begin();
1550 
1551  // Check if login already exists in same entity or into entity 0.
1552  if ($this->login) {
1553  $sqltochecklogin = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."user WHERE entity IN (".$this->db->sanitize((int) $this->entity).", 0) AND login = '".$this->db->escape($this->login)."'";
1554  $resqltochecklogin = $this->db->query($sqltochecklogin);
1555  if ($resqltochecklogin) {
1556  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1557  if ($objtochecklogin && $objtochecklogin->nb > 0) {
1558  $langs->load("errors");
1559  $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1560  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1561  $this->db->rollback();
1562  return -6;
1563  }
1564  $this->db->free($resqltochecklogin);
1565  }
1566  }
1567  if (!empty($this->email)) {
1568  $sqltochecklogin = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."user WHERE entity IN (".$this->db->sanitize((int) $this->entity).", 0) AND email = '".$this->db->escape($this->email)."'";
1569  $resqltochecklogin = $this->db->query($sqltochecklogin);
1570  if ($resqltochecklogin) {
1571  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1572  if ($objtochecklogin && $objtochecklogin->nb > 0) {
1573  $langs->load("errors");
1574  $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1575  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1576  $this->db->rollback();
1577  return -6;
1578  }
1579  $this->db->free($resqltochecklogin);
1580  }
1581  }
1582 
1583  // Insert into database
1584  $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, entity)";
1585  $sql .= " VALUES('".$this->db->idate($this->datec)."', '".$this->db->escape($this->login)."', '".$this->db->escape($this->ldap_sid)."', ".((int) $this->entity).")";
1586  $result = $this->db->query($sql);
1587 
1588  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1589  if ($result) {
1590  $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1591 
1592  // Set default rights
1593  if ($this->set_default_rights() < 0) {
1594  $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1595  $this->db->rollback();
1596  return -5;
1597  }
1598 
1599  if (!empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER) && !empty($conf->global->STOCK_USERSTOCK_AUTOCREATE)) {
1600  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1601  $langs->load("stocks");
1602  $entrepot = new Entrepot($this->db);
1603  $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1604  $entrepot->libelle = $entrepot->label; // For backward compatibility
1605  $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1606  $entrepot->statut = 1;
1607  $entrepot->country_id = $mysoc->country_id;
1608  $warehouseid = $entrepot->create($user);
1609 
1610  $this->fk_warehouse = $warehouseid;
1611  }
1612 
1613  // Update minor fields
1614  $result = $this->update($user, 1, 1);
1615  if ($result < 0) {
1616  $this->db->rollback();
1617  return -4;
1618  }
1619 
1620  if (!$notrigger) {
1621  // Call trigger
1622  $result = $this->call_trigger('USER_CREATE', $user);
1623  if ($result < 0) {
1624  $error++;
1625  }
1626  // End call triggers
1627  }
1628 
1629  if (!$error) {
1630  $this->db->commit();
1631  return $this->id;
1632  } else {
1633  //$this->error=$interface->error;
1634  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1635  $this->db->rollback();
1636  return -3;
1637  }
1638  } else {
1639  $this->error = $this->db->lasterror();
1640  $this->db->rollback();
1641  return -2;
1642  }
1643  }
1644 
1645 
1646  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1655  public function create_from_contact($contact, $login = '', $password = '')
1656  {
1657  // phpcs:enable
1658  global $conf, $user, $langs;
1659 
1660  $error = 0;
1661 
1662  // Define parameters
1663  $this->admin = 0;
1664  $this->civility_code = $contact->civility_code;
1665  $this->lastname = $contact->lastname;
1666  $this->firstname = $contact->firstname;
1667  $this->gender = $contact->gender;
1668  $this->email = $contact->email;
1669  $this->socialnetworks = $contact->socialnetworks;
1670  $this->office_phone = $contact->phone_pro;
1671  $this->office_fax = $contact->fax;
1672  $this->user_mobile = $contact->phone_mobile;
1673  $this->address = $contact->address;
1674  $this->zip = $contact->zip;
1675  $this->town = $contact->town;
1676  $this->setUpperOrLowerCase();
1677  $this->state_id = $contact->state_id;
1678  $this->country_id = $contact->country_id;
1679  $this->employee = 0;
1680 
1681  if (empty($login)) {
1682  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1683  $login = dol_buildlogin($contact->lastname, $contact->firstname);
1684  }
1685  $this->login = $login;
1686 
1687  $this->db->begin();
1688 
1689  // Create user and set $this->id. Trigger is disabled because executed later.
1690  $result = $this->create($user, 1);
1691  if ($result > 0) {
1692  $sql = "UPDATE ".$this->db->prefix()."user";
1693  $sql .= " SET fk_socpeople=".((int) $contact->id);
1694  $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
1695  if ($contact->socid > 0) {
1696  $sql .= ", fk_soc=".((int) $contact->socid);
1697  }
1698  $sql .= " WHERE rowid=".((int) $this->id);
1699 
1700  $resql = $this->db->query($sql);
1701 
1702  dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1703  if ($resql) {
1704  $this->context['createfromcontact'] = 'createfromcontact';
1705 
1706  // Call trigger
1707  $result = $this->call_trigger('USER_CREATE', $user);
1708  if ($result < 0) {
1709  $error++; $this->db->rollback(); return -1;
1710  }
1711  // End call triggers
1712 
1713  $this->db->commit();
1714  return $this->id;
1715  } else {
1716  $this->error = $this->db->error();
1717 
1718  $this->db->rollback();
1719  return -1;
1720  }
1721  } else {
1722  // $this->error deja positionne
1723  dol_syslog(get_class($this)."::create_from_contact - 0");
1724 
1725  $this->db->rollback();
1726  return $result;
1727  }
1728  }
1729 
1730  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1739  public function create_from_member($member, $login = '')
1740  {
1741  // phpcs:enable
1742  global $conf, $user, $langs;
1743 
1744  // Set properties on new user
1745  $this->admin = 0;
1746  $this->civility_code = $member->civility_id;
1747  $this->lastname = $member->lastname;
1748  $this->firstname = $member->firstname;
1749  $this->gender = $member->gender;
1750  $this->email = $member->email;
1751  $this->fk_member = $member->id;
1752  $this->address = $member->address;
1753  $this->zip = $member->zip;
1754  $this->town = $member->town;
1755  $this->setUpperOrLowerCase();
1756  $this->state_id = $member->state_id;
1757  $this->country_id = $member->country_id;
1758  $this->socialnetworks = $member->socialnetworks;
1759 
1760  $this->pass = $member->pass;
1761  $this->pass_crypted = $member->pass_indatabase_crypted;
1762 
1763  if (empty($login)) {
1764  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1765  $login = dol_buildlogin($member->lastname, $member->firstname);
1766  }
1767  $this->login = $login;
1768 
1769  $this->db->begin();
1770 
1771  // Create and set $this->id
1772  $result = $this->create($user);
1773  if ($result > 0) {
1774  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
1775  $newpass = $this->setPassword($user, $this->pass);
1776  if (is_numeric($newpass) && $newpass < 0) {
1777  $result = -2;
1778  }
1779  } 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.
1780  $sql = "UPDATE ".$this->db->prefix()."user";
1781  $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
1782  $sql .= " WHERE rowid=".((int) $this->id);
1783 
1784  $resql = $this->db->query($sql);
1785  if (!$resql) {
1786  $result = -1;
1787  }
1788  }
1789 
1790  if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
1791  $sql = "UPDATE ".$this->db->prefix()."user";
1792  $sql .= " SET fk_soc=".((int) $member->socid);
1793  $sql .= " WHERE rowid=".((int) $this->id);
1794 
1795  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
1796  $resql = $this->db->query($sql);
1797  if ($resql) {
1798  $this->db->commit();
1799  return $this->id;
1800  } else {
1801  $this->error = $this->db->lasterror();
1802 
1803  $this->db->rollback();
1804  return -1;
1805  }
1806  }
1807  }
1808 
1809  if ($result > 0) {
1810  $this->db->commit();
1811  return $this->id;
1812  } else {
1813  // $this->error deja positionne
1814  $this->db->rollback();
1815  return -2;
1816  }
1817  }
1818 
1819  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1825  public function set_default_rights()
1826  {
1827  // phpcs:enable
1828  global $conf;
1829 
1830  $rd = array();
1831  $num = 0;
1832  $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
1833  $sql .= " WHERE bydefault = 1";
1834  $sql .= " AND entity = ".((int) $conf->entity);
1835 
1836  $resql = $this->db->query($sql);
1837  if ($resql) {
1838  $num = $this->db->num_rows($resql);
1839  $i = 0;
1840  while ($i < $num) {
1841  $row = $this->db->fetch_row($resql);
1842  $rd[$i] = $row[0];
1843  $i++;
1844  }
1845  $this->db->free($resql);
1846  }
1847  $i = 0;
1848  while ($i < $num) {
1849  $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
1850  $result = $this->db->query($sql);
1851 
1852  $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
1853  $result = $this->db->query($sql);
1854  if (!$result) {
1855  return -1;
1856  }
1857  $i++;
1858  }
1859 
1860  return $i;
1861  }
1862 
1873  public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
1874  {
1875  global $conf, $langs;
1876 
1877  $nbrowsaffected = 0;
1878  $error = 0;
1879 
1880  dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
1881 
1882  // Clean parameters
1883  $this->civility_code = trim((string) $this->civility_code);
1884  $this->lastname = trim((string) $this->lastname);
1885  $this->firstname = trim((string) $this->firstname);
1886  $this->ref_employee = trim((string) $this->ref_employee);
1887  $this->national_registration_number = trim((string) $this->national_registration_number);
1888  $this->employee = ($this->employee > 0 ? $this->employee : 0);
1889  $this->login = trim((string) $this->login);
1890  $this->gender = trim((string) $this->gender);
1891 
1892  $this->pass = trim((string) $this->pass);
1893  $this->api_key = trim((string) $this->api_key);
1894  $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
1895  $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
1896 
1897  $this->address = trim((string) $this->address);
1898  $this->zip = trim((string) $this->zip);
1899  $this->town = trim((string) $this->town);
1900 
1901  $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
1902  $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
1903  $this->office_phone = trim((string) $this->office_phone);
1904  $this->office_fax = trim((string) $this->office_fax);
1905  $this->user_mobile = trim((string) $this->user_mobile);
1906  $this->personal_mobile = trim((string) $this->personal_mobile);
1907  $this->email = trim((string) $this->email);
1908  $this->personal_email = trim((string) $this->personal_email);
1909 
1910  $this->job = trim((string) $this->job);
1911  $this->signature = trim((string) $this->signature);
1912  $this->note_public = trim((string) $this->note_public);
1913  $this->note_private = trim((string) $this->note_private);
1914  $this->openid = trim((string) $this->openid);
1915  $this->admin = ($this->admin > 0 ? $this->admin : 0);
1916 
1917  $this->accountancy_code = trim((string) $this->accountancy_code);
1918  $this->color = trim((string) $this->color);
1919  $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
1920  $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
1921 
1922  $this->birth = empty($this->birth) ? '' : $this->birth;
1923  $this->fk_warehouse = (int) $this->fk_warehouse;
1924 
1925  $this->setUpperOrLowerCase();
1926 
1927  // Check parameters
1928  $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1929 
1930  if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
1931  $langs->load("errors");
1932  $this->error = $langs->trans("ErrorBadEMail", $this->email);
1933  return -1;
1934  }
1935  if (empty($this->login)) {
1936  $langs->load("errors");
1937  $this->error = $langs->trans("ErrorFieldRequired", 'Login');
1938  return -1;
1939  } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1940  $langs->load("errors");
1941  $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1942  return -1;
1943  }
1944 
1945  $this->db->begin();
1946 
1947  // Check if login already exists in same entity or into entity 0.
1948  if (!empty($this->oldcopy) && $this->oldcopy->login != $this->login) {
1949  $sqltochecklogin = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."user WHERE entity IN (".$this->db->sanitize((int) $this->entity).", 0) AND login = '".$this->db->escape($this->login)."'";
1950  $resqltochecklogin = $this->db->query($sqltochecklogin);
1951  if ($resqltochecklogin) {
1952  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1953  if ($objtochecklogin && $objtochecklogin->nb > 0) {
1954  $langs->load("errors");
1955  $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1956  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1957  $this->db->rollback();
1958  return -1;
1959  }
1960  }
1961  }
1962  if (!empty($this->oldcopy) && !empty($this->email) && $this->oldcopy->email != $this->email) {
1963  $sqltochecklogin = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."user WHERE entity IN (".$this->db->sanitize((int) $this->entity).", 0) AND email = '".$this->db->escape($this->email)."'";
1964  $resqltochecklogin = $this->db->query($sqltochecklogin);
1965  if ($resqltochecklogin) {
1966  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1967  if ($objtochecklogin && $objtochecklogin->nb > 0) {
1968  $langs->load("errors");
1969  $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1970  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1971  $this->db->rollback();
1972  return -1;
1973  }
1974  }
1975  }
1976 
1977  // Update datas
1978  $sql = "UPDATE ".$this->db->prefix()."user SET";
1979  $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
1980  $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
1981  $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
1982  $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
1983  $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
1984  $sql .= ", employee = ".(int) $this->employee;
1985  $sql .= ", login = '".$this->db->escape($this->login)."'";
1986  $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
1987  $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman'
1988  $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
1989  if (!empty($user->admin)) {
1990  $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
1991  }
1992  $sql .= ", address = '".$this->db->escape($this->address)."'";
1993  $sql .= ", zip = '".$this->db->escape($this->zip)."'";
1994  $sql .= ", town = '".$this->db->escape($this->town)."'";
1995  $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".$this->db->escape($this->state_id)."'" : "null");
1996  $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".$this->db->escape($this->country_id)."'" : "null");
1997  $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
1998  $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
1999  $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
2000  $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
2001  $sql .= ", email = '".$this->db->escape($this->email)."'";
2002  $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
2003  $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
2004  $sql .= ", job = '".$this->db->escape($this->job)."'";
2005  $sql .= ", signature = '".$this->db->escape($this->signature)."'";
2006  $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
2007  $sql .= ", color = '".$this->db->escape($this->color)."'";
2008  $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
2009  $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
2010  $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2011  $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2012  $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2013  $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2014  $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2015  $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2016  $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".$this->db->escape($this->fk_user)."'" : "null");
2017  $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".$this->db->escape($this->fk_user_expense_validator)."'" : "null");
2018  $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".$this->db->escape($this->fk_user_holiday_validator)."'" : "null");
2019  if (isset($this->thm) || $this->thm != '') {
2020  $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2021  }
2022  if (isset($this->tjm) || $this->tjm != '') {
2023  $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2024  }
2025  if (isset($this->salary) || $this->salary != '') {
2026  $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2027  }
2028  if (isset($this->salaryextra) || $this->salaryextra != '') {
2029  $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2030  }
2031  $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2032  if (!empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2033  $sql .= ", entity = ".((int) $this->entity); // entity flag can be set/unset only by an another superadmin user
2034  }
2035  $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
2036  $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
2037  $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
2038  $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2039  $sql .= " WHERE rowid = ".((int) $this->id);
2040 
2041  dol_syslog(get_class($this)."::update", LOG_DEBUG);
2042  $resql = $this->db->query($sql);
2043  if ($resql) {
2044  $nbrowsaffected += $this->db->affected_rows($resql);
2045 
2046  // Update password
2047  if (!empty($this->pass)) {
2048  if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2049  // If a new value for password is set and different than the one crypted into database
2050  $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2051  if (is_numeric($result) && $result < 0) {
2052  return -5;
2053  }
2054  }
2055  }
2056 
2057  // If user is linked to a member, remove old link to this member
2058  if ($this->fk_member > 0) {
2059  dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2060  $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2061  $resql = $this->db->query($sql);
2062  if (!$resql) {
2063  $this->error = $this->db->error(); $this->db->rollback(); return -5;
2064  }
2065  }
2066  // Set link to user
2067  dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2068  $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2069  $resql = $this->db->query($sql);
2070  if (!$resql) {
2071  $this->error = $this->db->error(); $this->db->rollback(); return -5;
2072  }
2073 
2074  if ($nbrowsaffected) { // If something has changed in data
2075  if ($this->fk_member > 0 && !$nosyncmember) {
2076  dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2077 
2078  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2079 
2080  // This user is linked with a member, so we also update member information
2081  // if this is an update.
2082  $adh = new Adherent($this->db);
2083  $result = $adh->fetch($this->fk_member);
2084 
2085  if ($result > 0) {
2086  $adh->civility_code = $this->civility_code;
2087  $adh->firstname = $this->firstname;
2088  $adh->lastname = $this->lastname;
2089  $adh->login = $this->login;
2090  $adh->gender = $this->gender;
2091  $adh->birth = $this->birth;
2092 
2093  $adh->pass = $this->pass;
2094 
2095  $adh->address = $this->address;
2096  $adh->town = $this->town;
2097  $adh->zip = $this->zip;
2098  $adh->state_id = $this->state_id;
2099  $adh->country_id = $this->country_id;
2100 
2101  $adh->email = $this->email;
2102 
2103  $adh->socialnetworks = $this->socialnetworks;
2104 
2105  $adh->phone = $this->office_phone;
2106  $adh->phone_mobile = $this->user_mobile;
2107 
2108  $adh->default_lang = $this->lang;
2109 
2110  $adh->user_id = $this->id;
2111  $adh->user_login = $this->login;
2112 
2113  $result = $adh->update($user, 0, 1, 0);
2114  if ($result < 0) {
2115  $this->error = $adh->error;
2116  $this->errors = $adh->errors;
2117  dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2118  $error++;
2119  }
2120  } elseif ($result < 0) {
2121  $this->error = $adh->error;
2122  $this->errors = $adh->errors;
2123  $error++;
2124  }
2125  }
2126 
2127  if ($this->contact_id > 0 && !$nosynccontact) {
2128  dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2129 
2130  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2131 
2132  // This user is linked with a contact, so we also update contact information if this is an update.
2133  $tmpobj = new Contact($this->db);
2134  $result = $tmpobj->fetch($this->contact_id);
2135 
2136  if ($result >= 0) {
2137  $tmpobj->civility_code = $this->civility_code;
2138  $tmpobj->firstname = $this->firstname;
2139  $tmpobj->lastname = $this->lastname;
2140  $tmpobj->login = $this->login;
2141  $tmpobj->gender = $this->gender;
2142  $tmpobj->birth = $this->birth;
2143 
2144  //$tmpobj->pass=$this->pass;
2145 
2146  $tmpobj->email = $this->email;
2147 
2148  $tmpobj->socialnetworks = $this->socialnetworks;
2149 
2150  $tmpobj->phone_pro = $this->office_phone;
2151  $tmpobj->phone_mobile = $this->user_mobile;
2152  $tmpobj->fax = $this->office_fax;
2153 
2154  $tmpobj->default_lang = $this->lang;
2155 
2156  $tmpobj->address = $this->address;
2157  $tmpobj->town = $this->town;
2158  $tmpobj->zip = $this->zip;
2159  $tmpobj->state_id = $this->state_id;
2160  $tmpobj->country_id = $this->country_id;
2161 
2162  $tmpobj->user_id = $this->id;
2163  $tmpobj->user_login = $this->login;
2164 
2165  $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2166  if ($result < 0) {
2167  $this->error = $tmpobj->error;
2168  $this->errors = $tmpobj->errors;
2169  dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2170  $error++;
2171  }
2172  } else {
2173  $this->error = $tmpobj->error;
2174  $this->errors = $tmpobj->errors;
2175  $error++;
2176  }
2177  }
2178  }
2179 
2180  $action = 'update';
2181 
2182  // Actions on extra fields
2183  if (!$error) {
2184  $result = $this->insertExtraFields();
2185  if ($result < 0) {
2186  $error++;
2187  }
2188  }
2189 
2190  if (!$error && !$notrigger) {
2191  // Call trigger
2192  $result = $this->call_trigger('USER_MODIFY', $user);
2193  if ($result < 0) {
2194  $error++;
2195  }
2196  // End call triggers
2197  }
2198 
2199  if (!$error) {
2200  $this->db->commit();
2201  return $nbrowsaffected;
2202  } else {
2203  dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2204  $this->db->rollback();
2205  return -1;
2206  }
2207  } else {
2208  $this->error = $this->db->lasterror();
2209  $this->db->rollback();
2210  return -2;
2211  }
2212  }
2213 
2214  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2221  public function update_last_login_date()
2222  {
2223  // phpcs:enable
2224  $now = dol_now();
2225 
2226  $userremoteip = getUserRemoteIP();
2227 
2228  $sql = "UPDATE ".$this->db->prefix()."user SET";
2229  $sql .= " datepreviouslogin = datelastlogin,";
2230  $sql .= " ippreviouslogin = iplastlogin,";
2231  $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2232  $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2233  $sql .= " tms = tms"; // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
2234  $sql .= " WHERE rowid = ".((int) $this->id);
2235 
2236  dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2237  $resql = $this->db->query($sql);
2238  if ($resql) {
2239  $this->datepreviouslogin = $this->datelastlogin;
2240  $this->datelastlogin = $now;
2241  $this->ippreviouslogin = $this->iplastlogin;
2242  $this->iplastlogin = $userremoteip;
2243  return 1;
2244  } else {
2245  $this->error = $this->db->lasterror().' sql='.$sql;
2246  return -1;
2247  }
2248  }
2249 
2250 
2263  public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2264  {
2265  global $conf, $langs;
2266  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2267 
2268  $error = 0;
2269 
2270  dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2271 
2272  // If new password not provided, we generate one
2273  if (!$password) {
2274  $password = getRandomPassword(false);
2275  }
2276 
2277  // Check and encrypt the password
2278  if (empty($passwordalreadycrypted)) {
2279  if (!empty($conf->global->USER_PASSWORD_GENERATED)) {
2280  // Add a check on rules for password syntax using the setup of the password generator
2281  $modGeneratePassClass = 'modGeneratePass'.ucfirst($conf->global->USER_PASSWORD_GENERATED);
2282 
2283  include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2284  if (class_exists($modGeneratePassClass)) {
2285  $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2286 
2287  // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2288  $modGeneratePass->WithoutAmbi = 0;
2289 
2290  // Call to validatePassword($password) to check pass match rules
2291  $testpassword = $modGeneratePass->validatePassword($password);
2292  if (!$testpassword) {
2293  $this->error = $modGeneratePass->error;
2294  return -1;
2295  }
2296  }
2297  }
2298 
2299 
2300  // Now, we encrypt the new password
2301  $password_crypted = dol_hash($password);
2302  }
2303 
2304  // Update password
2305  if (!$changelater) {
2306  if (!is_object($this->oldcopy)) {
2307  $this->oldcopy = clone $this;
2308  }
2309 
2310  $this->db->begin();
2311 
2312  $sql = "UPDATE ".$this->db->prefix()."user";
2313  $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2314  $sql .= " pass_temp = null";
2315  if (!empty($flagdelsessionsbefore)) {
2316  $sql .= ", flagdelsessionsbefore = '".$this->db->idate(dol_now() - 5, 'gmt')."'";
2317  }
2318  if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
2319  $sql .= ", pass = null";
2320  } else {
2321  $sql .= ", pass = '".$this->db->escape($password)."'";
2322  }
2323  $sql .= " WHERE rowid = ".((int) $this->id);
2324 
2325  dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2326  $result = $this->db->query($sql);
2327  if ($result) {
2328  if ($this->db->affected_rows($result)) {
2329  $this->pass = $password;
2330  $this->pass_indatabase = $password;
2331  $this->pass_indatabase_crypted = $password_crypted;
2332 
2333  if ($this->fk_member && !$nosyncmember) {
2334  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2335 
2336  // This user is linked with a member, so we also update members informations
2337  // if this is an update.
2338  $adh = new Adherent($this->db);
2339  $result = $adh->fetch($this->fk_member);
2340 
2341  if ($result >= 0) {
2342  $result = $adh->setPassword($user, $this->pass, (empty($conf->global->DATABASE_PWD_ENCRYPTED) ? 0 : 1), 1); // Cryptage non gere dans module adherent
2343  if (is_numeric($result) && $result < 0) {
2344  $this->error = $adh->error;
2345  dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2346  $error++;
2347  }
2348  } else {
2349  $this->error = $adh->error;
2350  $error++;
2351  }
2352  }
2353 
2354  dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2355 
2356  if (!$error && !$notrigger) {
2357  // Call trigger
2358  $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2359  if ($result < 0) {
2360  $error++; $this->db->rollback(); return -1;
2361  }
2362  // End call triggers
2363  }
2364 
2365  $this->db->commit();
2366  return $this->pass;
2367  } else {
2368  $this->db->rollback();
2369  return 0;
2370  }
2371  } else {
2372  $this->db->rollback();
2373  dol_print_error($this->db);
2374  return -1;
2375  }
2376  } else {
2377  // We store password in password temporary field.
2378  // After receiving confirmation link, we will erase and store it in pass_crypted
2379  $sql = "UPDATE ".$this->db->prefix()."user";
2380  $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2381  $sql .= " WHERE rowid = ".((int) $this->id);
2382 
2383  dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2384  $result = $this->db->query($sql);
2385  if ($result) {
2386  return $password;
2387  } else {
2388  dol_print_error($this->db);
2389  return -3;
2390  }
2391  }
2392  }
2393 
2394  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2403  public function send_password($user, $password = '', $changelater = 0)
2404  {
2405  // phpcs:enable
2406  global $conf, $langs, $mysoc;
2407  global $dolibarr_main_url_root;
2408 
2409  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2410 
2411  $msgishtml = 0;
2412 
2413  // Define $msg
2414  $mesg = '';
2415 
2416  $outputlangs = new Translate("", $conf);
2417 
2418  if (isset($this->conf->MAIN_LANG_DEFAULT)
2419  && $this->conf->MAIN_LANG_DEFAULT != 'auto') { // If user has defined its own language (rare because in most cases, auto is used)
2420  $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2421  }
2422 
2423  if ($this->conf->MAIN_LANG_DEFAULT) {
2424  $outputlangs->setDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2425  } else { // If user has not defined its own language, we used current language
2426  $outputlangs = $langs;
2427  }
2428 
2429  // Load translation files required by the page
2430  $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2431 
2432  $appli = constant('DOL_APPLICATION_TITLE');
2433  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
2434  $appli = $conf->global->MAIN_APPLICATION_TITLE;
2435  }
2436 
2437  $subject = '['.$mysoc->name.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2438 
2439  // Define $urlwithroot
2440  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2441  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2442 
2443  if (!$changelater) {
2444  $url = $urlwithroot.'/';
2445  if (!empty($conf->global->URL_REDIRECTION_AFTER_CHANGEPASSWORD)) {
2446  $url = $conf->global->URL_REDIRECTION_AFTER_CHANGEPASSWORD;
2447  }
2448 
2449  dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2450 
2451  $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2452  $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2453  $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2454  $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2455  $mesg .= "\n";
2456 
2457  $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2458  $mesg .= "--\n";
2459  $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2460  } else {
2461  //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2462  $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2463  $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2464  if (isModEnabled('multicompany')) {
2465  $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2466  }
2467 
2468  dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2469 
2470  $msgishtml = 1;
2471 
2472  $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2473  $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2474  $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2475  $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2476  $mesg .= "<br>\n";
2477  $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2478  $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2479  $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2480  }
2481 
2482  $trackid = 'use'.$this->id;
2483  $sendcontext = 'password';
2484 
2485  $mailfile = new CMailFile(
2486  $subject,
2487  $this->email,
2488  $conf->global->MAIN_MAIL_EMAIL_FROM,
2489  $mesg,
2490  array(),
2491  array(),
2492  array(),
2493  '',
2494  '',
2495  0,
2496  $msgishtml,
2497  '',
2498  '',
2499  $trackid,
2500  '',
2501  $sendcontext
2502  );
2503 
2504  if ($mailfile->sendfile()) {
2505  return 1;
2506  } else {
2507  $langs->trans("errors");
2508  $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2509  return -1;
2510  }
2511  }
2512 
2518  public function error()
2519  {
2520  return $this->error;
2521  }
2522 
2523 
2524  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2530  public function fetch_clicktodial()
2531  {
2532  // phpcs:enable
2533  $sql = "SELECT url, login, pass, poste ";
2534  $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2535  $sql .= " WHERE u.fk_user = ".((int) $this->id);
2536 
2537  $resql = $this->db->query($sql);
2538  if ($resql) {
2539  if ($this->db->num_rows($resql)) {
2540  $obj = $this->db->fetch_object($resql);
2541 
2542  $this->clicktodial_url = $obj->url;
2543  $this->clicktodial_login = $obj->login;
2544  $this->clicktodial_password = $obj->pass;
2545  $this->clicktodial_poste = $obj->poste;
2546  }
2547 
2548  $this->clicktodial_loaded = 1; // Data loaded (found or not)
2549 
2550  $this->db->free($resql);
2551  return 1;
2552  } else {
2553  $this->error = $this->db->error();
2554  return -1;
2555  }
2556  }
2557 
2558  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2564  public function update_clicktodial()
2565  {
2566  // phpcs:enable
2567  $this->db->begin();
2568 
2569  $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2570  $sql .= " WHERE fk_user = ".((int) $this->id);
2571 
2572  dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2573  $result = $this->db->query($sql);
2574 
2575  $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
2576  $sql .= " (fk_user,url,login,pass,poste)";
2577  $sql .= " VALUES (".$this->id;
2578  $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2579  $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2580  $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2581  $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2582 
2583  dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2584  $result = $this->db->query($sql);
2585  if ($result) {
2586  $this->db->commit();
2587  return 1;
2588  } else {
2589  $this->db->rollback();
2590  $this->error = $this->db->lasterror();
2591  return -1;
2592  }
2593  }
2594 
2595 
2596  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2605  public function SetInGroup($group, $entity, $notrigger = 0)
2606  {
2607  // phpcs:enable
2608  global $conf, $langs, $user;
2609 
2610  $error = 0;
2611 
2612  $this->db->begin();
2613 
2614  $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2615  $sql .= " WHERE fk_user = ".((int) $this->id);
2616  $sql .= " AND fk_usergroup = ".((int) $group);
2617  $sql .= " AND entity = ".((int) $entity);
2618 
2619  $result = $this->db->query($sql);
2620 
2621  $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
2622  $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
2623 
2624  $result = $this->db->query($sql);
2625  if ($result) {
2626  if (!$error && !$notrigger) {
2627  $this->newgroupid = $group; // deprecated. Remove this.
2628  $this->context = array('audit'=>$langs->trans("UserSetInGroup"), 'newgroupid'=>$group);
2629 
2630  // Call trigger
2631  $result = $this->call_trigger('USER_MODIFY', $user);
2632  if ($result < 0) {
2633  $error++;
2634  }
2635  // End call triggers
2636  }
2637 
2638  if (!$error) {
2639  $this->db->commit();
2640  return 1;
2641  } else {
2642  dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2643  $this->db->rollback();
2644  return -2;
2645  }
2646  } else {
2647  $this->error = $this->db->lasterror();
2648  $this->db->rollback();
2649  return -1;
2650  }
2651  }
2652 
2653  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2662  public function RemoveFromGroup($group, $entity, $notrigger = 0)
2663  {
2664  // phpcs:enable
2665  global $conf, $langs, $user;
2666 
2667  $error = 0;
2668 
2669  $this->db->begin();
2670 
2671  $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2672  $sql .= " WHERE fk_user = ".((int) $this->id);
2673  $sql .= " AND fk_usergroup = ".((int) $group);
2674  if (empty($entity)) {
2675  $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
2676  } else {
2677  $sql .= " AND entity = ".((int) $entity);
2678  }
2679 
2680  $result = $this->db->query($sql);
2681  if ($result) {
2682  if (!$error && !$notrigger) {
2683  $this->oldgroupid = $group; // deprecated. Remove this.
2684  $this->context = array('audit'=>$langs->trans("UserRemovedFromGroup"), 'oldgroupid'=>$group);
2685 
2686  // Call trigger
2687  $result = $this->call_trigger('USER_MODIFY', $user);
2688  if ($result < 0) {
2689  $error++;
2690  }
2691  // End call triggers
2692  }
2693 
2694  if (!$error) {
2695  $this->db->commit();
2696  return 1;
2697  } else {
2698  dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2699  $this->db->rollback();
2700  return -2;
2701  }
2702  } else {
2703  $this->error = $this->db->lasterror();
2704  $this->db->rollback();
2705  return -1;
2706  }
2707  }
2708 
2709 
2716  public function isNotIntoValidityDateRange()
2717  {
2718  include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2719 
2720  $now = dol_now();
2721 
2722  //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
2723 
2724  // Check date start validity
2725  if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
2726  return 1;
2727  }
2728  // Check date end validity
2729  if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
2730  return 1;
2731  }
2732 
2733  return 0;
2734  }
2735 
2736 
2747  public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
2748  {
2749  $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2750  $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
2751  $result .= '</a>';
2752 
2753  return $result;
2754  }
2755 
2763  public function getTooltipContentArray($params)
2764  {
2765  global $conf, $langs, $menumanager;
2766 
2767  $infologin = $params['infologin'] ?? 0;
2768  $option = $params['option'] ?? '';
2769 
2770  $datas = [];
2771  if (!empty($this->photo)) {
2772  $photo = '<div class="photointooltip floatright">';
2773  $photo .= Form::showphoto('userphoto', $this, 0, 60, 0, 'photoref photowithmargin photologintooltip', 'small', 0, 1); // Force height to 60 so we total height of tooltip can be calculated and collision can be managed
2774  $photo .= '</div>';
2775  $datas['photo'] = $photo;
2776  //$label .= '<div style="clear: both;"></div>';
2777  }
2778 
2779  // Info Login
2780  $datas['opendiv'] = '<div class="centpercent">';
2781  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
2782  $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs, ''));
2783  if (!empty($this->login)) {
2784  $datas['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
2785  }
2786  if (!empty($this->job)) {
2787  $datas['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
2788  }
2789  $datas['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
2790  if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
2791  $phonelist = array();
2792  if ($this->office_phone) {
2793  $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2794  }
2795  if ($this->office_fax) {
2796  $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2797  }
2798  if ($this->user_mobile) {
2799  $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
2800  }
2801  $datas['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
2802  }
2803  if (!empty($this->admin)) {
2804  $datas['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
2805  }
2806  if (!empty($this->accountancy_code) || $option == 'accountancy') {
2807  $datas['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
2808  }
2809  $company = '';
2810  if (!empty($this->socid)) { // Add thirdparty for external users
2811  $thirdpartystatic = new Societe($this->db);
2812  $thirdpartystatic->fetch($this->socid);
2813  if (empty($hidethirdpartylogo)) {
2814  $companylink = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2815  }
2816  $company = ' ('.$langs->trans("Company").': '.img_picto('', 'company').' '.dol_string_nohtmltag($thirdpartystatic->name).')';
2817  }
2818  $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
2819  $datas['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
2820  $datas['closediv'] = '</div>';
2821 
2822  if ($infologin > 0) {
2823  $datas['newlinelogin'] = '<br>';
2824  $datas['session'] = '<br><u>'.$langs->trans("Session").'</u>';
2825  $datas['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
2826  if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) {
2827  $datas['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
2828  }
2829  $datas['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
2830  $datas['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
2831  $datas['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
2832  $datas['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
2833  $datas['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
2834  $s = picto_from_langcode($langs->getDefaultLang());
2835  $datas['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
2836  $datas['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
2837  $datas['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
2838  $datas['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
2839  if ($conf->browser->layout == 'phone') {
2840  $datas['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
2841  }
2842  if (!empty($_SESSION["disablemodules"])) {
2843  $datas['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(join(', ', explode(',', $_SESSION["disablemodules"])));
2844  }
2845  }
2846 
2847  return $datas;
2848  }
2849 
2865  public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
2866  {
2867  global $langs, $conf, $db, $hookmanager, $user;
2868  global $dolibarr_main_authentication, $dolibarr_main_demo;
2869  global $menumanager;
2870 
2871  if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
2872  $option = 'nolink';
2873  }
2874 
2875  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) {
2876  $withpictoimg = 0;
2877  }
2878 
2879  $result = '';
2880  $params = [
2881  'id' => $this->id,
2882  'objecttype' => $this->element,
2883  'infologin' => $infologin,
2884  'option' => $option,
2885  ];
2886  $classfortooltip = 'classfortooltip';
2887  $dataparams = '';
2888  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2889  $classfortooltip = 'classforajaxtooltip';
2890  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2891  $label = '';
2892  } else {
2893  $label = implode($this->getTooltipContentArray($params));
2894  }
2895 
2896  $companylink = '';
2897  if (!empty($this->socid)) { // Add thirdparty for external users
2898  $thirdpartystatic = new Societe($this->db);
2899  $thirdpartystatic->fetch($this->socid);
2900  if (empty($hidethirdpartylogo)) {
2901  $companylink = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2902  }
2903  }
2904 
2905  if ($infologin < 0) {
2906  $label = '';
2907  }
2908 
2909  $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id;
2910  if ($option == 'leave') {
2911  $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id;
2912  }
2913 
2914  if ($option != 'nolink') {
2915  // Add param to save lastsearch_values or not
2916  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2917  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2918  $add_save_lastsearch_values = 1;
2919  }
2920  if ($add_save_lastsearch_values) {
2921  $url .= '&save_lastsearch_values=1';
2922  }
2923  }
2924 
2925  $linkstart = '<a href="'.$url.'"';
2926  $linkclose = "";
2927  if (empty($notooltip)) {
2928  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2929  $langs->load("users");
2930  $label = $langs->trans("ShowUser");
2931  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2932  }
2933  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2934  $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
2935  } else {
2936  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
2937  }
2938 
2939  $linkstart .= $linkclose.'>';
2940  $linkend = '</a>';
2941 
2942  //if ($withpictoimg == -1) $result.='<div class="nowrap">';
2943  $result .= (($option == 'nolink') ? '' : $linkstart);
2944  if ($withpictoimg) {
2945  $paddafterimage = '';
2946  if (abs((int) $withpictoimg) == 1) {
2947  $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
2948  }
2949  // Only picto
2950  if ($withpictoimg > 0) {
2951  $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' class="paddingright")', 0, 0, $notooltip ? 0 : 1).'</span>';
2952  } else {
2953  // Picto must be a photo
2954  $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>';
2955  }
2956  $result .= $picto;
2957  }
2958  if ($withpictoimg > -2 && $withpictoimg != 2) {
2959  if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2960  $result .= '<span class="nopadding usertext'.((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
2961  }
2962  if ($mode == 'login') {
2963  $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
2964  } else {
2965  $result .= dol_string_nohtmltag($this->getFullName($langs, '', ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
2966  }
2967  if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2968  $result .= '</span>';
2969  }
2970  }
2971  $result .= (($option == 'nolink') ? '' : $linkend);
2972  //if ($withpictoimg == -1) $result.='</div>';
2973 
2974  $result .= $companylink;
2975 
2976  global $action;
2977  $hookmanager->initHooks(array('userdao'));
2978  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
2979  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2980  if ($reshook > 0) {
2981  $result = $hookmanager->resPrint;
2982  } else {
2983  $result .= $hookmanager->resPrint;
2984  }
2985 
2986  return $result;
2987  }
2988 
2998  public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
2999  {
3000  global $langs, $user;
3001 
3002  $result = '';
3003 
3004  $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3005  $linkend = '</a>';
3006 
3007  //Check user's rights to see an other user
3008  if ((!$user->rights->user->user->lire && $this->id != $user->id)) {
3009  $option = 'nolink';
3010  }
3011 
3012  if ($option == 'xxx') {
3013  $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3014  $linkend = '</a>';
3015  }
3016 
3017  if ($option == 'nolink') {
3018  $linkstart = '';
3019  $linkend = '';
3020  }
3021 
3022  $result .= $linkstart;
3023  if ($withpictoimg) {
3024  $paddafterimage = '';
3025  if (abs($withpictoimg) == 1) {
3026  $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3027  }
3028  // Only picto
3029  if ($withpictoimg > 0) {
3030  $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3031  } else {
3032  // Picto must be a photo
3033  $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>';
3034  }
3035  $result .= $picto;
3036  }
3037  $result .= $this->login;
3038  $result .= $linkend;
3039 
3040  return $result;
3041  }
3042 
3049  public function getLibStatut($mode = 0)
3050  {
3051  return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3052  }
3053 
3054  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3062  public function LibStatut($status, $mode = 0)
3063  {
3064  // phpcs:enable
3065  global $langs;
3066 
3067  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3068  global $langs;
3069  //$langs->load("mymodule");
3070  $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3071  $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3072  $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3073  $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3074  }
3075 
3076  $statusType = 'status5';
3077  if ($status == self::STATUS_ENABLED) {
3078  $statusType = 'status4';
3079  }
3080 
3081  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3082  }
3083 
3084 
3092  public function getKanbanView($option = '', $arraydata = null)
3093  {
3094  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3095 
3096  $return = '<div class="box-flex-item box-flex-grow-zero">';
3097  $return .= '<div class="info-box info-box-sm">';
3098  $return .= '<span class="info-box-icon bg-infobox-action">';
3099 
3100  $label = '';
3101  if (!empty($this->photo)) {
3102  //$label .= '<div class="photointooltip floatright">';
3103  $label .= Form::showphoto('userphoto', $this, 0, 60, 0, 'photokanban photoref photowithmargin photologintooltip', 'small', 0, 1); // Force height to 60 so we total height of tooltip can be calculated and collision can be managed
3104  //$label .= '</div>';
3105  //$label .= '<div style="clear: both;"></div>';
3106  $return .= $label;
3107  } else {
3108  $return .= img_picto('', $this->picto);
3109  }
3110 
3111  //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3112  $return .= '</span>';
3113  $return .= '<div class="info-box-content">';
3114  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
3115  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3116  if (property_exists($this, 'label')) {
3117  $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3118  }
3119  if ($this->email) {
3120  $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3121  }
3122  if (method_exists($this, 'getLibStatut')) {
3123  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
3124  }
3125  $return .= '</div>';
3126  $return .= '</div>';
3127  $return .= '</div>';
3128 
3129  return $return;
3130  }
3131 
3132 
3133  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3134  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3144  public function _load_ldap_dn($info, $mode = 0)
3145  {
3146  // phpcs:enable
3147  global $conf;
3148  $dn = '';
3149  if ($mode == 0) {
3150  $dn = $conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS].",".$conf->global->LDAP_USER_DN;
3151  } elseif ($mode == 1) {
3152  $dn = $conf->global->LDAP_USER_DN;
3153  } elseif ($mode == 2) {
3154  $dn = $conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS];
3155  }
3156  return $dn;
3157  }
3158 
3159  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3160  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3166  public function _load_ldap_info()
3167  {
3168  // phpcs:enable
3169  global $conf, $langs;
3170 
3171  $info = array();
3172 
3173  $socialnetworks = getArrayOfSocialNetworks();
3174 
3175  $keymodified = false;
3176 
3177  // Object classes
3178  $info["objectclass"] = explode(',', $conf->global->LDAP_USER_OBJECT_CLASS);
3179 
3180  $this->fullname = $this->getFullName($langs);
3181 
3182  // Possible LDAP KEY (constname => varname)
3183  $ldapkey = array(
3184  'LDAP_FIELD_FULLNAME' => 'fullname',
3185  'LDAP_FIELD_NAME' => 'lastname',
3186  'LDAP_FIELD_FIRSTNAME' => 'firstname',
3187  'LDAP_FIELD_LOGIN' => 'login',
3188  'LDAP_FIELD_LOGIN_SAMBA'=> 'login',
3189  'LDAP_FIELD_PHONE' => 'office_phone',
3190  'LDAP_FIELD_MOBILE' => 'user_mobile',
3191  'LDAP_FIELD_FAX' => 'office_fax',
3192  'LDAP_FIELD_MAIL' => 'email',
3193  'LDAP_FIELD_SID' => 'ldap_sid',
3194  );
3195 
3196  // Champs
3197  foreach ($ldapkey as $constname => $varname) {
3198  if (!empty($this->$varname) && !empty($conf->global->$constname)) {
3199  $info[$conf->global->$constname] = $this->$varname;
3200 
3201  // Check if it is the LDAP key and if its value has been changed
3202  if (!empty($conf->global->LDAP_KEY_USERS) && $conf->global->LDAP_KEY_USERS == $conf->global->$constname) {
3203  if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
3204  $keymodified = true; // For check if LDAP key has been modified
3205  }
3206  }
3207  }
3208  }
3209  foreach ($socialnetworks as $key => $value) {
3210  if (!empty($this->socialnetworks[$value['label']]) && !empty($conf->global->{'LDAP_FIELD_'.strtoupper($value['label'])})) {
3211  $info[$conf->global->{'LDAP_FIELD_'.strtoupper($value['label'])}] = $this->socialnetworks[$value['label']];
3212  }
3213  }
3214  if ($this->address && !empty($conf->global->LDAP_FIELD_ADDRESS)) {
3215  $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address;
3216  }
3217  if ($this->zip && !empty($conf->global->LDAP_FIELD_ZIP)) {
3218  $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip;
3219  }
3220  if ($this->town && !empty($conf->global->LDAP_FIELD_TOWN)) {
3221  $info[$conf->global->LDAP_FIELD_TOWN] = $this->town;
3222  }
3223  if ($this->note_public && !empty($conf->global->LDAP_FIELD_DESCRIPTION)) {
3224  $info[$conf->global->LDAP_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_public, 2);
3225  }
3226  if ($this->socid > 0) {
3227  $soc = new Societe($this->db);
3228  $soc->fetch($this->socid);
3229 
3230  $info[$conf->global->LDAP_FIELD_COMPANY] = $soc->name;
3231  if ($soc->client == 1) {
3232  $info["businessCategory"] = "Customers";
3233  }
3234  if ($soc->client == 2) {
3235  $info["businessCategory"] = "Prospects";
3236  }
3237  if ($soc->fournisseur == 1) {
3238  $info["businessCategory"] = "Suppliers";
3239  }
3240  }
3241 
3242  // When password is modified
3243  if (!empty($this->pass)) {
3244  if (!empty($conf->global->LDAP_FIELD_PASSWORD)) {
3245  $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte
3246  }
3247  if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
3248  $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3249  }
3250  } elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') {
3251  // Set LDAP password if possible
3252  // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3253  if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
3254  // Just for the default MD5 !
3255  if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) {
3256  if ($this->pass_indatabase_crypted && !empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
3257  $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3258  }
3259  }
3260  } elseif (!empty($this->pass_indatabase)) {
3261  // Use $this->pass_indatabase value if exists
3262  if (!empty($conf->global->LDAP_FIELD_PASSWORD)) {
3263  $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte
3264  }
3265  if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
3266  $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3267  }
3268  }
3269  }
3270 
3271  if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') {
3272  $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3273 
3274  $info['uidnumber'] = $this->id;
3275 
3276  $info['phpgwTz'] = 0;
3277  $info['phpgwMailType'] = 'INTERNET';
3278  $info['phpgwMailHomeType'] = 'INTERNET';
3279 
3280  $info["phpgwContactTypeId"] = 'n';
3281  $info["phpgwContactCatId"] = 0;
3282  $info["phpgwContactAccess"] = "public";
3283 
3284  if (dol_strlen($this->egroupware_id) == 0) {
3285  $this->egroupware_id = 1;
3286  }
3287 
3288  $info["phpgwContactOwner"] = $this->egroupware_id;
3289 
3290  if ($this->email) {
3291  $info["rfc822Mailbox"] = $this->email;
3292  }
3293  if ($this->phone_mobile) {
3294  $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
3295  }
3296  }
3297 
3298  if (!empty($conf->global->LDAP_FIELD_USERID)) {
3299  $info[$conf->global->LDAP_FIELD_USERID] = $this->id;
3300  }
3301  if (!empty($conf->global->LDAP_FIELD_GROUPID)) {
3302  $usergroup = new UserGroup($this->db);
3303  $groupslist = $usergroup->listGroupsForUser($this->id);
3304  $info[$conf->global->LDAP_FIELD_GROUPID] = '65534';
3305  if (!empty($groupslist)) {
3306  foreach ($groupslist as $groupforuser) {
3307  $info[$conf->global->LDAP_FIELD_GROUPID] = $groupforuser->id; //Select first group in list
3308  break;
3309  }
3310  }
3311  }
3312  if (!empty($conf->global->LDAP_FIELD_HOMEDIRECTORY) && !empty($conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX)) {
3313  $info[$conf->global->LDAP_FIELD_HOMEDIRECTORY] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->login";
3314  }
3315 
3316  return $info;
3317  }
3318 
3319 
3327  public function initAsSpecimen()
3328  {
3329  global $user, $langs;
3330 
3331  $now = dol_now();
3332 
3333  // Initialise parametres
3334  $this->id = 0;
3335  $this->ref = 'SPECIMEN';
3336  $this->specimen = 1;
3337 
3338  $this->lastname = 'DOLIBARR';
3339  $this->firstname = 'SPECIMEN';
3340  $this->gender = 'man';
3341  $this->note_public = 'This is a note public';
3342  $this->note_private = 'This is a note private';
3343  $this->email = 'email@specimen.com';
3344  $this->personal_email = 'personalemail@specimen.com';
3345  $this->socialnetworks = array(
3346  'skype' => 'skypepseudo',
3347  'twitter' => 'twitterpseudo',
3348  'facebook' => 'facebookpseudo',
3349  'linkedin' => 'linkedinpseudo',
3350  );
3351  $this->office_phone = '0999999999';
3352  $this->office_fax = '0999999998';
3353  $this->user_mobile = '0999999997';
3354  $this->personal_mobile = '0999999996';
3355  $this->admin = 0;
3356  $this->login = 'dolibspec';
3357  $this->pass = 'dolibSpec+@123';
3358  //$this->pass_indatabase='dolibspec'; Set after a fetch
3359  //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3360  $this->datec = $now;
3361  $this->datem = $now;
3362 
3363  $this->datelastlogin = $now;
3364  $this->iplastlogin = '127.0.0.1';
3365  $this->datepreviouslogin = $now;
3366  $this->ippreviouslogin = '127.0.0.1';
3367  $this->statut = 1; // deprecated
3368  $this->status = 1;
3369 
3370  $this->entity = 1;
3371  return 1;
3372  }
3373 
3380  public function info($id)
3381  {
3382  $sql = "SELECT u.rowid, u.login as ref, u.datec,";
3383  $sql .= " u.tms as date_modification, u.entity";
3384  $sql .= " FROM ".$this->db->prefix()."user as u";
3385  $sql .= " WHERE u.rowid = ".((int) $id);
3386 
3387  $result = $this->db->query($sql);
3388  if ($result) {
3389  if ($this->db->num_rows($result)) {
3390  $obj = $this->db->fetch_object($result);
3391 
3392  $this->id = $obj->rowid;
3393 
3394  $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3395  $this->date_creation = $this->db->jdate($obj->datec);
3396  $this->date_modification = $this->db->jdate($obj->date_modification);
3397  $this->entity = $obj->entity;
3398  }
3399 
3400  $this->db->free($result);
3401  } else {
3402  dol_print_error($this->db);
3403  }
3404  }
3405 
3406 
3412  public function getNbOfEMailings()
3413  {
3414  $sql = "SELECT count(mc.email) as nb";
3415  $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3416  $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3417  $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes
3418 
3419  $resql = $this->db->query($sql);
3420  if ($resql) {
3421  $obj = $this->db->fetch_object($resql);
3422  $nb = $obj->nb;
3423 
3424  $this->db->free($resql);
3425  return $nb;
3426  } else {
3427  $this->error = $this->db->error();
3428  return -1;
3429  }
3430  }
3431 
3440  public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3441  {
3442  global $conf;
3443 
3444  $sql = "SELECT count(rowid) as nb";
3445  $sql .= " FROM ".$this->db->prefix()."user";
3446  if ($option == 'superadmin') {
3447  $sql .= " WHERE entity = 0";
3448  } else {
3449  $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3450  if ($limitTo == 'active') {
3451  $sql .= " AND statut = 1";
3452  }
3453  }
3454  if ($admin >= 0) {
3455  $sql .= " AND admin = ".(int) $admin;
3456  }
3457 
3458  $resql = $this->db->query($sql);
3459  if ($resql) {
3460  $obj = $this->db->fetch_object($resql);
3461  $nb = (int) $obj->nb;
3462 
3463  $this->db->free($resql);
3464  return $nb;
3465  } else {
3466  $this->error = $this->db->lasterror();
3467  return -1;
3468  }
3469  }
3470 
3471  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3478  public function update_ldap2dolibarr(&$ldapuser)
3479  {
3480  // phpcs:enable
3481  // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3482  global $user, $conf;
3483 
3484  $socialnetworks = getArrayOfSocialNetworks();
3485 
3486  $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3487  $this->firstname = $ldapuser->$tmpvar;
3488  $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3489  $this->lastname = $ldapuser->$tmpvar;
3490  $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3491  $this->login = $ldapuser->$tmpvar;
3492  $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3493  $this->pass = $ldapuser->$tmpvar;
3494  $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3495  $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3496 
3497  $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3498  $this->office_phone = $ldapuser->$tmpvar;
3499  $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3500  $this->user_mobile = $ldapuser->$tmpvar;
3501  $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3502  $this->office_fax = $ldapuser->$tmpvar;
3503  $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3504  $this->email = $ldapuser->$tmpvar;
3505  foreach ($socialnetworks as $key => $value) {
3506  $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3507  $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3508  }
3509  $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3510  $this->ldap_sid = $ldapuser->$tmpvar;
3511 
3512  $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3513  $this->job = $ldapuser->$tmpvar;
3514  $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3515  $this->note_public = $ldapuser->$tmpvar;
3516 
3517  $result = $this->update($user);
3518 
3519  dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3520 
3521  return $result;
3522  }
3523 
3524 
3525  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3532  public function get_children()
3533  {
3534  // phpcs:enable
3535  $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3536  $sql .= " WHERE fk_user = ".((int) $this->id);
3537 
3538  dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3539  $res = $this->db->query($sql);
3540  if ($res) {
3541  $users = array();
3542  while ($rec = $this->db->fetch_array($res)) {
3543  $user = new User($this->db);
3544  $user->fetch($rec['rowid']);
3545  $users[] = $user;
3546  }
3547  return $users;
3548  } else {
3549  dol_print_error($this->db);
3550  return -1;
3551  }
3552  }
3553 
3554 
3560  private function loadParentOf()
3561  {
3562  global $conf;
3563 
3564  $this->parentof = array();
3565 
3566  // Load array[child]=parent
3567  $sql = "SELECT fk_user as id_parent, rowid as id_son";
3568  $sql .= " FROM ".$this->db->prefix()."user";
3569  $sql .= " WHERE fk_user <> 0";
3570  $sql .= " AND entity IN (".getEntity('user').")";
3571 
3572  dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3573  $resql = $this->db->query($sql);
3574  if ($resql) {
3575  while ($obj = $this->db->fetch_object($resql)) {
3576  $this->parentof[$obj->id_son] = $obj->id_parent;
3577  }
3578  return 1;
3579  } else {
3580  dol_print_error($this->db);
3581  return -1;
3582  }
3583  }
3584 
3585  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3599  public function get_full_tree($deleteafterid = 0, $filter = '')
3600  {
3601  // phpcs:enable
3602  global $conf, $user;
3603  global $hookmanager;
3604 
3605  // Actions hooked (by external module)
3606  $hookmanager->initHooks(array('userdao'));
3607 
3608  $this->users = array();
3609 
3610  // Init this->parentof that is array(id_son=>id_parent, ...)
3611  $this->loadParentOf();
3612 
3613  // Init $this->users array
3614  $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
3615  $sql .= " FROM ".$this->db->prefix()."user as u";
3616  // Add fields from hooks
3617  $parameters = array();
3618  $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3619  if ($reshook > 0) {
3620  $sql .= $hookmanager->resPrint;
3621  } else {
3622  $sql .= " WHERE u.entity IN (".getEntity('user').")";
3623  }
3624  if ($filter) {
3625  $sql .= " AND ".$filter;
3626  }
3627 
3628  dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3629  $resql = $this->db->query($sql);
3630  if ($resql) {
3631  $i = 0;
3632  while ($obj = $this->db->fetch_object($resql)) {
3633  $this->users[$obj->rowid]['rowid'] = $obj->rowid;
3634  $this->users[$obj->rowid]['id'] = $obj->rowid;
3635  $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
3636  $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
3637  $this->users[$obj->rowid]['firstname'] = $obj->firstname;
3638  $this->users[$obj->rowid]['lastname'] = $obj->lastname;
3639  $this->users[$obj->rowid]['login'] = $obj->login;
3640  $this->users[$obj->rowid]['statut'] = $obj->statut;
3641  $this->users[$obj->rowid]['entity'] = $obj->entity;
3642  $this->users[$obj->rowid]['email'] = $obj->email;
3643  $this->users[$obj->rowid]['gender'] = $obj->gender;
3644  $this->users[$obj->rowid]['admin'] = $obj->admin;
3645  $this->users[$obj->rowid]['photo'] = $obj->photo;
3646  $i++;
3647  }
3648  } else {
3649  dol_print_error($this->db);
3650  return -1;
3651  }
3652 
3653  // We add the fullpath property to each elements of first level (no parent exists)
3654  dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3655  foreach ($this->users as $key => $val) {
3656  $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3657  if ($result < 0) {
3658  $this->error = 'ErrorLoopInHierarchy';
3659  return -1;
3660  }
3661  }
3662 
3663  // Exclude leaf including $deleteafterid from tree
3664  if ($deleteafterid) {
3665  //print "Look to discard user ".$deleteafterid."\n";
3666  $keyfilter1 = '^'.$deleteafterid.'$';
3667  $keyfilter2 = '_'.$deleteafterid.'$';
3668  $keyfilter3 = '^'.$deleteafterid.'_';
3669  $keyfilter4 = '_'.$deleteafterid.'_';
3670  foreach ($this->users as $key => $val) {
3671  if (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath'])
3672  || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])) {
3673  unset($this->users[$key]);
3674  }
3675  }
3676  }
3677 
3678  dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
3679  $this->users = dol_sort_array($this->users, 'fullname', 'asc', true, false);
3680 
3681  //var_dump($this->users);
3682 
3683  return $this->users;
3684  }
3685 
3694  public function getAllChildIds($addcurrentuser = 0)
3695  {
3696  $childids = array();
3697 
3698  if (isset($this->cache_childids[$this->id])) {
3699  $childids = $this->cache_childids[$this->id];
3700  } else {
3701  // Init this->users
3702  $this->get_full_tree();
3703 
3704  $idtoscan = $this->id;
3705 
3706  dol_syslog("Build childid for id = ".$idtoscan);
3707  foreach ($this->users as $id => $val) {
3708  //var_dump($val['fullpath']);
3709  if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
3710  $childids[$val['id']] = $val['id'];
3711  }
3712  }
3713  }
3714  $this->cache_childids[$this->id] = $childids;
3715 
3716  if ($addcurrentuser) {
3717  $childids[$this->id] = $this->id;
3718  }
3719 
3720  return $childids;
3721  }
3722 
3723  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3732  public function build_path_from_id_user($id_user, $protection = 0)
3733  {
3734  // phpcs:enable
3735  //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
3736 
3737  if (!empty($this->users[$id_user]['fullpath'])) {
3738  // Already defined
3739  dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
3740  return 0;
3741  }
3742 
3743  // Define fullpath and fullname
3744  $this->users[$id_user]['fullpath'] = '_'.$id_user;
3745  $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
3746  $i = 0; $cursor_user = $id_user;
3747 
3748  $useridfound = array($id_user);
3749  while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) {
3750  if (in_array($this->parentof[$cursor_user], $useridfound)) {
3751  dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
3752  return -1; // Should not happen. Protection against looping hierarchy
3753  }
3754  $useridfound[] = $this->parentof[$cursor_user];
3755  $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
3756  $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
3757  $i++; $cursor_user = $this->parentof[$cursor_user];
3758  }
3759 
3760  // We count number of _ to have level
3761  $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
3762 
3763  return 1;
3764  }
3765 
3774  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3775  {
3776  $tables = array(
3777  'user',
3778  );
3779 
3780  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3781  }
3782 
3783 
3784  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3790  public function load_state_board()
3791  {
3792  // phpcs:enable
3793  global $conf;
3794 
3795  $this->nb = array();
3796 
3797  $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
3798  $sql .= " FROM ".$this->db->prefix()."user as u";
3799  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
3800  $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
3801  $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
3802  $sql .= " AND ug.fk_user = u.rowid";
3803  } else {
3804  $sql .= " WHERE u.entity IN (".getEntity('user').")";
3805  }
3806  $sql .= " AND u.statut > 0";
3807  //$sql.= " AND employee != 0";
3808 
3809  $resql = $this->db->query($sql);
3810  if ($resql) {
3811  while ($obj = $this->db->fetch_object($resql)) {
3812  $this->nb["users"] = $obj->nb;
3813  }
3814  $this->db->free($resql);
3815  return 1;
3816  } else {
3817  dol_print_error($this->db);
3818  $this->error = $this->db->error();
3819  return -1;
3820  }
3821  }
3822 
3834  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3835  {
3836  global $conf, $user, $langs;
3837 
3838  $langs->load("user");
3839 
3840  // Positionne le modele sur le nom du modele a utiliser
3841  if (!dol_strlen($modele)) {
3842  if (!empty($conf->global->USER_ADDON_PDF)) {
3843  $modele = $conf->global->USER_ADDON_PDF;
3844  } else {
3845  $modele = 'bluesky';
3846  }
3847  }
3848 
3849  $modelpath = "core/modules/user/doc/";
3850 
3851  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3852  }
3853 
3854  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3862  public function user_get_property($rowid, $mode)
3863  {
3864  // phpcs:enable
3865  $user_property = '';
3866 
3867  if (empty($rowid)) {
3868  return '';
3869  }
3870 
3871  $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
3872  $sql .= " FROM ".$this->db->prefix()."user";
3873  $sql .= " WHERE rowid = ".((int) $rowid);
3874 
3875  $resql = $this->db->query($sql);
3876  if ($resql) {
3877  $nump = $this->db->num_rows($resql);
3878 
3879  if ($nump) {
3880  $obj = $this->db->fetch_object($resql);
3881 
3882  if ($mode == 'email') {
3883  $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
3884  } elseif ($mode == 'mobile') {
3885  $user_property = $obj->user_mobile;
3886  }
3887  }
3888  return $user_property;
3889  } else {
3890  dol_print_error($this->db);
3891  }
3892 
3893  return '';
3894  }
3895 
3903  public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
3904  {
3905  global $dolibarr_main_url_root;
3906  global $conf;
3907 
3908  $encodedsecurekey = dol_hash($conf->file->instance_unique_id.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
3909  if (isModEnabled('multicompany')) {
3910  $entity_qr = '&entity='.((int) $conf->entity);
3911  } else {
3912  $entity_qr = '';
3913  }
3914  // Define $urlwithroot
3915  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
3916  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
3917  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
3918 
3919  if ($typeofurl == 'internal') {
3920  $urlwithroot = DOL_URL_ROOT;
3921  }
3922 
3923  return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
3924  }
3925 
3938  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = array(), $filtermode = 'AND', $entityfilter = false)
3939  {
3940  global $conf, $user;
3941 
3942  $sql = "SELECT t.rowid";
3943  $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
3944 
3945  if ($entityfilter) {
3946  if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
3947  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
3948  $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
3949  } else {
3950  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
3951  $sql .= " WHERE ((ug.fk_user = t.rowid";
3952  $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
3953  $sql .= " OR t.entity = 0)"; // Show always superadmin
3954  }
3955  } else {
3956  $sql .= " WHERE t.entity IN (".getEntity('user').")";
3957  }
3958  } else {
3959  $sql .= " WHERE 1 = 1";
3960  }
3961 
3962  // Manage filter
3963  $sqlwhere = array();
3964  if (!empty($filter)) {
3965  foreach ($filter as $key => $value) {
3966  if ($key == 't.rowid') {
3967  $sqlwhere[] = $key." = ".((int) $value);
3968  } elseif (isset($this->fields[$key]['type']) && in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
3969  $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
3970  } elseif ($key == 'customsql') {
3971  $sqlwhere[] = $value;
3972  } else {
3973  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
3974  }
3975  }
3976  }
3977  if (count($sqlwhere) > 0) {
3978  $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
3979  }
3980  $sql .= $this->db->order($sortfield, $sortorder);
3981  if ($limit) {
3982  $sql .= $this->db->plimit($limit + 1, $offset);
3983  }
3984 
3985  dol_syslog(__METHOD__, LOG_DEBUG);
3986 
3987  $resql = $this->db->query($sql);
3988  if ($resql) {
3989  $this->users = array();
3990  $num = $this->db->num_rows($resql);
3991  if ($num) {
3992  while ($obj = $this->db->fetch_object($resql)) {
3993  $line = new self($this->db);
3994  $result = $line->fetch($obj->rowid);
3995  if ($result > 0 && !empty($line->id)) {
3996  $this->users[$obj->rowid] = clone $line;
3997  }
3998  }
3999  $this->db->free($resql);
4000  }
4001  return $num;
4002  } else {
4003  $this->errors[] = $this->db->lasterror();
4004  return -1;
4005  }
4006  }
4007 
4015  private $findUserIdByEmailCache;
4016 
4027  public function findUserIdByEmail($email)
4028  {
4029  if (isset($this->findUserIdByEmailCache[$email])) {
4030  return $this->findUserIdByEmailCache[$email];
4031  }
4032 
4033  $this->findUserIdByEmailCache[$email] = -1;
4034 
4035  global $conf;
4036 
4037  $sql = 'SELECT rowid';
4038  $sql .= ' FROM '.$this->db->prefix().'user';
4039  if (!empty($conf->global->AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR)) {
4040  $sql .= " WHERE email LIKE '%".$this->db->escape($email)."%'";
4041  } else {
4042  $sql .= " WHERE email = '".$this->db->escape($email)."'";
4043  }
4044  $sql .= ' LIMIT 1';
4045 
4046  $resql = $this->db->query($sql);
4047  if (!$resql) {
4048  return -1;
4049  }
4050 
4051  $obj = $this->db->fetch_object($resql);
4052  if (!$obj) {
4053  return -1;
4054  }
4055 
4056  $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4057 
4058  return $this->findUserIdByEmailCache[$email];
4059  }
4060 }
User\error
error()
Renvoie la derniere erreur fonctionnelle de manipulation de l'objet.
Definition: user.class.php:2518
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:51
dol_get_last_hour
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
Definition: date.lib.php:622
yn
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
Definition: functions.lib.php:6812
User\loadParentOf
loadParentOf()
Load this->parentof that is array(id_son=>id_parent, ...)
Definition: user.class.php:3560
dol_trunc
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
Definition: functions.lib.php:4049
User\getLibStatut
getLibStatut($mode=0)
Return the label of the status of user (active, inactive)
Definition: user.class.php:3049
User\getNbOfEMailings
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
Definition: user.class.php:3412
User\__construct
__construct($db)
Constructor of the class.
Definition: user.class.php:383
User\SetInGroup
SetInGroup($group, $entity, $notrigger=0)
Add user into a group.
Definition: user.class.php:2605
User\isNotIntoValidityDateRange
isNotIntoValidityDateRange()
Return a link with photo Use this->id,this->photo.
Definition: user.class.php:2716
User\update_last_login_date
update_last_login_date()
Mise a jour en base de la date de derniere connexion d'un utilisateur Fonction appelee lors d'une nou...
Definition: user.class.php:2221
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
User\update_clicktodial
update_clicktodial()
Update clicktodial info.
Definition: user.class.php:2564
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:5096
dol_sort_array
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...
Definition: functions.lib.php:8893
User\LibStatut
LibStatut($status, $mode=0)
Return the label of a status of user (active, inactive)
Definition: user.class.php:3062
dol_verifyHash
dol_verifyHash($chain, $hash, $type='0')
Compute a hash and compare it to the given one For backward compatibility reasons,...
Definition: security.lib.php:267
UserGroup
Class to manage user groups.
Definition: usergroup.class.php:40
Translate
Class to manage translations.
Definition: translate.class.php:30
User\getOnlineVirtualCardUrl
getOnlineVirtualCardUrl($mode='', $typeofurl='external')
Return string with full Url to virtual card.
Definition: user.class.php:3903
User\replaceThirdparty
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: user.class.php:3774
picto_from_langcode
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
Definition: functions.lib.php:9276
CMailFile
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Definition: CMailFile.class.php:41
User\getLoginUrl
getLoginUrl($withpictoimg=0, $option='', $notooltip=0, $morecss='')
Return clickable link of login (eventualy with picto)
Definition: user.class.php:2998
User\getNomUrl
getNomUrl($withpictoimg=0, $option='', $infologin=0, $notooltip=0, $maxlen=24, $hidethirdpartylogo=0, $mode='', $morecss='', $save_lastsearch_value=-1)
Return a HTML link to the user card (with optionaly the picto) Use this->id,this->lastname,...
Definition: user.class.php:2865
User\fetch
fetch($id='', $login='', $sid='', $loadpersonalconf=0, $entity=-1, $email='', $fk_socpeople=0)
Load a user from database with its id or ref (login).
Definition: user.class.php:422
User\get_children
get_children()
Return and array with all instanciated first level children users of current user.
Definition: user.class.php:3532
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:45
User\fetch_clicktodial
fetch_clicktodial()
Read clicktodial information for user.
Definition: user.class.php:2530
User\delrights
delrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0)
Remove a right to the user.
Definition: user.class.php:988
getArrayOfSocialNetworks
getArrayOfSocialNetworks()
Get array of social network dictionary.
Definition: functions.lib.php:3233
User\RemoveFromGroup
RemoveFromGroup($group, $entity, $notrigger=0)
Remove a user from a group.
Definition: user.class.php:2662
User\getAllChildIds
getAllChildIds($addcurrentuser=0)
Return list of all child users id in herarchy (all sublevels).
Definition: user.class.php:3694
getRandomPassword
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
Definition: security2.lib.php:482
User\set_default_rights
set_default_rights()
Assign rights by default.
Definition: user.class.php:1825
User\setstatus
setstatus($status)
Change status of a user.
Definition: user.class.php:1359
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2665
User\getNbOfUsers
getNbOfUsers($limitTo, $option='', $admin=-1)
Return number of existing users.
Definition: user.class.php:3440
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:4125
User\loadDefaultValues
loadDefaultValues()
Load default values from database table into property ->default_values.
Definition: user.class.php:658
dolGetLdapPasswordHash
dolGetLdapPasswordHash($password, $type='md5')
Returns a specific ldap hash of a password.
Definition: security.lib.php:293
dol_hash
dol_hash($chain, $type='0')
Returns a hash (non reversible encryption) of a string.
Definition: security.lib.php:219
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6110
User\findUserIdByEmail
findUserIdByEmail($email)
Find a user by the given e-mail and return it's user id when found.
Definition: user.class.php:4027
$sql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
User\$clicktodial_url
$clicktodial_url
@string clicktodial url
Definition: user.class.php:251
dol_get_first_hour
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition: date.lib.php:636
User\build_path_from_id_user
build_path_from_id_user($id_user, $protection=0)
For user id_user and its childs available in this->users, define property fullpath and fullname.
Definition: user.class.php:3732
User\info
info($id)
Load info of user object.
Definition: user.class.php:3380
dol_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:7034
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1732
conf
conf($dolibarr_main_document_root)
Load conf file (file must exists)
Definition: inc.php:400
Contact
Class to manage contact/addresses.
Definition: contact.class.php:42
User\getrights
getrights($moduletag='', $forcereload=0)
Load permissions granted to user into object user.
Definition: user.class.php:1123
dolEncrypt
dolEncrypt($chain, $key='', $ciphering='AES-256-CTR', $forceseed='')
Encode a string with a symetric encryption.
Definition: security.lib.php:121
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
Definition: functions.lib.php:8644
User\getKanbanView
getKanbanView($option='', $arraydata=null)
Return clicable link of object (with eventually picto)
Definition: user.class.php:3092
User\load_state_board
load_state_board()
Load metrics this->nb for dashboard.
Definition: user.class.php:3790
Adherent
Class to manage members of a foundation.
Definition: adherent.class.php:47
User\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
Definition: user.class.php:3834
CommonObject\fetch_optionals
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
Definition: commonobject.class.php:5959
User\initAsSpecimen
initAsSpecimen()
Initialise an instance with random values.
Definition: user.class.php:3327
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3987
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:207
dolGetFirstLastname
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
Definition: functions.lib.php:8561
ref
$object ref
Definition: info.php:78
DefaultValues
Class for MyObject.
Definition: defaultvalues.class.php:33
getDolGlobalString
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:142
User
Class to manage Dolibarr users.
Definition: user.class.php:47
User\setCategories
setCategories($categories)
Sets object to supplied categories.
Definition: user.class.php:1413
CommonObject\deleteExtraFields
deleteExtraFields()
Delete all extra fields values for the current object.
Definition: commonobject.class.php:6070
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10932
User\create_from_contact
create_from_contact($contact, $login='', $password='')
Create a user from a contact object.
Definition: user.class.php:1655
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4462
User\fetchAll
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter=array(), $filtermode='AND', $entityfilter=false)
Load all objects into $this->users.
Definition: user.class.php:3938
User\create_from_member
create_from_member($member, $login='')
Create a user into database from a member object.
Definition: user.class.php:1739
Entrepot
Class to manage warehouses.
Definition: entrepot.class.php:35
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:3046
dolDecrypt
dolDecrypt($chain, $key='')
Decode a string with a symetric encryption.
Definition: security.lib.php:175
User\_load_ldap_dn
_load_ldap_dn($info, $mode=0)
Retourne chaine DN complete dans l'annuaire LDAP pour l'objet.
Definition: user.class.php:3144
User\send_password
send_password($user, $password='', $changelater=0)
Send a new password (or instructions to reset it) by email.
Definition: user.class.php:2403
User\hasRight
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
Definition: user.class.php:708
User\user_get_property
user_get_property($rowid, $mode)
Return property of user from its id.
Definition: user.class.php:3862
dol_print_phone
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0)
Format phone numbers according to country.
Definition: functions.lib.php:3391
Form\showphoto
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Definition: html.form.class.php:9618
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5743
User\clearrights
clearrights()
Clear all permissions array of user.
Definition: user.class.php:1105
User\_load_ldap_info
_load_ldap_info()
Initialize the info array (array of LDAP values) that will be used to call LDAP functions.
Definition: user.class.php:3166
getDolGlobalInt
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
Definition: functions.lib.php:156
User\getTooltipContentArray
getTooltipContentArray($params)
Return array of data to show into tooltips.
Definition: user.class.php:2763
User\create
create($user, $notrigger=0)
Create a user into database.
Definition: user.class.php:1512
CommonObject\commonReplaceThirdparty
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
Definition: commonobject.class.php:8469
dol_buildlogin
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
Definition: functions2.lib.php:2045
User\update_ldap2dolibarr
update_ldap2dolibarr(&$ldapuser)
Update user using data from the LDAP.
Definition: user.class.php:3478
User\setPassword
setPassword($user, $password='', $changelater=0, $notrigger=0, $nosyncmember=0, $passwordalreadycrypted=0, $flagdelsessionsbefore=1)
Change password of a user.
Definition: user.class.php:2263
User\addrights
addrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0)
Add a right to the user.
Definition: user.class.php:844
User\get_full_tree
get_full_tree($deleteafterid=0, $filter='')
Build the hierarchy/tree of users into an array.
Definition: user.class.php:3599
getUserRemoteIP
getUserRemoteIP()
Return the IP of remote user.
Definition: functions.lib.php:3732
User\getPhotoUrl
getPhotoUrl($width, $height, $cssclass='', $imagesize='')
Return a link with photo Use this->id,this->photo.
Definition: user.class.php:2747
User\update
update($user, $notrigger=0, $nosyncmember=0, $nosyncmemberpass=0, $nosynccontact=0)
Update a user into database (and also password if this->pass is defined)
Definition: user.class.php:1873