dolibarr  18.0.6
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 (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1146  $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1147  }
1148  if ($moduletag) {
1149  $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1150  }
1151 
1152  $resql = $this->db->query($sql);
1153  if ($resql) {
1154  $num = $this->db->num_rows($resql);
1155  $i = 0;
1156  while ($i < $num) {
1157  $obj = $this->db->fetch_object($resql);
1158 
1159  if ($obj) {
1160  $module = $obj->module;
1161  $perms = $obj->perms;
1162  $subperms = $obj->subperms;
1163 
1164  if (!empty($perms)) {
1165  if (!empty($module)) {
1166  if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1167  $this->rights->$module = new stdClass();
1168  }
1169  if (!empty($subperms)) {
1170  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1171  $this->rights->$module->$perms = new stdClass();
1172  }
1173  if (empty($this->rights->$module->$perms->$subperms)) {
1174  $this->nb_rights++;
1175  }
1176  $this->rights->$module->$perms->$subperms = 1;
1177  } else {
1178  if (empty($this->rights->$module->$perms)) {
1179  $this->nb_rights++;
1180  }
1181  $this->rights->$module->$perms = 1;
1182  }
1183  }
1184  }
1185  }
1186  $i++;
1187  }
1188  $this->db->free($resql);
1189  }
1190 
1191  // Now permissions of groups
1192  $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1193  $sql .= " FROM ".$this->db->prefix()."usergroup_rights as gr,";
1194  $sql .= " ".$this->db->prefix()."usergroup_user as gu,";
1195  $sql .= " ".$this->db->prefix()."rights_def as r";
1196  $sql .= " WHERE r.id = gr.fk_id";
1197  // A very strange business rules. Must be same than into user->getrights() user/perms.php and user/group/perms.php
1198  if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
1199  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1200  $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1201  } else {
1202  $sql .= " AND r.entity = ".((int) $conf->entity);
1203  }
1204  } else {
1205  $sql .= " AND gr.entity = ".((int) $conf->entity); // Only groups created in current entity
1206  // The entity on the table usergroup_user should be useless and should never be used because it is alreay into gr and r.
1207  // but when using MULTICOMPANY_TRANSVERSE_MODE, we may insert record that make rubbish result due to duplicate record of
1208  // other entities, so we are forced to add a filter here
1209  $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1210  $sql .= " AND r.entity = ".((int) $conf->entity); // Only permission of modules enabled in current entity
1211  }
1212  // End of strange business rule
1213  $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
1214  $sql .= " AND gu.fk_user = ".((int) $this->id);
1215  $sql .= " AND r.perms IS NOT NULL";
1216  if ($moduletag) {
1217  $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1218  }
1219 
1220  $resql = $this->db->query($sql);
1221  if ($resql) {
1222  $num = $this->db->num_rows($resql);
1223  $i = 0;
1224  while ($i < $num) {
1225  $obj = $this->db->fetch_object($resql);
1226 
1227  if ($obj) {
1228  $module = $obj->module;
1229  $perms = $obj->perms;
1230  $subperms = $obj->subperms;
1231 
1232  if (!empty($perms)) {
1233  if (!empty($module)) {
1234  if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1235  $this->rights->$module = new stdClass();
1236  }
1237  if (!empty($subperms)) {
1238  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1239  $this->rights->$module->$perms = new stdClass();
1240  }
1241  if (empty($this->rights->$module->$perms->$subperms)) {
1242  $this->nb_rights++;
1243  }
1244  $this->rights->$module->$perms->$subperms = 1;
1245  } else {
1246  if (empty($this->rights->$module->$perms)) {
1247  $this->nb_rights++;
1248  }
1249  // 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
1250  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1251  $this->rights->$module->$perms = 1;
1252  }
1253  }
1254  }
1255  }
1256  }
1257  $i++;
1258  }
1259  $this->db->free($resql);
1260  }
1261 
1262  // Force permission on user for admin
1263  if (!empty($this->admin)) {
1264  if (empty($this->rights->user->user)) {
1265  $this->rights->user->user = new stdClass();
1266  }
1267  $listofpermtotest = array('lire', 'creer', 'password', 'supprimer', 'export');
1268  foreach ($listofpermtotest as $permtotest) {
1269  if (empty($this->rights->user->user->$permtotest)) {
1270  $this->rights->user->user->$permtotest = 1;
1271  $this->nb_rights++;
1272  }
1273  }
1274  if (empty($this->rights->user->self)) {
1275  $this->rights->user->self = new stdClass();
1276  }
1277  $listofpermtotest = array('creer', 'password');
1278  foreach ($listofpermtotest as $permtotest) {
1279  if (empty($this->rights->user->self->$permtotest)) {
1280  $this->rights->user->self->$permtotest = 1;
1281  $this->nb_rights++;
1282  }
1283  }
1284  // Add test on advanced permissions
1285  if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
1286  if (empty($this->rights->user->user_advance)) {
1287  $this->rights->user->user_advance = new stdClass();
1288  }
1289  $listofpermtotest = array('readperms', 'write');
1290  foreach ($listofpermtotest as $permtotest) {
1291  if (empty($this->rights->user->user_advance->$permtotest)) {
1292  $this->rights->user->user_advance->$permtotest = 1;
1293  $this->nb_rights++;
1294  }
1295  }
1296  if (empty($this->rights->user->self_advance)) {
1297  $this->rights->user->self_advance = new stdClass();
1298  }
1299  $listofpermtotest = array('readperms', 'writeperms');
1300  foreach ($listofpermtotest as $permtotest) {
1301  if (empty($this->rights->user->self_advance->$permtotest)) {
1302  $this->rights->user->self_advance->$permtotest = 1;
1303  $this->nb_rights++;
1304  }
1305  }
1306  if (empty($this->rights->user->group_advance)) {
1307  $this->rights->user->group_advance = new stdClass();
1308  }
1309  $listofpermtotest = array('read', 'readperms', 'write', 'delete');
1310  foreach ($listofpermtotest as $permtotest) {
1311  if (empty($this->rights->user) || empty($this->rights->user->group_advance->$permtotest)) {
1312  $this->rights->user->group_advance->$permtotest = 1;
1313  $this->nb_rights++;
1314  }
1315  }
1316  }
1317  }
1318 
1319  // For backward compatibility
1320  if (isset($this->rights->propale) && !isset($this->rights->propal)) {
1321  $this->rights->propal = $this->rights->propale;
1322  }
1323  if (isset($this->rights->propal) && !isset($this->rights->propale)) {
1324  $this->rights->propale = $this->rights->propal;
1325  }
1326 
1327  if (!$moduletag) {
1328  // Si module etait non defini, alors on a tout charge, on peut donc considerer
1329  // que les droits sont en cache (car tous charges) pour cet instance de user
1330  $this->all_permissions_are_loaded = 1;
1331  } else {
1332  // If module defined, we flag it as loaded into cache
1333  $this->_tab_loaded[$moduletag] = 1;
1334  }
1335  }
1336 
1343  public function setstatus($status)
1344  {
1345  global $conf, $langs, $user;
1346 
1347  $error = 0;
1348 
1349  // Check parameters
1350  if (isset($this->statut)) {
1351  if ($this->statut == $status) {
1352  return 0;
1353  }
1354  } elseif (isset($this->status) && $this->status == $status) {
1355  return 0;
1356  }
1357 
1358  $this->db->begin();
1359 
1360  // Save in database
1361  $sql = "UPDATE ".$this->db->prefix()."user";
1362  $sql .= " SET statut = ".((int) $status);
1363  $sql .= " WHERE rowid = ".((int) $this->id);
1364  $result = $this->db->query($sql);
1365 
1366  dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1367  if ($result) {
1368  if ($status == 0) {
1369  $this->context['actionmsg'] = 'User '.$this->login.' disabled';
1370  } else {
1371  $this->context['actionmsg'] = 'User '.$this->login.' enabled';
1372  }
1373  // Call trigger
1374  $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
1375  if ($result < 0) {
1376  $error++;
1377  }
1378  // End call triggers
1379  }
1380 
1381  if ($error) {
1382  $this->db->rollback();
1383  return -$error;
1384  } else {
1385  $this->status = $status;
1386  $this->statut = $status;
1387  $this->db->commit();
1388  return 1;
1389  }
1390  }
1391 
1402  public function setCategories($categories)
1403  {
1404  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1405  return parent::setCategoriesCommon($categories, Categorie::TYPE_USER);
1406  }
1407 
1414  public function delete(User $user)
1415  {
1416  global $conf, $langs;
1417 
1418  $error = 0;
1419 
1420  $this->db->begin();
1421 
1422  $this->fetch($this->id);
1423 
1424  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1425 
1426  // Remove rights
1427  $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1428 
1429  if (!$error && !$this->db->query($sql)) {
1430  $error++;
1431  $this->error = $this->db->lasterror();
1432  }
1433 
1434  // Remove group
1435  $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1436  if (!$error && !$this->db->query($sql)) {
1437  $error++;
1438  $this->error = $this->db->lasterror();
1439  }
1440 
1441  // Remove params
1442  $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1443  if (!$error && !$this->db->query($sql)) {
1444  $error++;
1445  $this->error = $this->db->lasterror();
1446  }
1447 
1448  // If contact, remove link
1449  if ($this->contact_id > 0) {
1450  $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1451  if (!$error && !$this->db->query($sql)) {
1452  $error++;
1453  $this->error = $this->db->lasterror();
1454  }
1455  }
1456 
1457  // Remove extrafields
1458  if (!$error) {
1459  $result = $this->deleteExtraFields();
1460  if ($result < 0) {
1461  $error++;
1462  dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1463  }
1464  }
1465 
1466  // Remove user
1467  if (!$error) {
1468  $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1469  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1470  if (!$this->db->query($sql)) {
1471  $error++;
1472  $this->error = $this->db->lasterror();
1473  }
1474  }
1475 
1476  if (!$error) {
1477  // Call trigger
1478  $result = $this->call_trigger('USER_DELETE', $user);
1479  if ($result < 0) {
1480  $error++;
1481  $this->db->rollback();
1482  return -1;
1483  }
1484  // End call triggers
1485 
1486  $this->db->commit();
1487  return 1;
1488  } else {
1489  $this->db->rollback();
1490  return -1;
1491  }
1492  }
1493 
1501  public function create($user, $notrigger = 0)
1502  {
1503  global $conf, $langs;
1504  global $mysoc;
1505 
1506  // Clean parameters
1507  $this->setUpperOrLowerCase();
1508 
1509  $this->civility_code = trim((string) $this->civility_code);
1510  $this->login = trim((string) $this->login);
1511  if (!isset($this->entity)) {
1512  $this->entity = $conf->entity; // If not defined, we use default value
1513  }
1514 
1515  dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1516 
1517  $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1518 
1519  // Check parameters
1520  if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
1521  $langs->load("errors");
1522  $this->error = $langs->trans("ErrorBadEMail", $this->email);
1523  return -1;
1524  }
1525  if (empty($this->login)) {
1526  $langs->load("errors");
1527  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1528  return -1;
1529  } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1530  $langs->load("errors");
1531  $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1532  return -1;
1533  }
1534 
1535  $this->datec = dol_now();
1536 
1537  $error = 0;
1538  $this->db->begin();
1539 
1540  // Check if login already exists in same entity or into entity 0.
1541  if ($this->login) {
1542  $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)."'";
1543  $resqltochecklogin = $this->db->query($sqltochecklogin);
1544  if ($resqltochecklogin) {
1545  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1546  if ($objtochecklogin && $objtochecklogin->nb > 0) {
1547  $langs->load("errors");
1548  $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1549  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1550  $this->db->rollback();
1551  return -6;
1552  }
1553  $this->db->free($resqltochecklogin);
1554  }
1555  }
1556  if (!empty($this->email)) {
1557  $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)."'";
1558  $resqltochecklogin = $this->db->query($sqltochecklogin);
1559  if ($resqltochecklogin) {
1560  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1561  if ($objtochecklogin && $objtochecklogin->nb > 0) {
1562  $langs->load("errors");
1563  $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1564  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1565  $this->db->rollback();
1566  return -6;
1567  }
1568  $this->db->free($resqltochecklogin);
1569  }
1570  }
1571 
1572  // Insert into database
1573  $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, entity)";
1574  $sql .= " VALUES('".$this->db->idate($this->datec)."', '".$this->db->escape($this->login)."', '".$this->db->escape($this->ldap_sid)."', ".((int) $this->entity).")";
1575  $result = $this->db->query($sql);
1576 
1577  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1578  if ($result) {
1579  $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1580 
1581  // Set default rights
1582  if ($this->set_default_rights() < 0) {
1583  $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1584  $this->db->rollback();
1585  return -5;
1586  }
1587 
1588  if (!empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER) && !empty($conf->global->STOCK_USERSTOCK_AUTOCREATE)) {
1589  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1590  $langs->load("stocks");
1591  $entrepot = new Entrepot($this->db);
1592  $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1593  $entrepot->libelle = $entrepot->label; // For backward compatibility
1594  $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1595  $entrepot->statut = 1;
1596  $entrepot->country_id = $mysoc->country_id;
1597  $warehouseid = $entrepot->create($user);
1598 
1599  $this->fk_warehouse = $warehouseid;
1600  }
1601 
1602  // Update minor fields
1603  $result = $this->update($user, 1, 1);
1604  if ($result < 0) {
1605  $this->db->rollback();
1606  return -4;
1607  }
1608 
1609  if (!$notrigger) {
1610  // Call trigger
1611  $result = $this->call_trigger('USER_CREATE', $user);
1612  if ($result < 0) {
1613  $error++;
1614  }
1615  // End call triggers
1616  }
1617 
1618  if (!$error) {
1619  $this->db->commit();
1620  return $this->id;
1621  } else {
1622  //$this->error=$interface->error;
1623  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1624  $this->db->rollback();
1625  return -3;
1626  }
1627  } else {
1628  $this->error = $this->db->lasterror();
1629  $this->db->rollback();
1630  return -2;
1631  }
1632  }
1633 
1634 
1635  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1644  public function create_from_contact($contact, $login = '', $password = '')
1645  {
1646  // phpcs:enable
1647  global $conf, $user, $langs;
1648 
1649  $error = 0;
1650 
1651  // Define parameters
1652  $this->admin = 0;
1653  $this->civility_code = $contact->civility_code;
1654  $this->lastname = $contact->lastname;
1655  $this->firstname = $contact->firstname;
1656  //$this->gender = $contact->gender; // contact ha sno gender
1657  $this->email = $contact->email;
1658  $this->socialnetworks = $contact->socialnetworks;
1659  $this->office_phone = $contact->phone_pro;
1660  $this->office_fax = $contact->fax;
1661  $this->user_mobile = $contact->phone_mobile;
1662  $this->address = $contact->address;
1663  $this->zip = $contact->zip;
1664  $this->town = $contact->town;
1665  $this->setUpperOrLowerCase();
1666  $this->state_id = $contact->state_id;
1667  $this->country_id = $contact->country_id;
1668  $this->employee = 0;
1669 
1670  if (empty($login)) {
1671  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1672  $login = dol_buildlogin($contact->lastname, $contact->firstname);
1673  }
1674  $this->login = $login;
1675 
1676  $this->db->begin();
1677 
1678  // Create user and set $this->id. Trigger is disabled because executed later.
1679  $result = $this->create($user, 1);
1680  if ($result > 0) {
1681  $sql = "UPDATE ".$this->db->prefix()."user";
1682  $sql .= " SET fk_socpeople=".((int) $contact->id);
1683  $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
1684  if ($contact->socid > 0) {
1685  $sql .= ", fk_soc=".((int) $contact->socid);
1686  }
1687  $sql .= " WHERE rowid=".((int) $this->id);
1688 
1689  $resql = $this->db->query($sql);
1690 
1691  dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1692  if ($resql) {
1693  $this->context['createfromcontact'] = 'createfromcontact';
1694 
1695  // Call trigger
1696  $result = $this->call_trigger('USER_CREATE', $user);
1697  if ($result < 0) {
1698  $error++; $this->db->rollback(); return -1;
1699  }
1700  // End call triggers
1701 
1702  $this->db->commit();
1703  return $this->id;
1704  } else {
1705  $this->error = $this->db->error();
1706 
1707  $this->db->rollback();
1708  return -1;
1709  }
1710  } else {
1711  // $this->error deja positionne
1712  dol_syslog(get_class($this)."::create_from_contact - 0");
1713 
1714  $this->db->rollback();
1715  return $result;
1716  }
1717  }
1718 
1719  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1728  public function create_from_member($member, $login = '')
1729  {
1730  // phpcs:enable
1731  global $conf, $user, $langs;
1732 
1733  // Set properties on new user
1734  $this->admin = 0;
1735  $this->civility_code = $member->civility_id;
1736  $this->lastname = $member->lastname;
1737  $this->firstname = $member->firstname;
1738  $this->gender = $member->gender;
1739  $this->email = $member->email;
1740  $this->fk_member = $member->id;
1741  $this->address = $member->address;
1742  $this->zip = $member->zip;
1743  $this->town = $member->town;
1744  $this->setUpperOrLowerCase();
1745  $this->state_id = $member->state_id;
1746  $this->country_id = $member->country_id;
1747  $this->socialnetworks = $member->socialnetworks;
1748 
1749  $this->pass = $member->pass;
1750  $this->pass_crypted = $member->pass_indatabase_crypted;
1751 
1752  if (empty($login)) {
1753  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1754  $login = dol_buildlogin($member->lastname, $member->firstname);
1755  }
1756  $this->login = $login;
1757 
1758  $this->db->begin();
1759 
1760  // Create and set $this->id
1761  $result = $this->create($user);
1762  if ($result > 0) {
1763  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
1764  $newpass = $this->setPassword($user, $this->pass);
1765  if (is_int($newpass) && $newpass < 0) {
1766  $result = -2;
1767  }
1768  } 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.
1769  $sql = "UPDATE ".$this->db->prefix()."user";
1770  $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
1771  $sql .= " WHERE rowid=".((int) $this->id);
1772 
1773  $resql = $this->db->query($sql);
1774  if (!$resql) {
1775  $result = -1;
1776  }
1777  }
1778 
1779  if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
1780  $sql = "UPDATE ".$this->db->prefix()."user";
1781  $sql .= " SET fk_soc=".((int) $member->socid);
1782  $sql .= " WHERE rowid=".((int) $this->id);
1783 
1784  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
1785  $resql = $this->db->query($sql);
1786  if ($resql) {
1787  $this->db->commit();
1788  return $this->id;
1789  } else {
1790  $this->error = $this->db->lasterror();
1791 
1792  $this->db->rollback();
1793  return -1;
1794  }
1795  }
1796  }
1797 
1798  if ($result > 0) {
1799  $this->db->commit();
1800  return $this->id;
1801  } else {
1802  // $this->error deja positionne
1803  $this->db->rollback();
1804  return -2;
1805  }
1806  }
1807 
1808  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1814  public function set_default_rights()
1815  {
1816  // phpcs:enable
1817  global $conf;
1818 
1819  $rd = array();
1820  $num = 0;
1821  $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
1822  $sql .= " WHERE bydefault = 1";
1823  $sql .= " AND entity = ".((int) $conf->entity);
1824 
1825  $resql = $this->db->query($sql);
1826  if ($resql) {
1827  $num = $this->db->num_rows($resql);
1828  $i = 0;
1829  while ($i < $num) {
1830  $row = $this->db->fetch_row($resql);
1831  $rd[$i] = $row[0];
1832  $i++;
1833  }
1834  $this->db->free($resql);
1835  }
1836  $i = 0;
1837  while ($i < $num) {
1838  $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
1839  $result = $this->db->query($sql);
1840 
1841  $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
1842  $result = $this->db->query($sql);
1843  if (!$result) {
1844  return -1;
1845  }
1846  $i++;
1847  }
1848 
1849  return $i;
1850  }
1851 
1862  public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
1863  {
1864  global $conf, $langs;
1865 
1866  $nbrowsaffected = 0;
1867  $error = 0;
1868 
1869  dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
1870 
1871  // Clean parameters
1872  $this->civility_code = trim((string) $this->civility_code);
1873  $this->lastname = trim((string) $this->lastname);
1874  $this->firstname = trim((string) $this->firstname);
1875  $this->ref_employee = trim((string) $this->ref_employee);
1876  $this->national_registration_number = trim((string) $this->national_registration_number);
1877  $this->employee = ($this->employee > 0 ? $this->employee : 0);
1878  $this->login = trim((string) $this->login);
1879  $this->gender = trim((string) $this->gender);
1880 
1881  $this->pass = trim((string) $this->pass);
1882  $this->api_key = trim((string) $this->api_key);
1883  $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
1884  $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
1885 
1886  $this->address = trim((string) $this->address);
1887  $this->zip = trim((string) $this->zip);
1888  $this->town = trim((string) $this->town);
1889 
1890  $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
1891  $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
1892  $this->office_phone = trim((string) $this->office_phone);
1893  $this->office_fax = trim((string) $this->office_fax);
1894  $this->user_mobile = trim((string) $this->user_mobile);
1895  $this->personal_mobile = trim((string) $this->personal_mobile);
1896  $this->email = trim((string) $this->email);
1897  $this->personal_email = trim((string) $this->personal_email);
1898 
1899  $this->job = trim((string) $this->job);
1900  $this->signature = trim((string) $this->signature);
1901  $this->note_public = trim((string) $this->note_public);
1902  $this->note_private = trim((string) $this->note_private);
1903  $this->openid = trim((string) $this->openid);
1904  $this->admin = ($this->admin > 0 ? $this->admin : 0);
1905 
1906  $this->accountancy_code = trim((string) $this->accountancy_code);
1907  $this->color = trim((string) $this->color);
1908  $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
1909  $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
1910 
1911  $this->birth = empty($this->birth) ? '' : $this->birth;
1912  $this->fk_warehouse = (int) $this->fk_warehouse;
1913 
1914  $this->setUpperOrLowerCase();
1915 
1916  // Check parameters
1917  $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1918 
1919  if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
1920  $langs->load("errors");
1921  $this->error = $langs->trans("ErrorBadEMail", $this->email);
1922  return -1;
1923  }
1924  if (empty($this->login)) {
1925  $langs->load("errors");
1926  $this->error = $langs->trans("ErrorFieldRequired", 'Login');
1927  return -1;
1928  } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1929  $langs->load("errors");
1930  $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1931  return -1;
1932  }
1933 
1934  $this->db->begin();
1935 
1936  // Check if login already exists in same entity or into entity 0.
1937  if (!empty($this->oldcopy) && $this->oldcopy->login != $this->login) {
1938  $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)."'";
1939  $resqltochecklogin = $this->db->query($sqltochecklogin);
1940  if ($resqltochecklogin) {
1941  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1942  if ($objtochecklogin && $objtochecklogin->nb > 0) {
1943  $langs->load("errors");
1944  $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1945  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1946  $this->db->rollback();
1947  return -1;
1948  }
1949  }
1950  }
1951  if (!empty($this->oldcopy) && !empty($this->email) && $this->oldcopy->email != $this->email) {
1952  $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)."'";
1953  $resqltochecklogin = $this->db->query($sqltochecklogin);
1954  if ($resqltochecklogin) {
1955  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1956  if ($objtochecklogin && $objtochecklogin->nb > 0) {
1957  $langs->load("errors");
1958  $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1959  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1960  $this->db->rollback();
1961  return -1;
1962  }
1963  }
1964  }
1965 
1966  // Update datas
1967  $sql = "UPDATE ".$this->db->prefix()."user SET";
1968  $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
1969  $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
1970  $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
1971  $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
1972  $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
1973  $sql .= ", employee = ".(int) $this->employee;
1974  $sql .= ", login = '".$this->db->escape($this->login)."'";
1975  $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
1976  $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman'
1977  $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
1978  if (!empty($user->admin)) {
1979  $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
1980  }
1981  $sql .= ", address = '".$this->db->escape($this->address)."'";
1982  $sql .= ", zip = '".$this->db->escape($this->zip)."'";
1983  $sql .= ", town = '".$this->db->escape($this->town)."'";
1984  $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".$this->db->escape($this->state_id)."'" : "null");
1985  $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".$this->db->escape($this->country_id)."'" : "null");
1986  $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
1987  $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
1988  $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
1989  $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
1990  $sql .= ", email = '".$this->db->escape($this->email)."'";
1991  $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
1992  $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1993  $sql .= ", job = '".$this->db->escape($this->job)."'";
1994  $sql .= ", signature = '".$this->db->escape($this->signature)."'";
1995  $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
1996  $sql .= ", color = '".$this->db->escape($this->color)."'";
1997  $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
1998  $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
1999  $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2000  $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2001  $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2002  $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2003  $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2004  $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2005  $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".$this->db->escape($this->fk_user)."'" : "null");
2006  $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".$this->db->escape($this->fk_user_expense_validator)."'" : "null");
2007  $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".$this->db->escape($this->fk_user_holiday_validator)."'" : "null");
2008  if (isset($this->thm) || $this->thm != '') {
2009  $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2010  }
2011  if (isset($this->tjm) || $this->tjm != '') {
2012  $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2013  }
2014  if (isset($this->salary) || $this->salary != '') {
2015  $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2016  }
2017  if (isset($this->salaryextra) || $this->salaryextra != '') {
2018  $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2019  }
2020  $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2021  if (!empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2022  $sql .= ", entity = ".((int) $this->entity); // entity flag can be set/unset only by an another superadmin user
2023  }
2024  $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
2025  $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
2026  $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
2027  $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2028  $sql .= " WHERE rowid = ".((int) $this->id);
2029 
2030  dol_syslog(get_class($this)."::update", LOG_DEBUG);
2031  $resql = $this->db->query($sql);
2032  if ($resql) {
2033  $nbrowsaffected += $this->db->affected_rows($resql);
2034 
2035  // Update password
2036  if (!empty($this->pass)) {
2037  if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2038  // If a new value for password is set and different than the one crypted into database
2039  $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2040  if (is_int($result) && $result < 0) {
2041  return -5;
2042  }
2043  }
2044  }
2045 
2046  // If user is linked to a member, remove old link to this member
2047  if ($this->fk_member > 0) {
2048  dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2049  $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2050  $resql = $this->db->query($sql);
2051  if (!$resql) {
2052  $this->error = $this->db->error(); $this->db->rollback(); return -5;
2053  }
2054  }
2055  // Set link to user
2056  dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2057  $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2058  $resql = $this->db->query($sql);
2059  if (!$resql) {
2060  $this->error = $this->db->error(); $this->db->rollback(); return -5;
2061  }
2062 
2063  if ($nbrowsaffected) { // If something has changed in data
2064  if ($this->fk_member > 0 && !$nosyncmember) {
2065  dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2066 
2067  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2068 
2069  // This user is linked with a member, so we also update member information
2070  // if this is an update.
2071  $adh = new Adherent($this->db);
2072  $result = $adh->fetch($this->fk_member);
2073 
2074  if ($result > 0) {
2075  $adh->civility_code = $this->civility_code;
2076  $adh->firstname = $this->firstname;
2077  $adh->lastname = $this->lastname;
2078  $adh->login = $this->login;
2079  $adh->gender = $this->gender;
2080  $adh->birth = $this->birth;
2081 
2082  $adh->pass = $this->pass;
2083 
2084  $adh->address = $this->address;
2085  $adh->town = $this->town;
2086  $adh->zip = $this->zip;
2087  $adh->state_id = $this->state_id;
2088  $adh->country_id = $this->country_id;
2089 
2090  $adh->email = $this->email;
2091 
2092  $adh->socialnetworks = $this->socialnetworks;
2093 
2094  $adh->phone = $this->office_phone;
2095  $adh->phone_mobile = $this->user_mobile;
2096 
2097  $adh->default_lang = $this->lang;
2098 
2099  $adh->user_id = $this->id;
2100  $adh->user_login = $this->login;
2101 
2102  $result = $adh->update($user, 0, 1, 0);
2103  if ($result < 0) {
2104  $this->error = $adh->error;
2105  $this->errors = $adh->errors;
2106  dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2107  $error++;
2108  }
2109  } elseif ($result < 0) {
2110  $this->error = $adh->error;
2111  $this->errors = $adh->errors;
2112  $error++;
2113  }
2114  }
2115 
2116  if ($this->contact_id > 0 && !$nosynccontact) {
2117  dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2118 
2119  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2120 
2121  // This user is linked with a contact, so we also update contact information if this is an update.
2122  $tmpobj = new Contact($this->db);
2123  $result = $tmpobj->fetch($this->contact_id);
2124 
2125  if ($result >= 0) {
2126  $tmpobj->civility_code = $this->civility_code;
2127  $tmpobj->firstname = $this->firstname;
2128  $tmpobj->lastname = $this->lastname;
2129  $tmpobj->login = $this->login;
2130  $tmpobj->gender = $this->gender;
2131  $tmpobj->birth = $this->birth;
2132 
2133  //$tmpobj->pass=$this->pass;
2134 
2135  $tmpobj->email = $this->email;
2136 
2137  $tmpobj->socialnetworks = $this->socialnetworks;
2138 
2139  $tmpobj->phone_pro = $this->office_phone;
2140  $tmpobj->phone_mobile = $this->user_mobile;
2141  $tmpobj->fax = $this->office_fax;
2142 
2143  $tmpobj->default_lang = $this->lang;
2144 
2145  $tmpobj->address = $this->address;
2146  $tmpobj->town = $this->town;
2147  $tmpobj->zip = $this->zip;
2148  $tmpobj->state_id = $this->state_id;
2149  $tmpobj->country_id = $this->country_id;
2150 
2151  $tmpobj->user_id = $this->id;
2152  $tmpobj->user_login = $this->login;
2153 
2154  $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2155  if ($result < 0) {
2156  $this->error = $tmpobj->error;
2157  $this->errors = $tmpobj->errors;
2158  dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2159  $error++;
2160  }
2161  } else {
2162  $this->error = $tmpobj->error;
2163  $this->errors = $tmpobj->errors;
2164  $error++;
2165  }
2166  }
2167  }
2168 
2169  $action = 'update';
2170 
2171  // Actions on extra fields
2172  if (!$error) {
2173  $result = $this->insertExtraFields();
2174  if ($result < 0) {
2175  $error++;
2176  }
2177  }
2178 
2179  if (!$error && !$notrigger) {
2180  // Call trigger
2181  $result = $this->call_trigger('USER_MODIFY', $user);
2182  if ($result < 0) {
2183  $error++;
2184  }
2185  // End call triggers
2186  }
2187 
2188  if (!$error) {
2189  $this->db->commit();
2190  return $nbrowsaffected;
2191  } else {
2192  dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2193  $this->db->rollback();
2194  return -1;
2195  }
2196  } else {
2197  $this->error = $this->db->lasterror();
2198  $this->db->rollback();
2199  return -2;
2200  }
2201  }
2202 
2203  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2210  public function update_last_login_date()
2211  {
2212  // phpcs:enable
2213  $now = dol_now();
2214 
2215  $userremoteip = getUserRemoteIP();
2216 
2217  $sql = "UPDATE ".$this->db->prefix()."user SET";
2218  $sql .= " datepreviouslogin = datelastlogin,";
2219  $sql .= " ippreviouslogin = iplastlogin,";
2220  $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2221  $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2222  $sql .= " tms = tms"; // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
2223  $sql .= " WHERE rowid = ".((int) $this->id);
2224 
2225  dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2226  $resql = $this->db->query($sql);
2227  if ($resql) {
2228  $this->datepreviouslogin = $this->datelastlogin;
2229  $this->datelastlogin = $now;
2230  $this->ippreviouslogin = $this->iplastlogin;
2231  $this->iplastlogin = $userremoteip;
2232  return 1;
2233  } else {
2234  $this->error = $this->db->lasterror().' sql='.$sql;
2235  return -1;
2236  }
2237  }
2238 
2239 
2252  public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2253  {
2254  global $conf, $langs;
2255  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2256 
2257  $error = 0;
2258 
2259  dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2260 
2261  // If new password not provided, we generate one
2262  if (!$password) {
2263  $password = getRandomPassword(false);
2264  }
2265 
2266  // Check and encrypt the password
2267  if (empty($passwordalreadycrypted)) {
2268  if (!empty($conf->global->USER_PASSWORD_GENERATED)) {
2269  // Add a check on rules for password syntax using the setup of the password generator
2270  $modGeneratePassClass = 'modGeneratePass'.ucfirst($conf->global->USER_PASSWORD_GENERATED);
2271 
2272  include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2273  if (class_exists($modGeneratePassClass)) {
2274  $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2275 
2276  // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2277  $modGeneratePass->WithoutAmbi = 0;
2278 
2279  // Call to validatePassword($password) to check pass match rules
2280  $testpassword = $modGeneratePass->validatePassword($password);
2281  if (!$testpassword) {
2282  $this->error = $modGeneratePass->error;
2283  return -1;
2284  }
2285  }
2286  }
2287 
2288 
2289  // Now, we encrypt the new password
2290  $password_crypted = dol_hash($password);
2291  }
2292 
2293  // Update password
2294  if (!$changelater) {
2295  if (!is_object($this->oldcopy)) {
2296  $this->oldcopy = clone $this;
2297  }
2298 
2299  $this->db->begin();
2300 
2301  $sql = "UPDATE ".$this->db->prefix()."user";
2302  $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2303  $sql .= " pass_temp = null";
2304  if (!empty($flagdelsessionsbefore)) {
2305  $sql .= ", flagdelsessionsbefore = '".$this->db->idate(dol_now() - 5, 'gmt')."'";
2306  }
2307  if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
2308  $sql .= ", pass = null";
2309  } else {
2310  $sql .= ", pass = '".$this->db->escape($password)."'";
2311  }
2312  $sql .= " WHERE rowid = ".((int) $this->id);
2313 
2314  dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2315  $result = $this->db->query($sql);
2316  if ($result) {
2317  if ($this->db->affected_rows($result)) {
2318  $this->pass = $password;
2319  $this->pass_indatabase = $password;
2320  $this->pass_indatabase_crypted = $password_crypted;
2321 
2322  if ($this->fk_member && !$nosyncmember) {
2323  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2324 
2325  // This user is linked with a member, so we also update members informations
2326  // if this is an update.
2327  $adh = new Adherent($this->db);
2328  $result = $adh->fetch($this->fk_member);
2329 
2330  if ($result >= 0) {
2331  $result = $adh->setPassword($user, $this->pass, (empty($conf->global->DATABASE_PWD_ENCRYPTED) ? 0 : 1), 1); // Cryptage non gere dans module adherent
2332  if (is_int($result) && $result < 0) {
2333  $this->error = $adh->error;
2334  dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2335  $error++;
2336  }
2337  } else {
2338  $this->error = $adh->error;
2339  $error++;
2340  }
2341  }
2342 
2343  dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2344 
2345  if (!$error && !$notrigger) {
2346  // Call trigger
2347  $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2348  if ($result < 0) {
2349  $error++; $this->db->rollback(); return -1;
2350  }
2351  // End call triggers
2352  }
2353 
2354  $this->db->commit();
2355  return $this->pass;
2356  } else {
2357  $this->db->rollback();
2358  return 0;
2359  }
2360  } else {
2361  $this->db->rollback();
2362  dol_print_error($this->db);
2363  return -1;
2364  }
2365  } else {
2366  // We store password in password temporary field.
2367  // After receiving confirmation link, we will erase and store it in pass_crypted
2368  $sql = "UPDATE ".$this->db->prefix()."user";
2369  $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2370  $sql .= " WHERE rowid = ".((int) $this->id);
2371 
2372  dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2373  $result = $this->db->query($sql);
2374  if ($result) {
2375  return $password;
2376  } else {
2377  dol_print_error($this->db);
2378  return -3;
2379  }
2380  }
2381  }
2382 
2383  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2392  public function send_password($user, $password = '', $changelater = 0)
2393  {
2394  // phpcs:enable
2395  global $conf, $langs, $mysoc;
2396  global $dolibarr_main_url_root;
2397 
2398  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2399 
2400  $msgishtml = 0;
2401 
2402  // Define $msg
2403  $mesg = '';
2404 
2405  $outputlangs = new Translate("", $conf);
2406 
2407  if (isset($this->conf->MAIN_LANG_DEFAULT)
2408  && $this->conf->MAIN_LANG_DEFAULT != 'auto') { // If user has defined its own language (rare because in most cases, auto is used)
2409  $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2410  }
2411 
2412  if ($this->conf->MAIN_LANG_DEFAULT) {
2413  $outputlangs->setDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2414  } else { // If user has not defined its own language, we used current language
2415  $outputlangs = $langs;
2416  }
2417 
2418  // Load translation files required by the page
2419  $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2420 
2421  $appli = constant('DOL_APPLICATION_TITLE');
2422  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
2423  $appli = $conf->global->MAIN_APPLICATION_TITLE;
2424  }
2425 
2426  $subject = '['.$mysoc->name.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2427 
2428  // Define $urlwithroot
2429  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2430  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2431 
2432  if (!$changelater) {
2433  $url = $urlwithroot.'/';
2434  if (!empty($conf->global->URL_REDIRECTION_AFTER_CHANGEPASSWORD)) {
2435  $url = $conf->global->URL_REDIRECTION_AFTER_CHANGEPASSWORD;
2436  }
2437 
2438  dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2439 
2440  $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2441  $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2442  $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2443  $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2444  $mesg .= "\n";
2445 
2446  $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2447  $mesg .= "--\n";
2448  $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2449  } else {
2450  //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2451  $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2452  $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2453  if (isModEnabled('multicompany')) {
2454  $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2455  }
2456 
2457  dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2458 
2459  $msgishtml = 1;
2460 
2461  $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2462  $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2463  $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2464  $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2465  $mesg .= "<br>\n";
2466  $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2467  $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2468  $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2469  }
2470 
2471  $trackid = 'use'.$this->id;
2472  $sendcontext = 'password';
2473 
2474  $mailfile = new CMailFile(
2475  $subject,
2476  $this->email,
2477  $conf->global->MAIN_MAIL_EMAIL_FROM,
2478  $mesg,
2479  array(),
2480  array(),
2481  array(),
2482  '',
2483  '',
2484  0,
2485  $msgishtml,
2486  '',
2487  '',
2488  $trackid,
2489  '',
2490  $sendcontext
2491  );
2492 
2493  if ($mailfile->sendfile()) {
2494  return 1;
2495  } else {
2496  $langs->trans("errors");
2497  $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2498  return -1;
2499  }
2500  }
2501 
2507  public function error()
2508  {
2509  return $this->error;
2510  }
2511 
2512 
2513  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2519  public function fetch_clicktodial()
2520  {
2521  // phpcs:enable
2522  $sql = "SELECT url, login, pass, poste ";
2523  $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2524  $sql .= " WHERE u.fk_user = ".((int) $this->id);
2525 
2526  $resql = $this->db->query($sql);
2527  if ($resql) {
2528  if ($this->db->num_rows($resql)) {
2529  $obj = $this->db->fetch_object($resql);
2530 
2531  $this->clicktodial_url = $obj->url;
2532  $this->clicktodial_login = $obj->login;
2533  $this->clicktodial_password = $obj->pass;
2534  $this->clicktodial_poste = $obj->poste;
2535  }
2536 
2537  $this->clicktodial_loaded = 1; // Data loaded (found or not)
2538 
2539  $this->db->free($resql);
2540  return 1;
2541  } else {
2542  $this->error = $this->db->error();
2543  return -1;
2544  }
2545  }
2546 
2547  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2553  public function update_clicktodial()
2554  {
2555  // phpcs:enable
2556  $this->db->begin();
2557 
2558  $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2559  $sql .= " WHERE fk_user = ".((int) $this->id);
2560 
2561  dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2562  $result = $this->db->query($sql);
2563 
2564  $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
2565  $sql .= " (fk_user,url,login,pass,poste)";
2566  $sql .= " VALUES (".$this->id;
2567  $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2568  $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2569  $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2570  $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2571 
2572  dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2573  $result = $this->db->query($sql);
2574  if ($result) {
2575  $this->db->commit();
2576  return 1;
2577  } else {
2578  $this->db->rollback();
2579  $this->error = $this->db->lasterror();
2580  return -1;
2581  }
2582  }
2583 
2584 
2585  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2594  public function SetInGroup($group, $entity, $notrigger = 0)
2595  {
2596  // phpcs:enable
2597  global $conf, $langs, $user;
2598 
2599  $error = 0;
2600 
2601  $this->db->begin();
2602 
2603  $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2604  $sql .= " WHERE fk_user = ".((int) $this->id);
2605  $sql .= " AND fk_usergroup = ".((int) $group);
2606  $sql .= " AND entity = ".((int) $entity);
2607 
2608  $result = $this->db->query($sql);
2609 
2610  $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
2611  $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
2612 
2613  $result = $this->db->query($sql);
2614  if ($result) {
2615  if (!$error && !$notrigger) {
2616  $this->newgroupid = $group; // deprecated. Remove this.
2617  $this->context = array('audit'=>$langs->trans("UserSetInGroup"), 'newgroupid'=>$group);
2618 
2619  // Call trigger
2620  $result = $this->call_trigger('USER_MODIFY', $user);
2621  if ($result < 0) {
2622  $error++;
2623  }
2624  // End call triggers
2625  }
2626 
2627  if (!$error) {
2628  $this->db->commit();
2629  return 1;
2630  } else {
2631  dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2632  $this->db->rollback();
2633  return -2;
2634  }
2635  } else {
2636  $this->error = $this->db->lasterror();
2637  $this->db->rollback();
2638  return -1;
2639  }
2640  }
2641 
2642  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2651  public function RemoveFromGroup($group, $entity, $notrigger = 0)
2652  {
2653  // phpcs:enable
2654  global $conf, $langs, $user;
2655 
2656  $error = 0;
2657 
2658  $this->db->begin();
2659 
2660  $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2661  $sql .= " WHERE fk_user = ".((int) $this->id);
2662  $sql .= " AND fk_usergroup = ".((int) $group);
2663  if (empty($entity)) {
2664  $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
2665  } else {
2666  $sql .= " AND entity = ".((int) $entity);
2667  }
2668 
2669  $result = $this->db->query($sql);
2670  if ($result) {
2671  if (!$error && !$notrigger) {
2672  $this->oldgroupid = $group; // deprecated. Remove this.
2673  $this->context = array('audit'=>$langs->trans("UserRemovedFromGroup"), 'oldgroupid'=>$group);
2674 
2675  // Call trigger
2676  $result = $this->call_trigger('USER_MODIFY', $user);
2677  if ($result < 0) {
2678  $error++;
2679  }
2680  // End call triggers
2681  }
2682 
2683  if (!$error) {
2684  $this->db->commit();
2685  return 1;
2686  } else {
2687  dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2688  $this->db->rollback();
2689  return -2;
2690  }
2691  } else {
2692  $this->error = $this->db->lasterror();
2693  $this->db->rollback();
2694  return -1;
2695  }
2696  }
2697 
2698 
2705  public function isNotIntoValidityDateRange()
2706  {
2707  include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2708 
2709  $now = dol_now();
2710 
2711  //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
2712 
2713  // Check date start validity
2714  if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
2715  return 1;
2716  }
2717  // Check date end validity
2718  if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
2719  return 1;
2720  }
2721 
2722  return 0;
2723  }
2724 
2725 
2736  public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
2737  {
2738  $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2739  $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
2740  $result .= '</a>';
2741 
2742  return $result;
2743  }
2744 
2752  public function getTooltipContentArray($params)
2753  {
2754  global $conf, $langs, $menumanager;
2755 
2756  $infologin = $params['infologin'] ?? 0;
2757  $option = $params['option'] ?? '';
2758 
2759  $datas = [];
2760  if (!empty($this->photo)) {
2761  $photo = '<div class="photointooltip floatright">';
2762  $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
2763  $photo .= '</div>';
2764  $datas['photo'] = $photo;
2765  //$label .= '<div style="clear: both;"></div>';
2766  }
2767 
2768  // Info Login
2769  $datas['opendiv'] = '<div class="centpercent">';
2770  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
2771  $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs, ''));
2772  if (!empty($this->login)) {
2773  $datas['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
2774  }
2775  if (!empty($this->job)) {
2776  $datas['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
2777  }
2778  $datas['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
2779  if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
2780  $phonelist = array();
2781  if ($this->office_phone) {
2782  $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2783  }
2784  if ($this->office_fax) {
2785  $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2786  }
2787  if ($this->user_mobile) {
2788  $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
2789  }
2790  $datas['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
2791  }
2792  if (!empty($this->admin)) {
2793  $datas['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
2794  }
2795  if (!empty($this->accountancy_code) || $option == 'accountancy') {
2796  $datas['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
2797  }
2798  $company = '';
2799  if (!empty($this->socid)) { // Add thirdparty for external users
2800  $thirdpartystatic = new Societe($this->db);
2801  $thirdpartystatic->fetch($this->socid);
2802  if (empty($hidethirdpartylogo)) {
2803  $companylink = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2804  }
2805  $company = ' ('.$langs->trans("Company").': '.img_picto('', 'company').' '.dol_string_nohtmltag($thirdpartystatic->name).')';
2806  }
2807  $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
2808  $datas['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
2809  $datas['closediv'] = '</div>';
2810 
2811  if ($infologin > 0) {
2812  $datas['newlinelogin'] = '<br>';
2813  $datas['session'] = '<br><u>'.$langs->trans("Session").'</u>';
2814  $datas['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
2815  if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) {
2816  $datas['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
2817  }
2818  $datas['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
2819  $datas['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
2820  $datas['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
2821  $datas['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
2822  $datas['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
2823  $s = picto_from_langcode($langs->getDefaultLang());
2824  $datas['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
2825  $datas['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
2826  $datas['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
2827  $datas['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
2828  if ($conf->browser->layout == 'phone') {
2829  $datas['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
2830  }
2831  if (!empty($_SESSION["disablemodules"])) {
2832  $datas['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(join(', ', explode(',', $_SESSION["disablemodules"])));
2833  }
2834  }
2835 
2836  return $datas;
2837  }
2838 
2854  public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
2855  {
2856  global $langs, $conf, $db, $hookmanager, $user;
2857  global $dolibarr_main_authentication, $dolibarr_main_demo;
2858  global $menumanager;
2859 
2860  if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
2861  $option = 'nolink';
2862  }
2863 
2864  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) {
2865  $withpictoimg = 0;
2866  }
2867 
2868  $result = '';
2869  $params = [
2870  'id' => $this->id,
2871  'objecttype' => $this->element,
2872  'infologin' => $infologin,
2873  'option' => $option,
2874  ];
2875  $classfortooltip = 'classfortooltip';
2876  $dataparams = '';
2877  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2878  $classfortooltip = 'classforajaxtooltip';
2879  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2880  $label = '';
2881  } else {
2882  $label = implode($this->getTooltipContentArray($params));
2883  }
2884 
2885  $companylink = '';
2886  if (!empty($this->socid)) { // Add thirdparty for external users
2887  $thirdpartystatic = new Societe($this->db);
2888  $thirdpartystatic->fetch($this->socid);
2889  if (empty($hidethirdpartylogo)) {
2890  $companylink = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2891  }
2892  }
2893 
2894  if ($infologin < 0) {
2895  $label = '';
2896  }
2897 
2898  $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id;
2899  if ($option == 'leave') {
2900  $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id;
2901  }
2902 
2903  if ($option != 'nolink') {
2904  // Add param to save lastsearch_values or not
2905  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2906  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2907  $add_save_lastsearch_values = 1;
2908  }
2909  if ($add_save_lastsearch_values) {
2910  $url .= '&save_lastsearch_values=1';
2911  }
2912  }
2913 
2914  $linkstart = '<a href="'.$url.'"';
2915  $linkclose = "";
2916  if (empty($notooltip)) {
2917  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2918  $langs->load("users");
2919  $label = $langs->trans("ShowUser");
2920  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2921  }
2922  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2923  $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
2924  } else {
2925  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
2926  }
2927 
2928  $linkstart .= $linkclose.'>';
2929  $linkend = '</a>';
2930 
2931  //if ($withpictoimg == -1) $result.='<div class="nowrap">';
2932  $result .= (($option == 'nolink') ? '' : $linkstart);
2933  if ($withpictoimg) {
2934  $paddafterimage = '';
2935  if (abs((int) $withpictoimg) == 1) {
2936  $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
2937  }
2938  // Only picto
2939  if ($withpictoimg > 0) {
2940  $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' class="paddingright")', 0, 0, $notooltip ? 0 : 1).'</span>';
2941  } else {
2942  // Picto must be a photo
2943  $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>';
2944  }
2945  $result .= $picto;
2946  }
2947  if ($withpictoimg > -2 && $withpictoimg != 2) {
2948  if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2949  $result .= '<span class="nopadding usertext'.((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
2950  }
2951  if ($mode == 'login') {
2952  $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
2953  } else {
2954  $result .= dol_string_nohtmltag($this->getFullName($langs, '', ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
2955  }
2956  if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2957  $result .= '</span>';
2958  }
2959  }
2960  $result .= (($option == 'nolink') ? '' : $linkend);
2961  //if ($withpictoimg == -1) $result.='</div>';
2962 
2963  $result .= $companylink;
2964 
2965  global $action;
2966  $hookmanager->initHooks(array('userdao'));
2967  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
2968  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2969  if ($reshook > 0) {
2970  $result = $hookmanager->resPrint;
2971  } else {
2972  $result .= $hookmanager->resPrint;
2973  }
2974 
2975  return $result;
2976  }
2977 
2987  public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
2988  {
2989  global $langs, $user;
2990 
2991  $result = '';
2992 
2993  $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2994  $linkend = '</a>';
2995 
2996  //Check user's rights to see an other user
2997  if ((!$user->rights->user->user->lire && $this->id != $user->id)) {
2998  $option = 'nolink';
2999  }
3000 
3001  if ($option == 'xxx') {
3002  $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3003  $linkend = '</a>';
3004  }
3005 
3006  if ($option == 'nolink') {
3007  $linkstart = '';
3008  $linkend = '';
3009  }
3010 
3011  $result .= $linkstart;
3012  if ($withpictoimg) {
3013  $paddafterimage = '';
3014  if (abs($withpictoimg) == 1) {
3015  $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3016  }
3017  // Only picto
3018  if ($withpictoimg > 0) {
3019  $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3020  } else {
3021  // Picto must be a photo
3022  $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>';
3023  }
3024  $result .= $picto;
3025  }
3026  $result .= $this->login;
3027  $result .= $linkend;
3028 
3029  return $result;
3030  }
3031 
3038  public function getLibStatut($mode = 0)
3039  {
3040  return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3041  }
3042 
3043  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3051  public function LibStatut($status, $mode = 0)
3052  {
3053  // phpcs:enable
3054  global $langs;
3055 
3056  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3057  global $langs;
3058  //$langs->load("mymodule");
3059  $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3060  $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3061  $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3062  $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3063  }
3064 
3065  $statusType = 'status5';
3066  if ($status == self::STATUS_ENABLED) {
3067  $statusType = 'status4';
3068  }
3069 
3070  $label = $this->labelStatus[$status];
3071  $labelshort = $this->labelStatusShort[$status];
3072 
3073  $now = dol_now();
3074  if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3075  $statusType = 'status3';
3076  $label .= ' ('.$langs->trans("UserNotYetValid").')';
3077  }
3078  if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3079  $statusType = 'status2';
3080  $label .= ' ('.$langs->trans("UserExpired").')';
3081  }
3082 
3083  return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3084  }
3085 
3086 
3094  public function getKanbanView($option = '', $arraydata = null)
3095  {
3096  global $langs;
3097 
3098  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3099 
3100  $return = '<div class="box-flex-item box-flex-grow-zero">';
3101  $return .= '<div class="info-box info-box-sm">';
3102  $return .= '<span class="info-box-icon bg-infobox-action">';
3103 
3104  $label = '';
3105  if (!empty($this->photo)) {
3106  //$label .= '<div class="photointooltip floatright">';
3107  $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
3108  //$label .= '</div>';
3109  //$label .= '<div style="clear: both;"></div>';
3110  $return .= $label;
3111  } else {
3112  $return .= img_picto('', $this->picto);
3113  }
3114 
3115  //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3116  $return .= '</span>';
3117  $return .= '<div class="info-box-content">';
3118  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3119  if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3120  $return .= img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingright paddingleft"');
3121  } elseif ($this->admin) {
3122  $return .= img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingright paddingleft"');
3123  }
3124  $return .= '</span>';
3125  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3126  if (property_exists($this, 'label')) {
3127  $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3128  }
3129  if ($this->email) {
3130  $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3131  }
3132  if (method_exists($this, 'getLibStatut')) {
3133  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
3134  }
3135  $return .= '</div>';
3136  $return .= '</div>';
3137  $return .= '</div>';
3138 
3139  return $return;
3140  }
3141 
3142 
3143  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3144  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3154  public function _load_ldap_dn($info, $mode = 0)
3155  {
3156  // phpcs:enable
3157  global $conf;
3158  $dn = '';
3159  if ($mode == 0) {
3160  $dn = $conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS].",".$conf->global->LDAP_USER_DN;
3161  } elseif ($mode == 1) {
3162  $dn = $conf->global->LDAP_USER_DN;
3163  } elseif ($mode == 2) {
3164  $dn = $conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS];
3165  }
3166  return $dn;
3167  }
3168 
3169  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3170  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3176  public function _load_ldap_info()
3177  {
3178  // phpcs:enable
3179  global $conf, $langs;
3180 
3181  $info = array();
3182 
3183  $socialnetworks = getArrayOfSocialNetworks();
3184 
3185  $keymodified = false;
3186 
3187  // Object classes
3188  $info["objectclass"] = explode(',', $conf->global->LDAP_USER_OBJECT_CLASS);
3189 
3190  $this->fullname = $this->getFullName($langs);
3191 
3192  // Possible LDAP KEY (constname => varname)
3193  $ldapkey = array(
3194  'LDAP_FIELD_FULLNAME' => 'fullname',
3195  'LDAP_FIELD_NAME' => 'lastname',
3196  'LDAP_FIELD_FIRSTNAME' => 'firstname',
3197  'LDAP_FIELD_LOGIN' => 'login',
3198  'LDAP_FIELD_LOGIN_SAMBA'=> 'login',
3199  'LDAP_FIELD_PHONE' => 'office_phone',
3200  'LDAP_FIELD_MOBILE' => 'user_mobile',
3201  'LDAP_FIELD_FAX' => 'office_fax',
3202  'LDAP_FIELD_MAIL' => 'email',
3203  'LDAP_FIELD_SID' => 'ldap_sid',
3204  );
3205 
3206  // Champs
3207  foreach ($ldapkey as $constname => $varname) {
3208  if (!empty($this->$varname) && !empty($conf->global->$constname)) {
3209  $info[$conf->global->$constname] = $this->$varname;
3210 
3211  // Check if it is the LDAP key and if its value has been changed
3212  if (!empty($conf->global->LDAP_KEY_USERS) && $conf->global->LDAP_KEY_USERS == $conf->global->$constname) {
3213  if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
3214  $keymodified = true; // For check if LDAP key has been modified
3215  }
3216  }
3217  }
3218  }
3219  foreach ($socialnetworks as $key => $value) {
3220  if (!empty($this->socialnetworks[$value['label']]) && !empty($conf->global->{'LDAP_FIELD_'.strtoupper($value['label'])})) {
3221  $info[$conf->global->{'LDAP_FIELD_'.strtoupper($value['label'])}] = $this->socialnetworks[$value['label']];
3222  }
3223  }
3224  if ($this->address && !empty($conf->global->LDAP_FIELD_ADDRESS)) {
3225  $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address;
3226  }
3227  if ($this->zip && !empty($conf->global->LDAP_FIELD_ZIP)) {
3228  $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip;
3229  }
3230  if ($this->town && !empty($conf->global->LDAP_FIELD_TOWN)) {
3231  $info[$conf->global->LDAP_FIELD_TOWN] = $this->town;
3232  }
3233  if ($this->note_public && !empty($conf->global->LDAP_FIELD_DESCRIPTION)) {
3234  $info[$conf->global->LDAP_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_public, 2);
3235  }
3236  if ($this->socid > 0) {
3237  $soc = new Societe($this->db);
3238  $soc->fetch($this->socid);
3239 
3240  $info[$conf->global->LDAP_FIELD_COMPANY] = $soc->name;
3241  if ($soc->client == 1) {
3242  $info["businessCategory"] = "Customers";
3243  }
3244  if ($soc->client == 2) {
3245  $info["businessCategory"] = "Prospects";
3246  }
3247  if ($soc->fournisseur == 1) {
3248  $info["businessCategory"] = "Suppliers";
3249  }
3250  }
3251 
3252  // When password is modified
3253  if (!empty($this->pass)) {
3254  if (!empty($conf->global->LDAP_FIELD_PASSWORD)) {
3255  $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte
3256  }
3257  if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
3258  $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3259  }
3260  } elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') {
3261  // Set LDAP password if possible
3262  // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3263  if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
3264  // Just for the default MD5 !
3265  if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) {
3266  if ($this->pass_indatabase_crypted && !empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
3267  $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3268  }
3269  }
3270  } elseif (!empty($this->pass_indatabase)) {
3271  // Use $this->pass_indatabase value if exists
3272  if (!empty($conf->global->LDAP_FIELD_PASSWORD)) {
3273  $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte
3274  }
3275  if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
3276  $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3277  }
3278  }
3279  }
3280 
3281  if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') {
3282  $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3283 
3284  $info['uidnumber'] = $this->id;
3285 
3286  $info['phpgwTz'] = 0;
3287  $info['phpgwMailType'] = 'INTERNET';
3288  $info['phpgwMailHomeType'] = 'INTERNET';
3289 
3290  $info["phpgwContactTypeId"] = 'n';
3291  $info["phpgwContactCatId"] = 0;
3292  $info["phpgwContactAccess"] = "public";
3293 
3294  if (dol_strlen($this->egroupware_id) == 0) {
3295  $this->egroupware_id = 1;
3296  }
3297 
3298  $info["phpgwContactOwner"] = $this->egroupware_id;
3299 
3300  if ($this->email) {
3301  $info["rfc822Mailbox"] = $this->email;
3302  }
3303  if ($this->phone_mobile) {
3304  $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
3305  }
3306  }
3307 
3308  if (!empty($conf->global->LDAP_FIELD_USERID)) {
3309  $info[$conf->global->LDAP_FIELD_USERID] = $this->id;
3310  }
3311  if (!empty($conf->global->LDAP_FIELD_GROUPID)) {
3312  $usergroup = new UserGroup($this->db);
3313  $groupslist = $usergroup->listGroupsForUser($this->id);
3314  $info[$conf->global->LDAP_FIELD_GROUPID] = '65534';
3315  if (!empty($groupslist)) {
3316  foreach ($groupslist as $groupforuser) {
3317  $info[$conf->global->LDAP_FIELD_GROUPID] = $groupforuser->id; //Select first group in list
3318  break;
3319  }
3320  }
3321  }
3322  if (!empty($conf->global->LDAP_FIELD_HOMEDIRECTORY) && !empty($conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX)) {
3323  $info[$conf->global->LDAP_FIELD_HOMEDIRECTORY] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->login";
3324  }
3325 
3326  return $info;
3327  }
3328 
3329 
3337  public function initAsSpecimen()
3338  {
3339  global $user, $langs;
3340 
3341  $now = dol_now();
3342 
3343  // Initialise parametres
3344  $this->id = 0;
3345  $this->ref = 'SPECIMEN';
3346  $this->specimen = 1;
3347 
3348  $this->lastname = 'DOLIBARR';
3349  $this->firstname = 'SPECIMEN';
3350  $this->gender = 'man';
3351  $this->note_public = 'This is a note public';
3352  $this->note_private = 'This is a note private';
3353  $this->email = 'email@specimen.com';
3354  $this->personal_email = 'personalemail@specimen.com';
3355  $this->socialnetworks = array(
3356  'skype' => 'skypepseudo',
3357  'twitter' => 'twitterpseudo',
3358  'facebook' => 'facebookpseudo',
3359  'linkedin' => 'linkedinpseudo',
3360  );
3361  $this->office_phone = '0999999999';
3362  $this->office_fax = '0999999998';
3363  $this->user_mobile = '0999999997';
3364  $this->personal_mobile = '0999999996';
3365  $this->admin = 0;
3366  $this->login = 'dolibspec';
3367  $this->pass = 'dolibSpec+@123';
3368  //$this->pass_indatabase='dolibspec'; Set after a fetch
3369  //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3370  $this->datec = $now;
3371  $this->datem = $now;
3372 
3373  $this->datelastlogin = $now;
3374  $this->iplastlogin = '127.0.0.1';
3375  $this->datepreviouslogin = $now;
3376  $this->ippreviouslogin = '127.0.0.1';
3377  $this->statut = 1; // deprecated
3378  $this->status = 1;
3379 
3380  $this->entity = 1;
3381  return 1;
3382  }
3383 
3390  public function info($id)
3391  {
3392  $sql = "SELECT u.rowid, u.login as ref, u.datec,";
3393  $sql .= " u.tms as date_modification, u.entity";
3394  $sql .= " FROM ".$this->db->prefix()."user as u";
3395  $sql .= " WHERE u.rowid = ".((int) $id);
3396 
3397  $result = $this->db->query($sql);
3398  if ($result) {
3399  if ($this->db->num_rows($result)) {
3400  $obj = $this->db->fetch_object($result);
3401 
3402  $this->id = $obj->rowid;
3403 
3404  $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3405  $this->date_creation = $this->db->jdate($obj->datec);
3406  $this->date_modification = $this->db->jdate($obj->date_modification);
3407  $this->entity = $obj->entity;
3408  }
3409 
3410  $this->db->free($result);
3411  } else {
3412  dol_print_error($this->db);
3413  }
3414  }
3415 
3416 
3422  public function getNbOfEMailings()
3423  {
3424  $sql = "SELECT count(mc.email) as nb";
3425  $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3426  $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3427  $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes
3428 
3429  $resql = $this->db->query($sql);
3430  if ($resql) {
3431  $obj = $this->db->fetch_object($resql);
3432  $nb = $obj->nb;
3433 
3434  $this->db->free($resql);
3435  return $nb;
3436  } else {
3437  $this->error = $this->db->error();
3438  return -1;
3439  }
3440  }
3441 
3450  public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3451  {
3452  global $conf;
3453 
3454  $sql = "SELECT count(rowid) as nb";
3455  $sql .= " FROM ".$this->db->prefix()."user";
3456  if ($option == 'superadmin') {
3457  $sql .= " WHERE entity = 0";
3458  } else {
3459  $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3460  if ($limitTo == 'active') {
3461  $sql .= " AND statut = 1";
3462  }
3463  }
3464  if ($admin >= 0) {
3465  $sql .= " AND admin = ".(int) $admin;
3466  }
3467 
3468  $resql = $this->db->query($sql);
3469  if ($resql) {
3470  $obj = $this->db->fetch_object($resql);
3471  $nb = (int) $obj->nb;
3472 
3473  $this->db->free($resql);
3474  return $nb;
3475  } else {
3476  $this->error = $this->db->lasterror();
3477  return -1;
3478  }
3479  }
3480 
3481  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3488  public function update_ldap2dolibarr(&$ldapuser)
3489  {
3490  // phpcs:enable
3491  // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3492  global $user, $conf;
3493 
3494  $socialnetworks = getArrayOfSocialNetworks();
3495 
3496  $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3497  $this->firstname = $ldapuser->$tmpvar;
3498  $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3499  $this->lastname = $ldapuser->$tmpvar;
3500  $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3501  $this->login = $ldapuser->$tmpvar;
3502  $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3503  $this->pass = $ldapuser->$tmpvar;
3504  $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3505  $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3506 
3507  $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3508  $this->office_phone = $ldapuser->$tmpvar;
3509  $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3510  $this->user_mobile = $ldapuser->$tmpvar;
3511  $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3512  $this->office_fax = $ldapuser->$tmpvar;
3513  $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3514  $this->email = $ldapuser->$tmpvar;
3515  foreach ($socialnetworks as $key => $value) {
3516  $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3517  $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3518  }
3519  $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3520  $this->ldap_sid = $ldapuser->$tmpvar;
3521 
3522  $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3523  $this->job = $ldapuser->$tmpvar;
3524  $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3525  $this->note_public = $ldapuser->$tmpvar;
3526 
3527  $result = $this->update($user);
3528 
3529  dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3530 
3531  return $result;
3532  }
3533 
3534 
3535  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3542  public function get_children()
3543  {
3544  // phpcs:enable
3545  $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3546  $sql .= " WHERE fk_user = ".((int) $this->id);
3547 
3548  dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3549  $res = $this->db->query($sql);
3550  if ($res) {
3551  $users = array();
3552  while ($rec = $this->db->fetch_array($res)) {
3553  $user = new User($this->db);
3554  $user->fetch($rec['rowid']);
3555  $users[] = $user;
3556  }
3557  return $users;
3558  } else {
3559  dol_print_error($this->db);
3560  return -1;
3561  }
3562  }
3563 
3564 
3570  private function loadParentOf()
3571  {
3572  global $conf;
3573 
3574  $this->parentof = array();
3575 
3576  // Load array[child]=parent
3577  $sql = "SELECT fk_user as id_parent, rowid as id_son";
3578  $sql .= " FROM ".$this->db->prefix()."user";
3579  $sql .= " WHERE fk_user <> 0";
3580  $sql .= " AND entity IN (".getEntity('user').")";
3581 
3582  dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3583  $resql = $this->db->query($sql);
3584  if ($resql) {
3585  while ($obj = $this->db->fetch_object($resql)) {
3586  $this->parentof[$obj->id_son] = $obj->id_parent;
3587  }
3588  return 1;
3589  } else {
3590  dol_print_error($this->db);
3591  return -1;
3592  }
3593  }
3594 
3595  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3609  public function get_full_tree($deleteafterid = 0, $filter = '')
3610  {
3611  // phpcs:enable
3612  global $conf, $user;
3613  global $hookmanager;
3614 
3615  // Actions hooked (by external module)
3616  $hookmanager->initHooks(array('userdao'));
3617 
3618  $this->users = array();
3619 
3620  // Init this->parentof that is array(id_son=>id_parent, ...)
3621  $this->loadParentOf();
3622 
3623  // Init $this->users array
3624  $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
3625  $sql .= " FROM ".$this->db->prefix()."user as u";
3626  // Add fields from hooks
3627  $parameters = array();
3628  $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3629  if ($reshook > 0) {
3630  $sql .= $hookmanager->resPrint;
3631  } else {
3632  $sql .= " WHERE u.entity IN (".getEntity('user').")";
3633  }
3634  if ($filter) {
3635  $sql .= " AND ".$filter;
3636  }
3637 
3638  dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3639  $resql = $this->db->query($sql);
3640  if ($resql) {
3641  $i = 0;
3642  while ($obj = $this->db->fetch_object($resql)) {
3643  $this->users[$obj->rowid]['rowid'] = $obj->rowid;
3644  $this->users[$obj->rowid]['id'] = $obj->rowid;
3645  $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
3646  $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
3647  $this->users[$obj->rowid]['firstname'] = $obj->firstname;
3648  $this->users[$obj->rowid]['lastname'] = $obj->lastname;
3649  $this->users[$obj->rowid]['login'] = $obj->login;
3650  $this->users[$obj->rowid]['statut'] = $obj->statut;
3651  $this->users[$obj->rowid]['entity'] = $obj->entity;
3652  $this->users[$obj->rowid]['email'] = $obj->email;
3653  $this->users[$obj->rowid]['gender'] = $obj->gender;
3654  $this->users[$obj->rowid]['admin'] = $obj->admin;
3655  $this->users[$obj->rowid]['photo'] = $obj->photo;
3656  $i++;
3657  }
3658  } else {
3659  dol_print_error($this->db);
3660  return -1;
3661  }
3662 
3663  // We add the fullpath property to each elements of first level (no parent exists)
3664  dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3665  foreach ($this->users as $key => $val) {
3666  $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3667  if ($result < 0) {
3668  $this->error = 'ErrorLoopInHierarchy';
3669  return -1;
3670  }
3671  }
3672 
3673  // Exclude leaf including $deleteafterid from tree
3674  if ($deleteafterid) {
3675  //print "Look to discard user ".$deleteafterid."\n";
3676  $keyfilter1 = '^'.$deleteafterid.'$';
3677  $keyfilter2 = '_'.$deleteafterid.'$';
3678  $keyfilter3 = '^'.$deleteafterid.'_';
3679  $keyfilter4 = '_'.$deleteafterid.'_';
3680  foreach ($this->users as $key => $val) {
3681  if (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath'])
3682  || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])) {
3683  unset($this->users[$key]);
3684  }
3685  }
3686  }
3687 
3688  dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
3689  $this->users = dol_sort_array($this->users, 'fullname', 'asc', true, false, 1);
3690 
3691  //var_dump($this->users);
3692 
3693  return $this->users;
3694  }
3695 
3704  public function getAllChildIds($addcurrentuser = 0)
3705  {
3706  $childids = array();
3707 
3708  if (isset($this->cache_childids[$this->id])) {
3709  $childids = $this->cache_childids[$this->id];
3710  } else {
3711  // Init this->users
3712  $this->get_full_tree();
3713 
3714  $idtoscan = $this->id;
3715 
3716  dol_syslog("Build childid for id = ".$idtoscan);
3717  foreach ($this->users as $id => $val) {
3718  //var_dump($val['fullpath']);
3719  if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
3720  $childids[$val['id']] = $val['id'];
3721  }
3722  }
3723  }
3724  $this->cache_childids[$this->id] = $childids;
3725 
3726  if ($addcurrentuser) {
3727  $childids[$this->id] = $this->id;
3728  }
3729 
3730  return $childids;
3731  }
3732 
3733  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3742  public function build_path_from_id_user($id_user, $protection = 0)
3743  {
3744  // phpcs:enable
3745  //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
3746 
3747  if (!empty($this->users[$id_user]['fullpath'])) {
3748  // Already defined
3749  dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
3750  return 0;
3751  }
3752 
3753  // Define fullpath and fullname
3754  $this->users[$id_user]['fullpath'] = '_'.$id_user;
3755  $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
3756  $i = 0; $cursor_user = $id_user;
3757 
3758  $useridfound = array($id_user);
3759  while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) {
3760  if (in_array($this->parentof[$cursor_user], $useridfound)) {
3761  dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
3762  return -1; // Should not happen. Protection against looping hierarchy
3763  }
3764  $useridfound[] = $this->parentof[$cursor_user];
3765  $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
3766  $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
3767  $i++; $cursor_user = $this->parentof[$cursor_user];
3768  }
3769 
3770  // We count number of _ to have level
3771  $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
3772 
3773  return 1;
3774  }
3775 
3784  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3785  {
3786  $tables = array(
3787  'user',
3788  );
3789 
3790  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3791  }
3792 
3793 
3794  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3800  public function load_state_board()
3801  {
3802  // phpcs:enable
3803  global $conf;
3804 
3805  $this->nb = array();
3806 
3807  $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
3808  $sql .= " FROM ".$this->db->prefix()."user as u";
3809  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
3810  $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
3811  $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
3812  $sql .= " AND ug.fk_user = u.rowid";
3813  } else {
3814  $sql .= " WHERE u.entity IN (".getEntity('user').")";
3815  }
3816  $sql .= " AND u.statut > 0";
3817  //$sql.= " AND employee != 0";
3818 
3819  $resql = $this->db->query($sql);
3820  if ($resql) {
3821  while ($obj = $this->db->fetch_object($resql)) {
3822  $this->nb["users"] = $obj->nb;
3823  }
3824  $this->db->free($resql);
3825  return 1;
3826  } else {
3827  dol_print_error($this->db);
3828  $this->error = $this->db->error();
3829  return -1;
3830  }
3831  }
3832 
3844  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3845  {
3846  global $conf, $user, $langs;
3847 
3848  $langs->load("user");
3849 
3850  // Positionne le modele sur le nom du modele a utiliser
3851  if (!dol_strlen($modele)) {
3852  if (!empty($conf->global->USER_ADDON_PDF)) {
3853  $modele = $conf->global->USER_ADDON_PDF;
3854  } else {
3855  $modele = 'bluesky';
3856  }
3857  }
3858 
3859  $modelpath = "core/modules/user/doc/";
3860 
3861  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3862  }
3863 
3864  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3872  public function user_get_property($rowid, $mode)
3873  {
3874  // phpcs:enable
3875  $user_property = '';
3876 
3877  if (empty($rowid)) {
3878  return '';
3879  }
3880 
3881  $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
3882  $sql .= " FROM ".$this->db->prefix()."user";
3883  $sql .= " WHERE rowid = ".((int) $rowid);
3884 
3885  $resql = $this->db->query($sql);
3886  if ($resql) {
3887  $nump = $this->db->num_rows($resql);
3888 
3889  if ($nump) {
3890  $obj = $this->db->fetch_object($resql);
3891 
3892  if ($mode == 'email') {
3893  $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
3894  } elseif ($mode == 'mobile') {
3895  $user_property = $obj->user_mobile;
3896  }
3897  }
3898  return $user_property;
3899  } else {
3900  dol_print_error($this->db);
3901  }
3902 
3903  return '';
3904  }
3905 
3913  public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
3914  {
3915  global $dolibarr_main_url_root;
3916  global $conf;
3917 
3918  $encodedsecurekey = dol_hash($conf->file->instance_unique_id.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
3919  if (isModEnabled('multicompany')) {
3920  $entity_qr = '&entity='.((int) $conf->entity);
3921  } else {
3922  $entity_qr = '';
3923  }
3924  // Define $urlwithroot
3925  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
3926  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
3927  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
3928 
3929  if ($typeofurl == 'internal') {
3930  $urlwithroot = DOL_URL_ROOT;
3931  }
3932 
3933  return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
3934  }
3935 
3948  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = array(), $filtermode = 'AND', $entityfilter = false)
3949  {
3950  global $conf, $user;
3951 
3952  $sql = "SELECT t.rowid";
3953  $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
3954 
3955  if ($entityfilter) {
3956  if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
3957  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
3958  $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
3959  } else {
3960  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
3961  $sql .= " WHERE ((ug.fk_user = t.rowid";
3962  $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
3963  $sql .= " OR t.entity = 0)"; // Show always superadmin
3964  }
3965  } else {
3966  $sql .= " WHERE t.entity IN (".getEntity('user').")";
3967  }
3968  } else {
3969  $sql .= " WHERE 1 = 1";
3970  }
3971 
3972  // Manage filter
3973  $sqlwhere = array();
3974  if (!empty($filter)) {
3975  foreach ($filter as $key => $value) {
3976  if ($key == 't.rowid') {
3977  $sqlwhere[] = $key." = ".((int) $value);
3978  } elseif (isset($this->fields[$key]['type']) && in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
3979  $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
3980  } elseif ($key == 'customsql') {
3981  $sqlwhere[] = $value;
3982  } else {
3983  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
3984  }
3985  }
3986  }
3987  if (count($sqlwhere) > 0) {
3988  $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
3989  }
3990  $sql .= $this->db->order($sortfield, $sortorder);
3991  if ($limit) {
3992  $sql .= $this->db->plimit($limit + 1, $offset);
3993  }
3994 
3995  dol_syslog(__METHOD__, LOG_DEBUG);
3996 
3997  $resql = $this->db->query($sql);
3998  if ($resql) {
3999  $this->users = array();
4000  $num = $this->db->num_rows($resql);
4001  if ($num) {
4002  while ($obj = $this->db->fetch_object($resql)) {
4003  $line = new self($this->db);
4004  $result = $line->fetch($obj->rowid);
4005  if ($result > 0 && !empty($line->id)) {
4006  $this->users[$obj->rowid] = clone $line;
4007  }
4008  }
4009  $this->db->free($resql);
4010  }
4011  return $num;
4012  } else {
4013  $this->errors[] = $this->db->lasterror();
4014  return -1;
4015  }
4016  }
4017 
4025  private $findUserIdByEmailCache;
4026 
4037  public function findUserIdByEmail($email)
4038  {
4039  if (isset($this->findUserIdByEmailCache[$email])) {
4040  return $this->findUserIdByEmailCache[$email];
4041  }
4042 
4043  $this->findUserIdByEmailCache[$email] = -1;
4044 
4045  global $conf;
4046 
4047  $sql = 'SELECT rowid';
4048  $sql .= ' FROM '.$this->db->prefix().'user';
4049  if (!empty($conf->global->AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR)) {
4050  $sql .= " WHERE email LIKE '%".$this->db->escape($email)."%'";
4051  } else {
4052  $sql .= " WHERE email = '".$this->db->escape($email)."'";
4053  }
4054  $sql .= ' LIMIT 1';
4055 
4056  $resql = $this->db->query($sql);
4057  if (!$resql) {
4058  return -1;
4059  }
4060 
4061  $obj = $this->db->fetch_object($resql);
4062  if (!$obj) {
4063  return -1;
4064  }
4065 
4066  $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4067 
4068  return $this->findUserIdByEmailCache[$email];
4069  }
4070 }
$object ref
Definition: info.php:78
Class to manage members of a foundation.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage contact/addresses.
Class for MyObject.
Class to manage Dolibarr database access.
Class to manage warehouses.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage user groups.
Class to manage Dolibarr users.
Definition: user.class.php:48
SetInGroup($group, $entity, $notrigger=0)
Add user into a group.
LibStatut($status, $mode=0)
Return the label of a status of user (active, inactive)
get_children()
Return and array with all instanciated first level children users of current user.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
Definition: user.class.php:689
info($id)
Load info of user object.
create_from_contact($contact, $login='', $password='')
Create a user from a contact object.
setstatus($status)
Change status of a user.
get_full_tree($deleteafterid=0, $filter='')
Build the hierarchy/tree of users into an array.
_load_ldap_info()
Initialize the info array (array of LDAP values) that will be used to call LDAP functions.
delrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0)
Remove a right to the user.
Definition: user.class.php:969
update_last_login_date()
Mise a jour en base de la date de derniere connexion d'un utilisateur Fonction appelee lors d'une nou...
__construct($db)
Constructor of the class.
Definition: user.class.php:365
RemoveFromGroup($group, $entity, $notrigger=0)
Remove a user from a group.
isNotIntoValidityDateRange()
Return a link with photo Use this->id,this->photo.
getNbOfUsers($limitTo, $option='', $admin=-1)
Return number of existing users.
fetch($id='', $login='', $sid='', $loadpersonalconf=0, $entity=-1, $email='', $fk_socpeople=0)
Load a user from database with its id or ref (login).
Definition: user.class.php:403
set_default_rights()
Assign rights by default.
getOnlineVirtualCardUrl($mode='', $typeofurl='external')
Return string with full Url to virtual card.
update($user, $notrigger=0, $nosyncmember=0, $nosyncmemberpass=0, $nosynccontact=0)
Update a user into database (and also password if this->pass is defined)
getLoginUrl($withpictoimg=0, $option='', $notooltip=0, $morecss='')
Return clickable link of login (eventualy with picto)
setCategories($categories)
Sets object to supplied categories.
loadParentOf()
Load this->parentof that is array(id_son=>id_parent, ...)
fetch_clicktodial()
Read clicktodial information for user.
build_path_from_id_user($id_user, $protection=0)
For user id_user and its childs available in this->users, define property fullpath and fullname.
error()
Renvoie la derniere erreur fonctionnelle de manipulation de l'objet.
getAllChildIds($addcurrentuser=0)
Return list of all child users id in herarchy (all sublevels).
initAsSpecimen()
Initialise an instance with random values.
setPassword($user, $password='', $changelater=0, $notrigger=0, $nosyncmember=0, $passwordalreadycrypted=0, $flagdelsessionsbefore=1)
Change password of a user.
getNomUrl($withpictoimg=0, $option='', $infologin=0, $notooltip=0, $maxlen=24, $hidethirdpartylogo=0, $mode='', $morecss='', $save_lastsearch_value=-1)
Return a HTML link to the user card (with optionaly the picto) Use this->id,this->lastname,...
clearrights()
Clear all permissions array of user.
load_state_board()
Load metrics this->nb for dashboard.
update_clicktodial()
Update clicktodial info.
getLibStatut($mode=0)
Return the label of the status of user (active, inactive)
create_from_member($member, $login='')
Create a user into database from a member object.
_load_ldap_dn($info, $mode=0)
Retourne chaine DN complete dans l'annuaire LDAP pour l'objet.
$clicktodial_url
@string clicktodial url
Definition: user.class.php:233
loadDefaultValues()
Load default values from database table into property ->default_values.
Definition: user.class.php:639
getPhotoUrl($width, $height, $cssclass='', $imagesize='')
Return a link with photo Use this->id,this->photo.
update_ldap2dolibarr(&$ldapuser)
Update user using data from the LDAP.
getrights($moduletag='', $forcereload=0)
Load permissions granted to user into object user.
user_get_property($rowid, $mode)
Return property of user from its id.
send_password($user, $password='', $changelater=0)
Send a new password (or instructions to reset it) by email.
getKanbanView($option='', $arraydata=null)
Return clicable link of object (with eventually picto)
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
addrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0)
Add a right to the user.
Definition: user.class.php:825
create($user, $notrigger=0)
Create a user into database.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter=array(), $filtermode='AND', $entityfilter=false)
Load all objects into $this->users.
findUserIdByEmail($email)
Find a user by the given e-mail and return it's user id when found.
getTooltipContentArray($params)
Return array of data to show into tooltips.
trait CommonPeople
Superclass for thirdparties, contacts, members or users.
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition: date.lib.php:637
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:623
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0)
Format phone numbers according to country.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by second index function, which produces ascending (default) or descending output...
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
getArrayOfSocialNetworks()
Get array of social network dictionary.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getUserRemoteIP()
Return the IP of remote user.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
conf($dolibarr_main_document_root)
Load conf file (file must exists)
Definition: inc.php:400
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dolEncrypt($chain, $key='', $ciphering='AES-256-CTR', $forceseed='')
Encode a string with a symetric encryption.
dol_verifyHash($chain, $hash, $type='0')
Compute a hash and compare it to the given one For backward compatibility reasons,...
dolGetLdapPasswordHash($password, $type='md5')
Returns a specific ldap hash of a password.
dolDecrypt($chain, $key='')
Decode a string with a symetric encryption.
dol_hash($chain, $type='0')
Returns a hash (non reversible encryption) of a string.