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