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