dolibarr  20.0.0-beta
user.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (c) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
4  * Copyright (c) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
5  * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6  * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
7  * Copyright (C) 2005-2024 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-2024 Frédéric France <frederic.france@free.fr>
16  * Copyright (C) 2019 Abbes Bahfir <dolipar@dolipar.org>
17  * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
18  * Copyright (C) 2024 Lenin Rivas <lenin.rivas777@gmail.com>
19  *
20  * This program is free software; you can redistribute it and/or modify
21  * it under the terms of the GNU General Public License as published by
22  * the Free Software Foundation; either version 3 of the License, or
23  * (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28  * GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program. If not, see <https://www.gnu.org/licenses/>.
32  */
33 
40 require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
43 require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
44 
45 
49 class User extends CommonObject
50 {
51  use CommonPeople;
52 
56  public $element = 'user';
57 
61  public $table_element = 'user';
62 
66  public $fk_element = 'fk_user';
67 
71  public $picto = 'user';
72 
73  public $id = 0;
74 
78  public $oldcopy;
79 
85  public $statut;
86 
87  public $status;
88 
92  public $openid;
93 
94  public $ldap_sid;
95  public $search_sid;
96  public $employee;
97  public $civility_code;
98 
102  public $fullname;
103 
107  public $gender;
108 
109  public $birth;
110 
114  public $email;
115 
119  public $email_oauth2;
120 
124  public $personal_email;
125 
129  public $socialnetworks;
130 
134  public $job;
135 
139  public $signature;
140 
144  public $office_phone;
145 
149  public $office_fax;
150 
154  public $user_mobile;
155 
159  public $personal_mobile;
160 
164  public $admin;
165 
169  public $login;
170 
174  public $api_key;
175 
179  public $entity;
180 
184  public $pass;
185 
189  public $pass_crypted;
190 
194  public $pass_indatabase;
195 
199  public $pass_indatabase_crypted;
200 
204  public $pass_temp;
205 
211  public $datec;
212 
218  public $datem;
219 
223  public $socid;
224 
228  public $contact_id;
229 
233  public $fk_member;
234 
238  public $fk_user;
239 
243  public $fk_user_expense_validator;
244 
248  public $fk_user_holiday_validator;
249 
254 
258  public $clicktodial_login;
259 
263  public $clicktodial_password;
264 
268  public $clicktodial_poste;
269 
273  public $clicktodial_loaded;
274 
275 
276  public $datelastlogin;
277  public $datepreviouslogin;
278  public $flagdelsessionsbefore;
279  public $iplastlogin;
280  public $ippreviouslogin;
281  public $datestartvalidity;
282  public $dateendvalidity;
283 
287  public $photo;
288 
292  public $lang;
293 
297  public $rights;
298 
302  public $all_permissions_are_loaded;
303 
307  public $nb_rights;
308 
312  public $user_group_list;
313 
317  private $_tab_loaded = array();
318 
322  public $conf;
323 
324  public $default_values; // To store default values for user. Loaded by loadDefaultValues().
325 
326  public $lastsearch_values_tmp; // To store current search criteria for user
327  public $lastsearch_values; // To store last saved search criteria for user
328 
332  public $users = array();
333  public $parentof; // To store an array of all parents for all ids.
334  private $cache_childids; // Cache array of already loaded children
335 
336  public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
337 
338  public $thm; // Average cost of employee - Used for valuation of time spent
339  public $tjm; // Average cost of employee
340 
341  public $salary; // Monthly salary - Denormalized value from llx_user_employment
342  public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment
343  public $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment
344 
348  public $color;
349 
350  public $dateemployment; // Define date of employment by company
351  public $dateemploymentend; // Define date of employment end by company
352 
353  public $default_c_exp_tax_cat;
354 
358  public $ref_employee;
359 
363  public $national_registration_number;
364 
365  public $default_range;
366 
370  public $fk_warehouse;
371 
375  public $fk_establishment;
376 
380  public $label_establishment;
381 
385  //private $egroupware_id;
386 
391  public $usergroup_entity;
392 
393  public $fields = array(
394  'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
395  'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 20, 'searchall' => 1),
396  'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1),
397  'ref_employee' => array('type' => 'varchar(50)', 'label' => 'RefEmployee', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 30, 'searchall' => 1),
398  'national_registration_number' => array('type' => 'varchar(50)', 'label' => 'NationalRegistrationNumber', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 40, 'searchall' => 1)
399  );
400 
401  const STATUS_DISABLED = 0;
402  const STATUS_ENABLED = 1;
403 
409  public function __construct($db)
410  {
411  $this->db = $db;
412 
413  $this->ismultientitymanaged = 1;
414  $this->isextrafieldmanaged = 1;
415  // User preference
416  $this->clicktodial_loaded = 0;
417 
418  // For cache usage
419  $this->all_permissions_are_loaded = 0;
420  $this->nb_rights = 0;
421 
422  // Force some default values
423  $this->admin = 0;
424  $this->employee = 1;
425 
426  $this->conf = new stdClass();
427  $this->rights = new stdClass();
428  $this->rights->user = new stdClass();
429  $this->rights->user->user = new stdClass();
430  $this->rights->user->self = new stdClass();
431  $this->rights->user->user_advance = new stdClass();
432  $this->rights->user->self_advance = new stdClass();
433  $this->rights->user->group_advance = new stdClass();
434  }
435 
450  public function fetch($id = 0, $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1, $email = '', $fk_socpeople = 0, $use_email_oauth2 = 0)
451  {
452  global $conf, $user;
453 
454  // Clean parameters
455  $login = trim($login);
456 
457  // Get user
458  $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.civility as civility_code, u.birth, u.job,";
459  $sql .= " u.email, u.email_oauth2, u.personal_email,";
460  $sql .= " u.socialnetworks,";
461  $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile, u.personal_mobile,";
462  $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
463  $sql .= " u.admin, u.login, u.note_private, u.note_public,";
464  $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.api_key,";
465  $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,";
466  $sql .= " u.statut as status, u.lang, u.entity,";
467  $sql .= " u.datec as datec,";
468  $sql .= " u.tms as datem,";
469  $sql .= " u.datelastlogin as datel,";
470  $sql .= " u.datepreviouslogin as datep,";
471  $sql .= " u.flagdelsessionsbefore,";
472  $sql .= " u.iplastlogin,";
473  $sql .= " u.ippreviouslogin,";
474  $sql .= " u.datelastpassvalidation,";
475  $sql .= " u.datestartvalidity,";
476  $sql .= " u.dateendvalidity,";
477  $sql .= " u.photo as photo,";
478  $sql .= " u.openid as openid,";
479  $sql .= " u.accountancy_code,";
480  $sql .= " u.thm,";
481  $sql .= " u.tjm,";
482  $sql .= " u.salary,";
483  $sql .= " u.salaryextra,";
484  $sql .= " u.weeklyhours,";
485  $sql .= " u.color,";
486  $sql .= " u.dateemployment, u.dateemploymentend,";
487  $sql .= " u.fk_warehouse,";
488  $sql .= " u.ref_ext,";
489  $sql .= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode
490  $sql .= " u.national_registration_number,";
491  $sql .= " u.ref_employee,";
492  $sql .= " c.code as country_code, c.label as country,";
493  $sql .= " d.code_departement as state_code, d.nom as state,";
494  $sql .= " s.label as label_establishment, u.fk_establishment";
495  $sql .= " FROM ".$this->db->prefix()."user as u";
496  $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as c ON u.fk_country = c.rowid";
497  $sql .= " LEFT JOIN ".$this->db->prefix()."c_departements as d ON u.fk_state = d.rowid";
498  $sql .= " LEFT JOIN ".$this->db->prefix()."establishment as s ON u.fk_establishment = s.rowid";
499 
500  if ($entity < 0) {
501  if ((!isModEnabled('multicompany') || !getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) && (!empty($user->entity))) {
502  $sql .= " WHERE u.entity IN (0, ".((int) $conf->entity).")";
503  } else {
504  $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
505  }
506  } else {
507  // The fetch was forced on an entity
508  if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
509  $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
510  } else {
511  $sql .= " WHERE u.entity IN (0, ".((int) (($entity != '' && $entity >= 0) ? $entity : $conf->entity)).")"; // search in entity provided in parameter
512  }
513  }
514 
515  if ($sid) {
516  // permet une recherche du user par son SID ActiveDirectory ou Samba
517  $sql .= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."')";
518  } elseif ($login) {
519  $sql .= " AND u.login = '".$this->db->escape($login)."'";
520  } elseif ($email) {
521  $sql .= " AND (u.email = '".$this->db->escape($email)."'";
522  if ($use_email_oauth2) {
523  $sql .= " OR u.email_oauth2 = '".$this->db->escape($email)."'";
524  }
525  $sql .= ")";
526  } elseif ($fk_socpeople > 0) {
527  $sql .= " AND u.fk_socpeople = ".((int) $fk_socpeople);
528  } else {
529  $sql .= " AND u.rowid = ".((int) $id);
530  }
531  $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
532 
533  if ($sid) {
534  // permet une recherche du user par son SID ActiveDirectory ou Samba
535  $sql .= ' '.$this->db->plimit(1);
536  }
537 
538  $resql = $this->db->query($sql);
539  if ($resql) {
540  $num = $this->db->num_rows($resql);
541  if ($num > 1) {
542  $this->error = "USERDUPLICATEFOUND";
543  dol_syslog(get_class($this)."::fetch more than 1 user found", LOG_WARNING);
544 
545  $this->db->free($resql);
546  return 0;
547  }
548 
549  $obj = $this->db->fetch_object($resql);
550  if ($obj) {
551  $this->id = $obj->rowid;
552  $this->ref = $obj->rowid;
553 
554  $this->ref_ext = $obj->ref_ext;
555 
556  $this->ldap_sid = $obj->ldap_sid;
557  $this->civility_code = $obj->civility_code;
558  $this->lastname = $obj->lastname;
559  $this->firstname = $obj->firstname;
560  $this->ref_employee = $obj->ref_employee;
561  $this->national_registration_number = $obj->national_registration_number;
562 
563  $this->employee = $obj->employee;
564 
565  $this->login = $obj->login;
566  $this->gender = $obj->gender;
567  $this->birth = $this->db->jdate($obj->birth);
568  $this->pass_indatabase = $obj->pass;
569  $this->pass_indatabase_crypted = $obj->pass_crypted;
570  $this->pass = $obj->pass;
571  $this->pass_temp = $obj->pass_temp;
572  $this->api_key = dolDecrypt($obj->api_key);
573 
574  $this->address = $obj->address;
575  $this->zip = $obj->zip;
576  $this->town = $obj->town;
577 
578  $this->country_id = $obj->country_id;
579  $this->country_code = $obj->country_id ? $obj->country_code : '';
580  //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
581 
582  $this->state_id = $obj->state_id;
583  $this->state_code = $obj->state_code;
584  $this->state = ($obj->state != '-' ? $obj->state : '');
585 
586  $this->office_phone = $obj->office_phone;
587  $this->office_fax = $obj->office_fax;
588  $this->user_mobile = $obj->user_mobile;
589  $this->personal_mobile = $obj->personal_mobile;
590  $this->email = $obj->email;
591  $this->email_oauth2 = $obj->email_oauth2;
592  $this->personal_email = $obj->personal_email;
593  $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
594  $this->job = $obj->job;
595  $this->signature = $obj->signature;
596  $this->admin = $obj->admin;
597  $this->note_public = $obj->note_public;
598  $this->note_private = $obj->note_private;
599 
600  $this->statut = $obj->status; // deprecated
601  $this->status = $obj->status;
602 
603  $this->photo = $obj->photo;
604  $this->openid = $obj->openid;
605  $this->lang = $obj->lang;
606  $this->entity = $obj->entity;
607  $this->accountancy_code = $obj->accountancy_code;
608  $this->thm = $obj->thm;
609  $this->tjm = $obj->tjm;
610  $this->salary = $obj->salary;
611  $this->salaryextra = $obj->salaryextra;
612  $this->weeklyhours = $obj->weeklyhours;
613  $this->color = $obj->color;
614  $this->dateemployment = $this->db->jdate($obj->dateemployment);
615  $this->dateemploymentend = $this->db->jdate($obj->dateemploymentend);
616 
617  $this->datec = $this->db->jdate($obj->datec);
618  $this->datem = $this->db->jdate($obj->datem);
619  $this->datelastlogin = $this->db->jdate($obj->datel);
620  $this->datepreviouslogin = $this->db->jdate($obj->datep);
621  $this->flagdelsessionsbefore = $this->db->jdate($obj->flagdelsessionsbefore, 'gmt');
622  $this->iplastlogin = $obj->iplastlogin;
623  $this->ippreviouslogin = $obj->ippreviouslogin;
624  $this->datestartvalidity = $this->db->jdate($obj->datestartvalidity);
625  $this->dateendvalidity = $this->db->jdate($obj->dateendvalidity);
626 
627  $this->socid = $obj->fk_soc;
628  $this->contact_id = $obj->fk_socpeople;
629  $this->fk_member = $obj->fk_member;
630  $this->fk_user = $obj->fk_user;
631  $this->fk_user_expense_validator = $obj->fk_user_expense_validator;
632  $this->fk_user_holiday_validator = $obj->fk_user_holiday_validator;
633 
634  $this->default_range = $obj->default_range;
635  $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
636  $this->fk_warehouse = $obj->fk_warehouse;
637  $this->fk_establishment = $obj->fk_establishment;
638  $this->label_establishment = $obj->label_establishment;
639 
640  // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
641  // in such case, this admin user must be admin for ALL entities.
642  if (!isModEnabled('multicompany') && $this->admin && $this->entity == 1) {
643  $this->entity = 0;
644  }
645 
646  // Retrieve all extrafield
647  // fetch optionals attributes and labels
648  $this->fetch_optionals();
649 
650  $this->db->free($resql);
651  } else {
652  $this->error = "USERNOTFOUND";
653  dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
654 
655  $this->db->free($resql);
656  return 0;
657  }
658  } else {
659  $this->error = $this->db->lasterror();
660  return -1;
661  }
662 
663  // To get back the global configuration unique to the user
664  if ($loadpersonalconf) {
665  $result = $this->loadPersonalConf();
666 
667  $result = $this->loadDefaultValues();
668 
669  if ($result < 0) {
670  $this->error = $this->db->lasterror();
671  return -3;
672  }
673  }
674 
675  return 1;
676  }
677 
678 
684  public function loadPersonalConf()
685  {
686  global $conf;
687 
688  // Load user->conf for user
689  $sql = "SELECT param, value FROM ".$this->db->prefix()."user_param";
690  $sql .= " WHERE fk_user = ".((int) $this->id);
691  $sql .= " AND entity = ".((int) $conf->entity);
692  //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
693  $resql = $this->db->query($sql);
694  if ($resql) {
695  $num = $this->db->num_rows($resql);
696  $i = 0;
697  while ($i < $num) {
698  $obj = $this->db->fetch_object($resql);
699  $p = (!empty($obj->param) ? $obj->param : '');
700  if (!empty($p)) {
701  $this->conf->$p = $obj->value;
702  }
703  $i++;
704  }
705  $this->db->free($resql);
706 
707  return $num;
708  } else {
709  $this->error = $this->db->lasterror();
710 
711  return -2;
712  }
713  }
714 
720  public function loadDefaultValues()
721  {
722  global $conf;
723 
724  if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
725  // Load user->default_values for user. TODO Save this in memcached ?
726  require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php';
727 
728  $defaultValues = new DefaultValues($this->db);
729  $result = $defaultValues->fetchAll('', '', 0, 0, '(t.user_id:in:0,'.$this->id.') AND (entity:in:'.(isset($this->entity) ? $this->entity : $conf->entity).','.$conf->entity.')'); // User 0 (all) + me (if defined)
730  //$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)
731 
732  if (!is_array($result) && $result < 0) {
733  setEventMessages($defaultValues->error, $defaultValues->errors, 'errors');
734  dol_print_error($this->db);
735  return -1;
736  } elseif (count($result) > 0) {
737  foreach ($result as $defval) {
738  if (!empty($defval->page) && !empty($defval->type) && !empty($defval->param)) {
739  $pagewithoutquerystring = $defval->page;
740  $pagequeries = '';
741  $reg = array();
742  if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
743  $pagewithoutquerystring = $reg[1];
744  $pagequeries = $reg[2];
745  }
746  $this->default_values[$pagewithoutquerystring][$defval->type][$pagequeries ? $pagequeries : '_noquery_'][$defval->param] = $defval->value;
747  }
748  }
749  }
750  if (!empty($this->default_values)) {
751  foreach ($this->default_values as $a => $b) {
752  foreach ($b as $c => $d) {
753  krsort($this->default_values[$a][$c]);
754  }
755  }
756  }
757  }
758  return 1;
759  }
760 
772  public function hasRight($module, $permlevel1, $permlevel2 = '')
773  {
774  // For compatibility with bad naming permissions on module
775  $moduletomoduletouse = array(
776  'compta' => 'comptabilite',
777  'contract' => 'contrat',
778  'member' => 'adherent',
779  'mo' => 'mrp',
780  'order' => 'commande',
781  'produit' => 'product',
782  'project' => 'projet',
783  'propale' => 'propal',
784  'shipping' => 'expedition',
785  'task' => 'task@projet',
786  'fichinter' => 'ficheinter',
787  'inventory' => 'stock',
788  'invoice' => 'facture',
789  'invoice_supplier' => 'fournisseur',
790  'order_supplier' => 'fournisseur',
791  'knowledgerecord' => 'knowledgerecord@knowledgemanagement',
792  'skill@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
793  'job@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
794  'position@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
795  'facturerec' => 'facture',
796  'margins' => 'margin',
797  );
798 
799  if (!empty($moduletomoduletouse[$module])) {
800  $module = $moduletomoduletouse[$module];
801  }
802 
803  $moduleRightsMapping = array(
804  'product' => 'produit',
805  'margin' => 'margins',
806  'comptabilite' => 'compta'
807  );
808 
809  $rightsPath = $module;
810  if (!empty($moduleRightsMapping[$rightsPath])) {
811  $rightsPath = $moduleRightsMapping[$rightsPath];
812  }
813 
814  // If module is abc@module, we check permission user->hasRight(module, abc, permlevel1)
815  $tmp = explode('@', $rightsPath, 2);
816  if (!empty($tmp[1])) {
817  if (strpos($module, '@') !== false) {
818  $module = $tmp[1];
819  }
820  if ($tmp[0] != $tmp[1]) {
821  // If $module = 'myobject@mymodule'
822  $rightsPath = $tmp[1];
823  $permlevel2 = $permlevel1;
824  $permlevel1 = $tmp[0];
825  } else {
826  // If $module = 'abc@abc'
827  $rightsPath = $tmp[1];
828  }
829  }
830 
831  // In $conf->modules, we have 'accounting', 'product', 'facture', ...
832  // In $user->rights, we have 'accounting', 'produit', 'facture', ...
833  //var_dump($this->rights->$rightsPath);
834  //var_dump($conf->modules);
835  //var_dump($module.' '.isModEnabled($module).' '.$rightsPath.' '.$permlevel1.' '.$permlevel2);
836  if (!isModEnabled($module)) {
837  return 0;
838  }
839 
840  // Special case for external user
841  if (!empty($this->socid)) {
842  if ($module == 'societe' && ($permlevel1 == 'creer' || $permlevel1 == 'write')) {
843  return 0; // An external user never has the permission ->societe->write to see all thirdparties (always restricted to himself)
844  }
845  if ($module == 'societe' && $permlevel1 == 'client' && $permlevel2 == 'voir') {
846  return 0; // An external user never has the permission ->societe->client->voir to see all thirdparties (always restricted to himself)
847  }
848  if ($module == 'societe' && $permlevel1 == 'export') {
849  return 0; // An external user never has the permission ->societe->export to see all thirdparties (always restricted to himself)
850  }
851  if ($module == 'societe' && ($permlevel1 == 'supprimer' || $permlevel1 == 'delete')) {
852  return 0; // An external user never has the permission ->societe->delete to see all thirdparties (always restricted to himself)
853  }
854  }
855 
856  // For compatibility with bad naming permissions on permlevel1
857  if ($permlevel1 == 'propale') {
858  $permlevel1 = 'propal';
859  }
860  if ($permlevel1 == 'member') {
861  $permlevel1 = 'adherent';
862  }
863  if ($permlevel1 == 'recruitmentcandidature') {
864  $permlevel1 = 'recruitmentjobposition';
865  }
866 
867  //var_dump($this->rights);
868  //var_dump($rightsPath.' '.$permlevel1.' '.$permlevel2);
869  if (empty($rightsPath) || empty($this->rights) || empty($this->rights->$rightsPath) || empty($permlevel1)) {
870  return 0;
871  }
872 
873  if ($permlevel2) {
874  if (!empty($this->rights->$rightsPath->$permlevel1)) {
875  if (!empty($this->rights->$rightsPath->$permlevel1->$permlevel2)) {
876  return $this->rights->$rightsPath->$permlevel1->$permlevel2;
877  }
878  // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
879  // instead of "read", "write", "delete"
880  if ($permlevel2 == 'read' && !empty($this->rights->$rightsPath->$permlevel1->lire)) {
881  return $this->rights->$rightsPath->$permlevel1->lire;
882  }
883  if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->creer)) {
884  return $this->rights->$rightsPath->$permlevel1->creer;
885  }
886  if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->create)) {
887  return $this->rights->$rightsPath->$permlevel1->create;
888  }
889  if ($permlevel2 == 'delete' && !empty($this->rights->$rightsPath->$permlevel1->supprimer)) {
890  return $this->rights->$rightsPath->$permlevel1->supprimer;
891  }
892  }
893  } else {
894  if (!empty($this->rights->$rightsPath->$permlevel1)) {
895  return $this->rights->$rightsPath->$permlevel1;
896  }
897  // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
898  // instead of "read", "write", "delete"
899  if ($permlevel1 == 'read' && !empty($this->rights->$rightsPath->lire)) {
900  return $this->rights->$rightsPath->lire;
901  }
902  if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->creer)) {
903  return $this->rights->$rightsPath->creer;
904  }
905  if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->create)) {
906  return $this->rights->$rightsPath->create;
907  }
908  if ($permlevel1 == 'delete' && !empty($this->rights->$rightsPath->supprimer)) {
909  return $this->rights->$rightsPath->supprimer;
910  }
911  }
912 
913  return 0;
914  }
915 
927  public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
928  {
929  global $conf, $user, $langs;
930 
931  $entity = (empty($entity) ? $conf->entity : $entity);
932 
933  dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity, $notrigger for user id=".$this->id);
934 
935  if (empty($this->id)) {
936  $this->error = 'Try to call addrights on an object user with an empty id';
937  return -1;
938  }
939 
940  $error = 0;
941  $whereforadd = '';
942 
943  $this->db->begin();
944 
945  if (!empty($rid)) {
946  $module = $perms = $subperms = '';
947 
948  // If we ask to add a given permission, we first load properties of this permission (module, perms and subperms).
949  $sql = "SELECT module, perms, subperms";
950  $sql .= " FROM ".$this->db->prefix()."rights_def";
951  $sql .= " WHERE id = ".((int) $rid);
952  $sql .= " AND entity = ".((int) $entity);
953 
954  $result = $this->db->query($sql);
955  if ($result) {
956  $obj = $this->db->fetch_object($result);
957 
958  if ($obj) {
959  $module = $obj->module;
960  $perms = $obj->perms;
961  $subperms = $obj->subperms;
962  }
963  } else {
964  $error++;
965  dol_print_error($this->db);
966  }
967 
968  // Define the where for the permission to add
969  $whereforadd = "id=".((int) $rid);
970  // Add also inherited permissions
971  if (!empty($subperms)) {
972  $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))";
973  } elseif (!empty($perms)) {
974  $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND subperms IS NULL)";
975  }
976  } else {
977  // A list of permission was requested (not a single specific permission)
978  // based on the name of a module of permissions
979  // Used in the where clause to determine the list of permissions to add.
980  if (!empty($allmodule)) {
981  if ($allmodule == 'allmodules') {
982  $whereforadd = 'allmodules';
983  } else {
984  $whereforadd = "module='".$this->db->escape($allmodule)."'";
985  if (!empty($allperms)) {
986  $whereforadd .= " AND perms='".$this->db->escape($allperms)."'";
987  }
988  }
989  }
990  }
991 
992  // Add automatically other permission using the criteria whereforadd
993  // $whereforadd can be a SQL filter or the string 'allmodules'
994  if (!empty($whereforadd)) {
995  //print "$module-$perms-$subperms";
996  $sql = "SELECT id";
997  $sql .= " FROM ".$this->db->prefix()."rights_def";
998  $sql .= " WHERE entity = ".((int) $entity);
999  if (!empty($whereforadd) && $whereforadd != 'allmodules') {
1000  $sql .= " AND (".$whereforadd.")"; // Note: parenthesis are important because whereforadd can contains OR. Also note that $whereforadd is already sanitized
1001  }
1002 
1003  $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1004  $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1005  $sqldelete .= $sql;
1006  $sqldelete .= ") AND entity = ".((int) $entity);
1007  if (!$this->db->query($sqldelete)) {
1008  $error++;
1009  }
1010 
1011  if (!$error) {
1012  $resql = $this->db->query($sql);
1013  if ($resql) {
1014  $num = $this->db->num_rows($resql);
1015  $i = 0;
1016  while ($i < $num) {
1017  $obj = $this->db->fetch_object($resql);
1018 
1019  if ($obj) {
1020  $nid = $obj->id;
1021 
1022  $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id) VALUES (".((int) $entity).", ".((int) $this->id).", ".((int) $nid).")";
1023  if (!$this->db->query($sql)) {
1024  $error++;
1025  }
1026  }
1027 
1028  $i++;
1029  }
1030  } else {
1031  $error++;
1032  dol_print_error($this->db);
1033  }
1034  }
1035  }
1036 
1037  if (!$error && !$notrigger) {
1038  $langs->load("other");
1039  $this->context = array('audit' => $langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : ''));
1040 
1041  // Call trigger
1042  $result = $this->call_trigger('USER_MODIFY', $user);
1043  if ($result < 0) {
1044  $error++;
1045  }
1046  // End call triggers
1047  }
1048 
1049  if ($error) {
1050  $this->db->rollback();
1051  return -$error;
1052  } else {
1053  $this->db->commit();
1054  return 1;
1055  }
1056  }
1057 
1058 
1070  public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1071  {
1072  global $conf, $user, $langs;
1073 
1074  $error = 0;
1075  $wherefordel = '';
1076  $entity = (!empty($entity) ? $entity : $conf->entity);
1077 
1078  $this->db->begin();
1079 
1080  if (!empty($rid)) {
1081  $module = $perms = $subperms = '';
1082 
1083  // When the request is to delete a specific permissions, this gets the
1084  // les charactis for the module, permissions and sub-permission of this permission.
1085  $sql = "SELECT module, perms, subperms";
1086  $sql .= " FROM ".$this->db->prefix()."rights_def";
1087  $sql .= " WHERE id = '".$this->db->escape($rid)."'";
1088  $sql .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1089 
1090  $result = $this->db->query($sql);
1091  if ($result) {
1092  $obj = $this->db->fetch_object($result);
1093 
1094  if ($obj) {
1095  $module = $obj->module;
1096  $perms = $obj->perms;
1097  $subperms = $obj->subperms;
1098  }
1099  } else {
1100  $error++;
1101  dol_print_error($this->db);
1102  }
1103 
1104  // Where clause for the list of permissions to delete
1105  $wherefordel = "id=".((int) $rid);
1106  // Suppression des droits induits
1107  if ($subperms == 'lire' || $subperms == 'read') {
1108  $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)";
1109  }
1110  if ($perms == 'lire' || $perms == 'read') {
1111  $wherefordel .= " OR (module='".$this->db->escape($module)."')";
1112  }
1113  } else {
1114  // The deletion of the permissions concerns the name of a module or
1115  // list of permissions.
1116  // Used in the Where clause to determine the list of permission to delete
1117  if (!empty($allmodule)) {
1118  if ($allmodule == 'allmodules') {
1119  $wherefordel = 'allmodules';
1120  } else {
1121  $wherefordel = "module='".$this->db->escape($allmodule)."'";
1122  if (!empty($allperms)) {
1123  $wherefordel .= " AND perms='".$this->db->escape($allperms)."'";
1124  }
1125  }
1126  }
1127  }
1128 
1129  // Delete permission according to a criteria set into $wherefordel
1130  if (!empty($wherefordel)) {
1131  //print "$module-$perms-$subperms";
1132  $sql = "SELECT id";
1133  $sql .= " FROM ".$this->db->prefix()."rights_def";
1134  $sql .= " WHERE entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1135  if (!empty($wherefordel) && $wherefordel != 'allmodules') {
1136  $sql .= " AND (".$wherefordel.")"; // Note: parenthesis are important because wherefordel can contains OR. Also note that $wherefordel is already sanitized
1137  }
1138 
1139  // avoid admin to remove his own important rights
1140  if ($this->admin == 1) {
1141  $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
1142  $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
1143  $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
1144  $sql .= " AND id NOT IN (358)"; // user export
1145  }
1146 
1147  $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1148  $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1149  $sqldelete .= $sql;
1150  $sqldelete .= ")";
1151  $sqldelete .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1152 
1153  $resql = $this->db->query($sqldelete);
1154  if (!$resql) {
1155  $error++;
1156  dol_print_error($this->db);
1157  }
1158  }
1159 
1160  if (!$error && !$notrigger) {
1161  $langs->load("other");
1162  $this->context = array('audit' => $langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : ''));
1163 
1164  // Call trigger
1165  $result = $this->call_trigger('USER_MODIFY', $user);
1166  if ($result < 0) {
1167  $error++;
1168  }
1169  // End call triggers
1170  }
1171 
1172  if ($error) {
1173  $this->db->rollback();
1174  return -$error;
1175  } else {
1176  $this->db->commit();
1177  return 1;
1178  }
1179  }
1180 
1181 
1188  public function clearrights()
1189  {
1190  dol_syslog(get_class($this)."::clearrights reset user->rights");
1191  $this->rights = new stdClass();
1192  $this->nb_rights = 0;
1193  $this->all_permissions_are_loaded = 0;
1194  $this->_tab_loaded = array();
1195  }
1196 
1197 
1206  public function loadRights($moduletag = '', $forcereload = 0)
1207  {
1208  global $conf;
1209 
1210  $alreadyloaded = false;
1211 
1212  if (empty($forcereload)) {
1213  if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
1214  // Rights for this module are already loaded, so we leave
1215  $alreadyloaded = true;
1216  }
1217 
1218  if (!empty($this->all_permissions_are_loaded)) {
1219  // We already loaded all rights for this user, so we leave
1220  $alreadyloaded = true;
1221  }
1222  }
1223 
1224  // More init to avoid warnings/errors
1225  if (!isset($this->rights) || !is_object($this->rights)) {
1226  $this->rights = new stdClass();
1227  }
1228  if (!isset($this->rights->user) || !is_object($this->rights->user)) {
1229  $this->rights->user = new stdClass();
1230  }
1231 
1232  // Get permission of users + Get permissions of groups
1233 
1234  if (!$alreadyloaded) {
1235  // First user permissions
1236  $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1237  $sql .= " FROM ".$this->db->prefix()."user_rights as ur,";
1238  $sql .= " ".$this->db->prefix()."rights_def as r";
1239  $sql .= " WHERE r.id = ur.fk_id";
1240  if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1241  // on old version, we use entity defined into table r only
1242  $sql .= " AND r.entity IN (0,".(isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') ? "1," : "").$conf->entity.")";
1243  } else {
1244  // On table r=rights_def, the unique key is (id, entity) because id is hard coded into module descriptor and insert during module activation.
1245  // So we must include the filter on entity on both table r. and ur.
1246  $sql .= " AND r.entity = ".((int) $conf->entity)." AND ur.entity = ".((int) $conf->entity);
1247  }
1248  $sql .= " AND ur.fk_user= ".((int) $this->id);
1249  $sql .= " AND r.perms IS NOT NULL";
1250  if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1251  $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1252  }
1253  if ($moduletag) {
1254  $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1255  }
1256 
1257  $resql = $this->db->query($sql);
1258  if ($resql) {
1259  $num = $this->db->num_rows($resql);
1260  $i = 0;
1261  while ($i < $num) {
1262  $obj = $this->db->fetch_object($resql);
1263 
1264  if ($obj) {
1265  $module = $obj->module;
1266  $perms = $obj->perms;
1267  $subperms = $obj->subperms;
1268 
1269  if (!empty($perms)) {
1270  if (!empty($module)) {
1271  if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1272  $this->rights->$module = new stdClass();
1273  }
1274  if (!empty($subperms)) {
1275  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1276  $this->rights->$module->$perms = new stdClass();
1277  }
1278  if (empty($this->rights->$module->$perms->$subperms)) {
1279  $this->nb_rights++;
1280  }
1281  $this->rights->$module->$perms->$subperms = 1;
1282  } else {
1283  if (empty($this->rights->$module->$perms)) {
1284  $this->nb_rights++;
1285  }
1286  $this->rights->$module->$perms = 1;
1287  }
1288  }
1289  }
1290  }
1291  $i++;
1292  }
1293  $this->db->free($resql);
1294  }
1295 
1296  // Now permissions of groups
1297  $sql = "SELECT DISTINCT r.module, r.perms, r.subperms, r.entity";
1298  $sql .= " FROM ".$this->db->prefix()."usergroup_rights as gr,";
1299  $sql .= " ".$this->db->prefix()."usergroup_user as gu,";
1300  $sql .= " ".$this->db->prefix()."rights_def as r";
1301  $sql .= " WHERE r.id = gr.fk_id";
1302  // @FIXME Very strange business rules. Must be alays the same than into user->getrights() user/perms.php and user/group/perms.php
1303  if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1304  if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1305  $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1306  } else {
1307  $sql .= " AND r.entity = ".((int) $conf->entity);
1308  }
1309  } else {
1310  $sql .= " AND gr.entity = ".((int) $conf->entity); // Only groups created in current entity
1311  // The entity on the table gu=usergroup_user should be useless and should never be used because it is already into gr and r.
1312  // but when using MULTICOMPANY_TRANSVERSE_MODE, we may have inserted record that make rubbish result here due to the duplicate record of
1313  // other entities, so we are forced to add a filter on gu here
1314  $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1315  $sql .= " AND r.entity = ".((int) $conf->entity); // Only permission of modules enabled in current entity
1316  }
1317  // End of strange business rule
1318  $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
1319  $sql .= " AND gu.fk_user = ".((int) $this->id);
1320  $sql .= " AND r.perms IS NOT NULL";
1321  if ($moduletag) {
1322  $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1323  }
1324 
1325  $resql = $this->db->query($sql);
1326  if ($resql) {
1327  $num = $this->db->num_rows($resql);
1328  $i = 0;
1329  while ($i < $num) {
1330  $obj = $this->db->fetch_object($resql);
1331 
1332  if ($obj) {
1333  $module = $obj->module;
1334  $perms = $obj->perms;
1335  $subperms = $obj->subperms;
1336 
1337  if (!empty($perms)) {
1338  if (!empty($module)) {
1339  if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1340  $this->rights->$module = new stdClass();
1341  }
1342  if (!empty($subperms)) {
1343  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1344  $this->rights->$module->$perms = new stdClass();
1345  }
1346  if (empty($this->rights->$module->$perms->$subperms)) { // already counted
1347  $this->nb_rights++;
1348  }
1349  $this->rights->$module->$perms->$subperms = 1;
1350  } else {
1351  if (empty($this->rights->$module->$perms)) { // already counted
1352  $this->nb_rights++;
1353  }
1354  // 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
1355  if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1356  $this->rights->$module->$perms = 1;
1357  }
1358  }
1359  }
1360  }
1361  }
1362  $i++;
1363  }
1364  $this->db->free($resql);
1365  }
1366 
1367  // Force permission on user for admin
1368  if (!empty($this->admin)) {
1369  if (empty($this->rights->user->user)) {
1370  $this->rights->user->user = new stdClass();
1371  }
1372  $listofpermtotest = array('lire', 'creer', 'password', 'supprimer', 'export');
1373  foreach ($listofpermtotest as $permtotest) {
1374  if (empty($this->rights->user->user->$permtotest)) {
1375  $this->rights->user->user->$permtotest = 1;
1376  $this->nb_rights++;
1377  }
1378  }
1379  if (empty($this->rights->user->self)) {
1380  $this->rights->user->self = new stdClass();
1381  }
1382  $listofpermtotest = array('creer', 'password');
1383  foreach ($listofpermtotest as $permtotest) {
1384  if (empty($this->rights->user->self->$permtotest)) {
1385  $this->rights->user->self->$permtotest = 1;
1386  $this->nb_rights++;
1387  }
1388  }
1389  // Add test on advanced permissions
1390  if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1391  if (empty($this->rights->user->user_advance)) {
1392  $this->rights->user->user_advance = new stdClass();
1393  }
1394  $listofpermtotest = array('readperms', 'write');
1395  foreach ($listofpermtotest as $permtotest) {
1396  if (empty($this->rights->user->user_advance->$permtotest)) {
1397  $this->rights->user->user_advance->$permtotest = 1;
1398  $this->nb_rights++;
1399  }
1400  }
1401  if (empty($this->rights->user->self_advance)) {
1402  $this->rights->user->self_advance = new stdClass();
1403  }
1404  $listofpermtotest = array('readperms', 'writeperms');
1405  foreach ($listofpermtotest as $permtotest) {
1406  if (empty($this->rights->user->self_advance->$permtotest)) {
1407  $this->rights->user->self_advance->$permtotest = 1;
1408  $this->nb_rights++;
1409  }
1410  }
1411  if (empty($this->rights->user->group_advance)) {
1412  $this->rights->user->group_advance = new stdClass();
1413  }
1414  $listofpermtotest = array('read', 'readperms', 'write', 'delete');
1415  foreach ($listofpermtotest as $permtotest) {
1416  if (empty($this->rights->user) || empty($this->rights->user->group_advance->$permtotest)) {
1417  $this->rights->user->group_advance->$permtotest = 1;
1418  $this->nb_rights++;
1419  }
1420  }
1421  }
1422  }
1423 
1424  // For backward compatibility
1425  if (isset($this->rights->propale) && !isset($this->rights->propal)) {
1426  $this->rights->propal = $this->rights->propale;
1427  }
1428  if (isset($this->rights->propal) && !isset($this->rights->propale)) {
1429  $this->rights->propale = $this->rights->propal;
1430  }
1431 
1432  if (!$moduletag) {
1433  // If the module was not define, then everything is loaded.
1434  // Therefore, we can consider that the permissions are cached
1435  // because they were all loaded for this user instance.
1436  $this->all_permissions_are_loaded = 1;
1437  } else {
1438  // If the module is defined, we flag it as loaded into cache
1439  $this->_tab_loaded[$moduletag] = 1;
1440  }
1441  }
1442  }
1443 
1455  public function getrights($moduletag = '', $forcereload = 0)
1456  {
1457  $this->loadRights($moduletag, $forcereload);
1458  }
1459 
1466  public function setstatus($status)
1467  {
1468  global $conf, $langs, $user;
1469 
1470  $error = 0;
1471 
1472  // Check parameters
1473  if (isset($this->statut)) {
1474  if ($this->statut == $status) {
1475  return 0;
1476  }
1477  } elseif (isset($this->status) && $this->status == $status) {
1478  return 0;
1479  }
1480 
1481  $this->db->begin();
1482 
1483  // Save in database
1484  $sql = "UPDATE ".$this->db->prefix()."user";
1485  $sql .= " SET statut = ".((int) $status);
1486  $sql .= " WHERE rowid = ".((int) $this->id);
1487  $result = $this->db->query($sql);
1488 
1489  dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1490  if ($result) {
1491  if ($status == 0) {
1492  $this->context['actionmsg'] = 'User '.$this->login.' disabled';
1493  } else {
1494  $this->context['actionmsg'] = 'User '.$this->login.' enabled';
1495  }
1496  // Call trigger
1497  $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
1498  if ($result < 0) {
1499  $error++;
1500  }
1501  // End call triggers
1502  }
1503 
1504  if ($error) {
1505  $this->db->rollback();
1506  return -$error;
1507  } else {
1508  $this->status = $status;
1509  $this->statut = $status;
1510  $this->db->commit();
1511  return 1;
1512  }
1513  }
1514 
1525  public function setCategories($categories)
1526  {
1527  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1528  return parent::setCategoriesCommon($categories, Categorie::TYPE_USER);
1529  }
1530 
1537  public function delete(User $user)
1538  {
1539  global $conf, $langs;
1540 
1541  $error = 0;
1542 
1543  $this->db->begin();
1544 
1545  $this->fetch($this->id);
1546 
1547  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1548 
1549  // Remove rights
1550  $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1551 
1552  if (!$error && !$this->db->query($sql)) {
1553  $error++;
1554  $this->error = $this->db->lasterror();
1555  }
1556 
1557  // Remove group
1558  $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1559  if (!$error && !$this->db->query($sql)) {
1560  $error++;
1561  $this->error = $this->db->lasterror();
1562  }
1563 
1564  // Remove params
1565  $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1566  if (!$error && !$this->db->query($sql)) {
1567  $error++;
1568  $this->error = $this->db->lasterror();
1569  }
1570 
1571  // If contact, remove link
1572  if ($this->contact_id > 0) {
1573  $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1574  if (!$error && !$this->db->query($sql)) {
1575  $error++;
1576  $this->error = $this->db->lasterror();
1577  }
1578  }
1579 
1580  // Remove extrafields
1581  if (!$error) {
1582  $result = $this->deleteExtraFields();
1583  if ($result < 0) {
1584  $error++;
1585  dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1586  }
1587  }
1588 
1589  // Remove user
1590  if (!$error) {
1591  $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1592  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1593  if (!$this->db->query($sql)) {
1594  $error++;
1595  $this->error = $this->db->lasterror();
1596  }
1597  }
1598 
1599  if (!$error) {
1600  // Call trigger
1601  $result = $this->call_trigger('USER_DELETE', $user);
1602  if ($result < 0) {
1603  $error++;
1604  $this->db->rollback();
1605  return -1;
1606  }
1607  // End call triggers
1608 
1609  $this->db->commit();
1610  return 1;
1611  } else {
1612  $this->db->rollback();
1613  return -1;
1614  }
1615  }
1616 
1624  public function create($user, $notrigger = 0)
1625  {
1626  global $conf, $langs;
1627  global $mysoc;
1628 
1629  // Clean parameters
1630  $this->setUpperOrLowerCase();
1631 
1632  $this->civility_code = trim((string) $this->civility_code);
1633  $this->login = trim((string) $this->login);
1634  if (!isset($this->entity)) {
1635  $this->entity = $conf->entity; // If not defined, we use default value
1636  }
1637 
1638  dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1639 
1640  $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1641 
1642  // Check parameters
1643  if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
1644  $langs->load("errors");
1645  $this->error = $langs->trans("ErrorBadEMail", $this->email);
1646  return -1;
1647  }
1648  if (empty($this->login)) {
1649  $langs->load("errors");
1650  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1651  return -1;
1652  } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1653  $langs->load("errors");
1654  $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1655  return -1;
1656  }
1657 
1658  $this->datec = dol_now();
1659 
1660  $error = 0;
1661  $this->db->begin();
1662 
1663  // Check if login already exists in same entity or into entity 0.
1664  if ($this->login) {
1665  $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)."'";
1666  $resqltochecklogin = $this->db->query($sqltochecklogin);
1667  if ($resqltochecklogin) {
1668  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1669  if ($objtochecklogin && $objtochecklogin->nb > 0) {
1670  $langs->load("errors");
1671  $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1672  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1673  $this->db->rollback();
1674  return -6;
1675  }
1676  $this->db->free($resqltochecklogin);
1677  }
1678  }
1679  if (!empty($this->email)) {
1680  $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)."'";
1681  $resqltochecklogin = $this->db->query($sqltochecklogin);
1682  if ($resqltochecklogin) {
1683  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1684  if ($objtochecklogin && $objtochecklogin->nb > 0) {
1685  $langs->load("errors");
1686  $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1687  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1688  $this->db->rollback();
1689  return -6;
1690  }
1691  $this->db->free($resqltochecklogin);
1692  }
1693  }
1694 
1695  // Insert into database
1696  $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, entity)";
1697  $sql .= " VALUES('".$this->db->idate($this->datec)."', '".$this->db->escape($this->login)."', '".$this->db->escape($this->ldap_sid)."', ".((int) $this->entity).")";
1698  $result = $this->db->query($sql);
1699 
1700  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1701  if ($result) {
1702  $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1703 
1704  // Set default rights
1705  if ($this->set_default_rights() < 0) {
1706  $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1707  $this->db->rollback();
1708  return -5;
1709  }
1710 
1711  if (getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && getDolGlobalString('STOCK_USERSTOCK_AUTOCREATE')) {
1712  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1713  $langs->load("stocks");
1714 
1715  $entrepot = new Entrepot($this->db);
1716  $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1717  $entrepot->libelle = $entrepot->label; // For backward compatibility
1718  $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1719  $entrepot->statut = 1;
1720  $entrepot->country_id = $mysoc->country_id;
1721 
1722  $warehouseid = $entrepot->create($user);
1723 
1724  $this->fk_warehouse = $warehouseid;
1725  }
1726 
1727  // Update minor fields
1728  $result = $this->update($user, 1, 1);
1729  if ($result < 0) {
1730  $this->db->rollback();
1731  return -4;
1732  }
1733 
1734  if (!$notrigger) {
1735  // Call trigger
1736  $result = $this->call_trigger('USER_CREATE', $user);
1737  if ($result < 0) {
1738  $error++;
1739  }
1740  // End call triggers
1741  }
1742 
1743  if (!$error) {
1744  $this->db->commit();
1745  return $this->id;
1746  } else {
1747  //$this->error=$interface->error;
1748  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1749  $this->db->rollback();
1750  return -3;
1751  }
1752  } else {
1753  $this->error = $this->db->lasterror();
1754  $this->db->rollback();
1755  return -2;
1756  }
1757  }
1758 
1759 
1760  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1769  public function create_from_contact($contact, $login = '', $password = '')
1770  {
1771  // phpcs:enable
1772  global $conf, $user, $langs;
1773 
1774  $error = 0;
1775 
1776  // Define parameters
1777  $this->admin = 0;
1778  $this->civility_code = $contact->civility_code;
1779  $this->lastname = $contact->lastname;
1780  $this->firstname = $contact->firstname;
1781  //$this->gender = $contact->gender; // contact has no gender
1782  $this->email = $contact->email;
1783  $this->socialnetworks = $contact->socialnetworks;
1784  $this->office_phone = $contact->phone_pro;
1785  $this->office_fax = $contact->fax;
1786  $this->user_mobile = $contact->phone_mobile;
1787  $this->address = $contact->address;
1788  $this->zip = $contact->zip;
1789  $this->town = $contact->town;
1790  $this->setUpperOrLowerCase();
1791  $this->state_id = $contact->state_id;
1792  $this->country_id = $contact->country_id;
1793  $this->employee = 0;
1794 
1795  if (empty($login)) {
1796  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1797  $login = dol_buildlogin($contact->lastname, $contact->firstname);
1798  }
1799  $this->login = $login;
1800 
1801  $this->db->begin();
1802 
1803  // Create user and set $this->id. Trigger is disabled because executed later.
1804  $result = $this->create($user, 1);
1805  if ($result > 0) {
1806  $sql = "UPDATE ".$this->db->prefix()."user";
1807  $sql .= " SET fk_socpeople=".((int) $contact->id);
1808  $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
1809  if ($contact->socid > 0) {
1810  $sql .= ", fk_soc=".((int) $contact->socid);
1811  }
1812  $sql .= " WHERE rowid=".((int) $this->id);
1813 
1814  $resql = $this->db->query($sql);
1815 
1816  dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1817  if ($resql) {
1818  $this->context['createfromcontact'] = 'createfromcontact';
1819 
1820  // Call trigger
1821  $result = $this->call_trigger('USER_CREATE', $user);
1822  if ($result < 0) {
1823  $error++;
1824  $this->db->rollback();
1825  return -1;
1826  }
1827  // End call triggers
1828 
1829  $this->db->commit();
1830  return $this->id;
1831  } else {
1832  $this->error = $this->db->error();
1833 
1834  $this->db->rollback();
1835  return -1;
1836  }
1837  } else {
1838  // $this->error deja positionne
1839  dol_syslog(get_class($this)."::create_from_contact - 0");
1840 
1841  $this->db->rollback();
1842  return $result;
1843  }
1844  }
1845 
1846  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1855  public function create_from_member($member, $login = '')
1856  {
1857  // phpcs:enable
1858  global $user;
1859 
1860  // Set properties on new user
1861  $this->admin = 0;
1862  $this->civility_code = $member->civility_code;
1863  $this->lastname = $member->lastname;
1864  $this->firstname = $member->firstname;
1865  $this->gender = $member->gender;
1866  $this->email = $member->email;
1867  $this->fk_member = $member->id;
1868  $this->address = $member->address;
1869  $this->zip = $member->zip;
1870  $this->town = $member->town;
1871  $this->setUpperOrLowerCase();
1872  $this->state_id = $member->state_id;
1873  $this->country_id = $member->country_id;
1874  $this->socialnetworks = $member->socialnetworks;
1875 
1876  $this->pass = $member->pass;
1877  $this->pass_crypted = $member->pass_indatabase_crypted;
1878 
1879  if (empty($login)) {
1880  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1881  $login = dol_buildlogin($member->lastname, $member->firstname);
1882  }
1883  $this->login = $login;
1884 
1885  $this->db->begin();
1886 
1887  // Create and set $this->id
1888  $result = $this->create($user);
1889  if ($result > 0) {
1890  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
1891  $newpass = $this->setPassword($user, $this->pass);
1892  if (is_int($newpass) && $newpass < 0) {
1893  $result = -2;
1894  }
1895  } elseif (!empty($this->pass_crypted)) { // If an encrypted password is already known, we save it directly into database because the previous create did not save it.
1896  $sql = "UPDATE ".$this->db->prefix()."user";
1897  $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
1898  $sql .= " WHERE rowid=".((int) $this->id);
1899 
1900  $resql = $this->db->query($sql);
1901  if (!$resql) {
1902  $result = -1;
1903  }
1904  }
1905 
1906  if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
1907  $sql = "UPDATE ".$this->db->prefix()."user";
1908  $sql .= " SET fk_soc=".((int) $member->socid);
1909  $sql .= " WHERE rowid=".((int) $this->id);
1910 
1911  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
1912  $resql = $this->db->query($sql);
1913  if ($resql) {
1914  $this->db->commit();
1915  return $this->id;
1916  } else {
1917  $this->error = $this->db->lasterror();
1918 
1919  $this->db->rollback();
1920  return -1;
1921  }
1922  }
1923  }
1924 
1925  if ($result > 0) {
1926  $this->db->commit();
1927  return $this->id;
1928  } else {
1929  // $this->error deja positionne
1930  $this->db->rollback();
1931  return -2;
1932  }
1933  }
1934 
1935  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1941  public function set_default_rights()
1942  {
1943  // phpcs:enable
1944  global $conf;
1945 
1946  $rd = array();
1947  $num = 0;
1948  $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
1949  $sql .= " WHERE bydefault = 1";
1950  $sql .= " AND entity = ".((int) $conf->entity);
1951 
1952  $resql = $this->db->query($sql);
1953  if ($resql) {
1954  $num = $this->db->num_rows($resql);
1955  $i = 0;
1956  while ($i < $num) {
1957  $row = $this->db->fetch_row($resql);
1958  $rd[$i] = $row[0];
1959  $i++;
1960  }
1961  $this->db->free($resql);
1962  }
1963  $i = 0;
1964  while ($i < $num) {
1965  $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
1966  $result = $this->db->query($sql);
1967 
1968  $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
1969  $result = $this->db->query($sql);
1970  if (!$result) {
1971  return -1;
1972  }
1973  $i++;
1974  }
1975 
1976  return $i;
1977  }
1978 
1989  public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
1990  {
1991  global $conf, $langs;
1992 
1993  $nbrowsaffected = 0;
1994  $error = 0;
1995 
1996  dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
1997 
1998  // Clean parameters
1999  $this->civility_code = trim((string) $this->civility_code);
2000  $this->lastname = trim((string) $this->lastname);
2001  $this->firstname = trim((string) $this->firstname);
2002  $this->ref_employee = trim((string) $this->ref_employee);
2003  $this->national_registration_number = trim((string) $this->national_registration_number);
2004  $this->employee = ($this->employee > 0 ? $this->employee : 0);
2005  $this->login = trim((string) $this->login);
2006  $this->gender = trim((string) $this->gender);
2007 
2008  $this->pass = trim((string) $this->pass);
2009  $this->api_key = trim((string) $this->api_key);
2010  $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
2011  $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
2012 
2013  $this->address = trim((string) $this->address);
2014  $this->zip = trim((string) $this->zip);
2015  $this->town = trim((string) $this->town);
2016 
2017  $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
2018  $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
2019  $this->office_phone = trim((string) $this->office_phone);
2020  $this->office_fax = trim((string) $this->office_fax);
2021  $this->user_mobile = trim((string) $this->user_mobile);
2022  $this->personal_mobile = trim((string) $this->personal_mobile);
2023  $this->email = trim((string) $this->email);
2024  $this->personal_email = trim((string) $this->personal_email);
2025 
2026  $this->job = trim((string) $this->job);
2027  $this->signature = trim((string) $this->signature);
2028  $this->note_public = trim((string) $this->note_public);
2029  $this->note_private = trim((string) $this->note_private);
2030  $this->openid = trim((string) $this->openid);
2031  $this->admin = ($this->admin > 0 ? $this->admin : 0);
2032 
2033  $this->accountancy_code = trim((string) $this->accountancy_code);
2034  $this->color = trim((string) $this->color);
2035  $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
2036  $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
2037 
2038  $this->birth = empty($this->birth) ? '' : $this->birth;
2039  $this->fk_warehouse = (int) $this->fk_warehouse;
2040  $this->fk_establishment = (int) $this->fk_establishment;
2041 
2042  $this->setUpperOrLowerCase();
2043 
2044  // Check parameters
2045  $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
2046 
2047  if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
2048  $langs->load("errors");
2049  $this->error = $langs->trans("ErrorBadEMail", $this->email);
2050  return -1;
2051  }
2052  if (empty($this->login)) {
2053  $langs->load("errors");
2054  $this->error = $langs->trans("ErrorFieldRequired", 'Login');
2055  return -1;
2056  } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
2057  $langs->load("errors");
2058  $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
2059  return -1;
2060  }
2061 
2062  $this->db->begin();
2063 
2064  // Check if login already exists in same entity or into entity 0.
2065  if (!empty($this->oldcopy) && $this->oldcopy->login != $this->login) {
2066  $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)."'";
2067  $resqltochecklogin = $this->db->query($sqltochecklogin);
2068  if ($resqltochecklogin) {
2069  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2070  if ($objtochecklogin && $objtochecklogin->nb > 0) {
2071  $langs->load("errors");
2072  $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
2073  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2074  $this->db->rollback();
2075  return -1;
2076  }
2077  }
2078  }
2079  if (!empty($this->oldcopy) && !empty($this->email) && $this->oldcopy->email != $this->email) {
2080  $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)."'";
2081  $resqltochecklogin = $this->db->query($sqltochecklogin);
2082  if ($resqltochecklogin) {
2083  $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2084  if ($objtochecklogin && $objtochecklogin->nb > 0) {
2085  $langs->load("errors");
2086  $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
2087  dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2088  $this->db->rollback();
2089  return -1;
2090  }
2091  }
2092  }
2093 
2094  // Update data
2095  $sql = "UPDATE ".$this->db->prefix()."user SET";
2096  $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
2097  $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
2098  $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
2099  $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
2100  $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
2101  $sql .= ", employee = ".(int) $this->employee;
2102  $sql .= ", login = '".$this->db->escape($this->login)."'";
2103  $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
2104  $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' or 'other'
2105  $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
2106  if (!empty($user->admin)) {
2107  $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
2108  }
2109  $sql .= ", address = '".$this->db->escape($this->address)."'";
2110  $sql .= ", zip = '".$this->db->escape($this->zip)."'";
2111  $sql .= ", town = '".$this->db->escape($this->town)."'";
2112  $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".$this->db->escape($this->state_id)."'" : "null");
2113  $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".$this->db->escape($this->country_id)."'" : "null");
2114  $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
2115  $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
2116  $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
2117  $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
2118  $sql .= ", email = '".$this->db->escape($this->email)."'";
2119  $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
2120  $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
2121  $sql .= ", job = '".$this->db->escape($this->job)."'";
2122  $sql .= ", signature = '".$this->db->escape($this->signature)."'";
2123  $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
2124  $sql .= ", color = '".$this->db->escape($this->color)."'";
2125  $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
2126  $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
2127  $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2128  $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2129  $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2130  $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2131  $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2132  $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2133  $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".$this->db->escape($this->fk_user)."'" : "null");
2134  $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".$this->db->escape($this->fk_user_expense_validator)."'" : "null");
2135  $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".$this->db->escape($this->fk_user_holiday_validator)."'" : "null");
2136  if (isset($this->thm) || $this->thm != '') {
2137  $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2138  }
2139  if (isset($this->tjm) || $this->tjm != '') {
2140  $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2141  }
2142  if (isset($this->salary) || $this->salary != '') {
2143  $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2144  }
2145  if (isset($this->salaryextra) || $this->salaryextra != '') {
2146  $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2147  }
2148  $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2149  if (!empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2150  $sql .= ", entity = ".((int) $this->entity); // entity flag can be set/unset only by an another superadmin user
2151  }
2152  $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
2153  $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
2154  $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
2155  $sql .= ", fk_establishment = ".($this->fk_establishment > 0 ? $this->fk_establishment : "null");
2156  $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2157  $sql .= " WHERE rowid = ".((int) $this->id);
2158 
2159  dol_syslog(get_class($this)."::update", LOG_DEBUG);
2160  $resql = $this->db->query($sql);
2161  if ($resql) {
2162  $nbrowsaffected += $this->db->affected_rows($resql);
2163 
2164  // Update password
2165  if (!empty($this->pass)) {
2166  if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2167  // If a new value for password is set and different than the one encrypted into database
2168  $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2169  if (is_int($result) && $result < 0) {
2170  return -5;
2171  }
2172  }
2173  }
2174 
2175  // If user is linked to a member, remove old link to this member
2176  if ($this->fk_member > 0) {
2177  dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2178  $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2179  $resql = $this->db->query($sql);
2180  if (!$resql) {
2181  $this->error = $this->db->error();
2182  $this->db->rollback();
2183  return -5;
2184  }
2185  }
2186  // Set link to user
2187  dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2188  $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2189  $resql = $this->db->query($sql);
2190  if (!$resql) {
2191  $this->error = $this->db->error();
2192  $this->db->rollback();
2193  return -5;
2194  }
2195 
2196  if ($nbrowsaffected) { // If something has changed in data
2197  if ($this->fk_member > 0 && !$nosyncmember) {
2198  dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2199 
2200  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2201 
2202  // This user is linked with a member, so we also update member information
2203  // if this is an update.
2204  $adh = new Adherent($this->db);
2205  $result = $adh->fetch($this->fk_member);
2206 
2207  if ($result > 0) {
2208  $adh->civility_code = $this->civility_code;
2209  $adh->firstname = $this->firstname;
2210  $adh->lastname = $this->lastname;
2211  $adh->login = $this->login;
2212  $adh->gender = $this->gender;
2213  $adh->birth = $this->birth;
2214 
2215  $adh->pass = $this->pass;
2216 
2217  $adh->address = $this->address;
2218  $adh->town = $this->town;
2219  $adh->zip = $this->zip;
2220  $adh->state_id = $this->state_id;
2221  $adh->country_id = $this->country_id;
2222 
2223  $adh->email = $this->email;
2224 
2225  $adh->socialnetworks = $this->socialnetworks;
2226 
2227  $adh->phone = $this->office_phone;
2228  $adh->phone_mobile = $this->user_mobile;
2229 
2230  $adh->default_lang = $this->lang;
2231 
2232  $adh->user_id = $this->id;
2233  $adh->user_login = $this->login;
2234 
2235  $result = $adh->update($user, 0, 1, 0);
2236  if ($result < 0) {
2237  $this->error = $adh->error;
2238  $this->errors = $adh->errors;
2239  dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2240  $error++;
2241  }
2242  } elseif ($result < 0) {
2243  $this->error = $adh->error;
2244  $this->errors = $adh->errors;
2245  $error++;
2246  }
2247  }
2248 
2249  if ($this->contact_id > 0 && !$nosynccontact) {
2250  dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2251 
2252  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2253 
2254  // This user is linked with a contact, so we also update contact information if this is an update.
2255  $tmpobj = new Contact($this->db);
2256  $result = $tmpobj->fetch($this->contact_id);
2257 
2258  if ($result >= 0) {
2259  $tmpobj->civility_code = $this->civility_code;
2260  $tmpobj->firstname = $this->firstname;
2261  $tmpobj->lastname = $this->lastname;
2262  $tmpobj->login = $this->login;
2263  $tmpobj->gender = $this->gender;
2264  $tmpobj->birth = $this->birth;
2265 
2266  //$tmpobj->pass=$this->pass;
2267 
2268  $tmpobj->email = $this->email;
2269 
2270  $tmpobj->socialnetworks = $this->socialnetworks;
2271 
2272  $tmpobj->phone_pro = $this->office_phone;
2273  $tmpobj->phone_mobile = $this->user_mobile;
2274  $tmpobj->fax = $this->office_fax;
2275 
2276  $tmpobj->default_lang = $this->lang;
2277 
2278  $tmpobj->address = $this->address;
2279  $tmpobj->town = $this->town;
2280  $tmpobj->zip = $this->zip;
2281  $tmpobj->state_id = $this->state_id;
2282  $tmpobj->country_id = $this->country_id;
2283 
2284  $tmpobj->user_id = $this->id;
2285  $tmpobj->user_login = $this->login;
2286 
2287  $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2288  if ($result < 0) {
2289  $this->error = $tmpobj->error;
2290  $this->errors = $tmpobj->errors;
2291  dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2292  $error++;
2293  }
2294  } else {
2295  $this->error = $tmpobj->error;
2296  $this->errors = $tmpobj->errors;
2297  $error++;
2298  }
2299  }
2300  }
2301 
2302  $action = 'update';
2303 
2304  // Actions on extra fields
2305  if (!$error) {
2306  $result = $this->insertExtraFields();
2307  if ($result < 0) {
2308  $error++;
2309  }
2310  }
2311 
2312  if (!$error && !$notrigger) {
2313  // Call trigger
2314  $result = $this->call_trigger('USER_MODIFY', $user);
2315  if ($result < 0) {
2316  $error++;
2317  }
2318  // End call triggers
2319  }
2320 
2321  if (!$error) {
2322  $this->db->commit();
2323  return $nbrowsaffected;
2324  } else {
2325  dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2326  $this->db->rollback();
2327  return -1;
2328  }
2329  } else {
2330  $this->error = $this->db->lasterror();
2331  $this->db->rollback();
2332  return -2;
2333  }
2334  }
2335 
2336  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2343  public function update_last_login_date()
2344  {
2345  // phpcs:enable
2346  $now = dol_now();
2347 
2348  $userremoteip = getUserRemoteIP();
2349 
2350  $sql = "UPDATE ".$this->db->prefix()."user SET";
2351  $sql .= " datepreviouslogin = datelastlogin,";
2352  $sql .= " ippreviouslogin = iplastlogin,";
2353  $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2354  $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2355  $sql .= " tms = tms"; // The last update date must change because the last login date is updated
2356  $sql .= " WHERE rowid = ".((int) $this->id);
2357 
2358  dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2359  $resql = $this->db->query($sql);
2360  if ($resql) {
2361  $this->datepreviouslogin = $this->datelastlogin;
2362  $this->datelastlogin = $now;
2363  $this->ippreviouslogin = $this->iplastlogin;
2364  $this->iplastlogin = $userremoteip;
2365  return 1;
2366  } else {
2367  $this->error = $this->db->lasterror().' sql='.$sql;
2368  return -1;
2369  }
2370  }
2371 
2372 
2385  public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2386  {
2387  global $conf, $langs;
2388  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2389 
2390  $error = 0;
2391 
2392  dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2393 
2394  // If new password not provided, we generate one
2395  if (!$password) {
2396  $password = getRandomPassword(false);
2397  }
2398 
2399  // Check and encrypt the password
2400  if (empty($passwordalreadycrypted)) {
2401  if (getDolGlobalString('USER_PASSWORD_GENERATED')) {
2402  // Add a check on rules for password syntax using the setup of the password generator
2403  $modGeneratePassClass = 'modGeneratePass'.ucfirst($conf->global->USER_PASSWORD_GENERATED);
2404 
2405  include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2406  if (class_exists($modGeneratePassClass)) {
2407  $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2408 
2409  // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2410  $modGeneratePass->WithoutAmbi = 0;
2411 
2412  // Call to validatePassword($password) to check pass match rules
2413  $testpassword = $modGeneratePass->validatePassword($password);
2414  if (!$testpassword) {
2415  $this->error = $modGeneratePass->error;
2416  return -1;
2417  }
2418  }
2419  }
2420 
2421 
2422  // Now, we encrypt the new password
2423  $password_crypted = dol_hash($password);
2424  }
2425 
2426  // Update password
2427  if (!$changelater) {
2428  if (!is_object($this->oldcopy)) {
2429  $this->oldcopy = clone $this;
2430  }
2431 
2432  $this->db->begin();
2433 
2434  $sql = "UPDATE ".$this->db->prefix()."user";
2435  $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2436  $sql .= " pass_temp = null";
2437  if (!empty($flagdelsessionsbefore)) {
2438  $sql .= ", flagdelsessionsbefore = '".$this->db->idate(dol_now() - 5, 'gmt')."'";
2439  }
2440  if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
2441  $sql .= ", pass = null";
2442  } else {
2443  $sql .= ", pass = '".$this->db->escape($password)."'";
2444  }
2445  $sql .= " WHERE rowid = ".((int) $this->id);
2446 
2447  dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2448  $result = $this->db->query($sql);
2449  if ($result) {
2450  if ($this->db->affected_rows($result)) {
2451  $this->pass = $password;
2452  $this->pass_indatabase = $password;
2453  $this->pass_indatabase_crypted = $password_crypted;
2454 
2455  if ($this->fk_member && !$nosyncmember) {
2456  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2457 
2458  // This user is linked with a member, so we also update members information
2459  // if this is an update.
2460  $adh = new Adherent($this->db);
2461  $result = $adh->fetch($this->fk_member);
2462 
2463  if ($result >= 0) {
2464  $result = $adh->setPassword($user, $this->pass, (!getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 0 : 1), 1); // The encryption is not managed in the 'adherent' module
2465  if (is_int($result) && $result < 0) {
2466  $this->error = $adh->error;
2467  dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2468  $error++;
2469  }
2470  } else {
2471  $this->error = $adh->error;
2472  $error++;
2473  }
2474  }
2475 
2476  dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2477 
2478  if (!$error && !$notrigger) {
2479  // Call trigger
2480  $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2481  if ($result < 0) {
2482  $error++;
2483  $this->db->rollback();
2484  return -1;
2485  }
2486  // End call triggers
2487  }
2488 
2489  $this->db->commit();
2490  return $this->pass;
2491  } else {
2492  $this->db->rollback();
2493  return 0;
2494  }
2495  } else {
2496  $this->db->rollback();
2497  dol_print_error($this->db);
2498  return -1;
2499  }
2500  } else {
2501  // We store password in password temporary field.
2502  // After receiving confirmation link, we will erase and store it in pass_crypted
2503  $sql = "UPDATE ".$this->db->prefix()."user";
2504  $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2505  $sql .= " WHERE rowid = ".((int) $this->id);
2506 
2507  dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2508  $result = $this->db->query($sql);
2509  if ($result) {
2510  return $password;
2511  } else {
2512  dol_print_error($this->db);
2513  return -3;
2514  }
2515  }
2516  }
2517 
2518  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2527  public function send_password($user, $password = '', $changelater = 0)
2528  {
2529  // phpcs:enable
2530  global $conf, $langs, $mysoc;
2531  global $dolibarr_main_url_root;
2532 
2533  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2534 
2535  $msgishtml = 0;
2536 
2537  // Define $msg
2538  $mesg = '';
2539 
2540  $outputlangs = new Translate("", $conf);
2541 
2542  if (isset($this->conf->MAIN_LANG_DEFAULT)
2543  && $this->conf->MAIN_LANG_DEFAULT != 'auto') { // If user has defined its own language (rare because in most cases, auto is used)
2544  $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2545  }
2546 
2547  if ($this->conf->MAIN_LANG_DEFAULT) {
2548  $outputlangs->setDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2549  } else { // If user has not defined its own language, we used current language
2550  $outputlangs = $langs;
2551  }
2552 
2553  // Load translation files required by the page
2554  $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2555 
2556  $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', constant('DOL_APPLICATION_TITLE'));
2557 
2558  $subject = '['.$appli.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2559 
2560  // Define $urlwithroot
2561  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2562  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2563 
2564  if (!$changelater) {
2565  $url = $urlwithroot.'/';
2566  if (getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD')) {
2567  $url = getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD');
2568  }
2569 
2570  dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2571 
2572  $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2573  $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2574  $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2575  $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2576  $mesg .= "\n";
2577 
2578  $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2579  $mesg .= "--\n";
2580  $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2581  } else {
2582  //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2583  $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2584  $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2585  if (isModEnabled('multicompany')) {
2586  $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2587  }
2588 
2589  dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2590 
2591  $msgishtml = 1;
2592 
2593  $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2594  $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2595  $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2596  $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2597  $mesg .= "<br>\n";
2598  $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2599  $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2600  $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2601  }
2602 
2603  $trackid = 'use'.$this->id;
2604  $sendcontext = 'password';
2605 
2606  $mailfile = new CMailFile(
2607  $subject,
2608  $this->email,
2609  $conf->global->MAIN_MAIL_EMAIL_FROM,
2610  $mesg,
2611  array(),
2612  array(),
2613  array(),
2614  '',
2615  '',
2616  0,
2617  $msgishtml,
2618  '',
2619  '',
2620  $trackid,
2621  '',
2622  $sendcontext
2623  );
2624 
2625  if ($mailfile->sendfile()) {
2626  return 1;
2627  } else {
2628  $langs->trans("errors");
2629  $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2630  return -1;
2631  }
2632  }
2633 
2639  public function error()
2640  {
2641  return $this->error;
2642  }
2643 
2644 
2645  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2651  public function fetch_clicktodial()
2652  {
2653  // phpcs:enable
2654  $sql = "SELECT url, login, pass, poste ";
2655  $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2656  $sql .= " WHERE u.fk_user = ".((int) $this->id);
2657 
2658  $resql = $this->db->query($sql);
2659  if ($resql) {
2660  if ($this->db->num_rows($resql)) {
2661  $obj = $this->db->fetch_object($resql);
2662 
2663  $this->clicktodial_url = $obj->url;
2664  $this->clicktodial_login = $obj->login;
2665  $this->clicktodial_password = $obj->pass;
2666  $this->clicktodial_poste = $obj->poste;
2667  }
2668 
2669  $this->clicktodial_loaded = 1; // Data loaded (found or not)
2670 
2671  $this->db->free($resql);
2672  return 1;
2673  } else {
2674  $this->error = $this->db->error();
2675  return -1;
2676  }
2677  }
2678 
2679  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2685  public function update_clicktodial()
2686  {
2687  // phpcs:enable
2688  $this->db->begin();
2689 
2690  $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2691  $sql .= " WHERE fk_user = ".((int) $this->id);
2692 
2693  dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2694  $result = $this->db->query($sql);
2695 
2696  $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
2697  $sql .= " (fk_user,url,login,pass,poste)";
2698  $sql .= " VALUES (".$this->id;
2699  $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2700  $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2701  $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2702  $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2703 
2704  dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2705  $result = $this->db->query($sql);
2706  if ($result) {
2707  $this->db->commit();
2708  return 1;
2709  } else {
2710  $this->db->rollback();
2711  $this->error = $this->db->lasterror();
2712  return -1;
2713  }
2714  }
2715 
2716 
2717  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2726  public function SetInGroup($group, $entity, $notrigger = 0)
2727  {
2728  // phpcs:enable
2729  global $conf, $langs, $user;
2730 
2731  $error = 0;
2732 
2733  $this->db->begin();
2734 
2735  $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2736  $sql .= " WHERE fk_user = ".((int) $this->id);
2737  $sql .= " AND fk_usergroup = ".((int) $group);
2738  $sql .= " AND entity = ".((int) $entity);
2739 
2740  $result = $this->db->query($sql);
2741 
2742  $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
2743  $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
2744 
2745  $result = $this->db->query($sql);
2746  if ($result) {
2747  if (!$error && !$notrigger) {
2748  $this->context = array('audit' => $langs->trans("UserSetInGroup"), 'newgroupid' => $group);
2749 
2750  // Call trigger
2751  $result = $this->call_trigger('USER_MODIFY', $user);
2752  if ($result < 0) {
2753  $error++;
2754  }
2755  // End call triggers
2756  }
2757 
2758  if (!$error) {
2759  $this->db->commit();
2760  return 1;
2761  } else {
2762  dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2763  $this->db->rollback();
2764  return -2;
2765  }
2766  } else {
2767  $this->error = $this->db->lasterror();
2768  $this->db->rollback();
2769  return -1;
2770  }
2771  }
2772 
2773  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2782  public function RemoveFromGroup($group, $entity, $notrigger = 0)
2783  {
2784  // phpcs:enable
2785  global $conf, $langs, $user;
2786 
2787  $error = 0;
2788 
2789  $this->db->begin();
2790 
2791  $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2792  $sql .= " WHERE fk_user = ".((int) $this->id);
2793  $sql .= " AND fk_usergroup = ".((int) $group);
2794  if (empty($entity)) {
2795  $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
2796  } else {
2797  $sql .= " AND entity = ".((int) $entity);
2798  }
2799 
2800  $result = $this->db->query($sql);
2801  if ($result) {
2802  if (!$error && !$notrigger) {
2803  $this->context = array('audit' => $langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
2804 
2805  // Call trigger
2806  $result = $this->call_trigger('USER_MODIFY', $user);
2807  if ($result < 0) {
2808  $error++;
2809  }
2810  // End call triggers
2811  }
2812 
2813  if (!$error) {
2814  $this->db->commit();
2815  return 1;
2816  } else {
2817  dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2818  $this->db->rollback();
2819  return -2;
2820  }
2821  } else {
2822  $this->error = $this->db->lasterror();
2823  $this->db->rollback();
2824  return -1;
2825  }
2826  }
2827 
2828 
2835  public function isNotIntoValidityDateRange()
2836  {
2837  include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2838 
2839  $now = dol_now();
2840 
2841  //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
2842 
2843  // Check date start validity
2844  if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
2845  return 1;
2846  }
2847  // Check date end validity
2848  if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
2849  return 1;
2850  }
2851 
2852  return 0;
2853  }
2854 
2855 
2867  public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
2868  {
2869  $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2870  $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
2871  $result .= '</a>';
2872 
2873  return $result;
2874  }
2875 
2883  public function getTooltipContentArray($params)
2884  {
2885  global $conf, $langs, $menumanager;
2886  global $dolibarr_main_demo;
2887 
2888  $infologin = $params['infologin'] ?? 0;
2889  $option = $params['option'] ?? '';
2890 
2891  $data = [];
2892  if (!empty($this->photo)) {
2893  $photo = '<div class="photointooltip floatright">';
2894  $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
2895  $photo .= '</div>';
2896  $data['photo'] = $photo;
2897  //$label .= '<div style="clear: both;"></div>';
2898  }
2899 
2900  // Info Login
2901  $data['opendiv'] = '<div class="centpercent divtooltip">';
2902  $data['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
2903  $data['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs, ''));
2904  if (!empty($this->login)) {
2905  $data['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
2906  }
2907  if (!empty($this->job)) {
2908  $data['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
2909  }
2910  $data['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
2911  if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
2912  $phonelist = array();
2913  if ($this->office_phone) {
2914  $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2915  }
2916  if ($this->office_fax) {
2917  $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2918  }
2919  if ($this->user_mobile) {
2920  $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
2921  }
2922  $data['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
2923  }
2924  if (!empty($this->admin)) {
2925  $data['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
2926  }
2927  if (!empty($this->accountancy_code) || $option == 'accountancy') {
2928  $langs->load("companies");
2929  $data['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
2930  }
2931  $company = '';
2932  if (!empty($this->socid)) { // Add thirdparty for external users
2933  $thirdpartystatic = new Societe($this->db);
2934  $thirdpartystatic->fetch($this->socid);
2935  $companyimg = '';
2936  if (empty($params['hidethirdpartylogo'])) {
2937  $companyimg = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2938  }
2939  $company = ' ('.$langs->trans("Company").': '.($companyimg ? $companyimg : img_picto('', 'company')).' '.dol_string_nohtmltag($thirdpartystatic->name).')';
2940  }
2941  $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
2942  $data['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
2943  $data['closediv'] = '</div>';
2944 
2945  if ($infologin > 0) {
2946  $data['newlinelogin'] = '<br>';
2947  $data['session'] = '<br><u>'.$langs->trans("Session").'</u>';
2948  $data['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
2949  if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
2950  $data['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
2951  }
2952  $data['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
2953  $data['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
2954  $data['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
2955  $data['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
2956  $data['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
2957  $s = picto_from_langcode($langs->getDefaultLang());
2958  $data['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
2959  $data['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
2960  $data['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
2961  $data['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
2962  if ($conf->browser->layout == 'phone') {
2963  $data['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
2964  }
2965  if (!empty($_SESSION["disablemodules"])) {
2966  $data['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(implode(', ', explode(',', $_SESSION["disablemodules"])));
2967  }
2968  }
2969 
2970  return $data;
2971  }
2972 
2988  public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
2989  {
2990  global $langs, $conf, $db, $hookmanager, $user;
2991  global $dolibarr_main_authentication, $dolibarr_main_demo;
2992 
2993  if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
2994  $option = 'nolink';
2995  }
2996 
2997  if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
2998  $withpictoimg = 0;
2999  }
3000 
3001  $result = '';
3002  $params = [
3003  'id' => $this->id,
3004  'objecttype' => $this->element,
3005  'infologin' => $infologin,
3006  'option' => $option,
3007  'hidethirdpartylogo' => $hidethirdpartylogo,
3008  ];
3009  $classfortooltip = 'classfortooltip';
3010  $dataparams = '';
3011  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3012  $classfortooltip = 'classforajaxtooltip';
3013  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3014  $label = '';
3015  } else {
3016  $label = implode($this->getTooltipContentArray($params));
3017  }
3018 
3019  $companylink = '';
3020  if (!empty($this->socid)) { // Add thirdparty for external users
3021  $thirdpartystatic = new Societe($this->db);
3022  $thirdpartystatic->fetch($this->socid);
3023  if (empty($hidethirdpartylogo)) {
3024  $companylink = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
3025  }
3026  }
3027 
3028  if ($infologin < 0) {
3029  $label = '';
3030  }
3031 
3032  $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id;
3033  if ($option == 'leave') {
3034  $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id;
3035  }
3036 
3037  if ($option != 'nolink') {
3038  // Add param to save lastsearch_values or not
3039  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3040  if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3041  $add_save_lastsearch_values = 1;
3042  }
3043  if ($add_save_lastsearch_values) {
3044  $url .= '&save_lastsearch_values=1';
3045  }
3046  }
3047 
3048  $linkstart = '<a href="'.$url.'"';
3049  $linkclose = "";
3050  if (empty($notooltip)) {
3051  if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3052  $langs->load("users");
3053  $label = $langs->trans("ShowUser");
3054  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
3055  }
3056  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3057  $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
3058  } else {
3059  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
3060  }
3061 
3062  $linkstart .= $linkclose.'>';
3063  $linkend = '</a>';
3064 
3065  //if ($withpictoimg == -1) $result.='<div class="nowrap">';
3066  $result .= (($option == 'nolink') ? '' : $linkstart);
3067  if ($withpictoimg) {
3068  $paddafterimage = '';
3069  if (abs((int) $withpictoimg) == 1) {
3070  $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3071  }
3072  // Only picto
3073  if ($withpictoimg > 0) {
3074  $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'"><div class="valignmiddle userphoto inline-block center marginrightonlyshort"'.($paddafterimage ? ' '.$paddafterimage : '').'>'.img_object('', 'user', 'class=""', 0, 0, $notooltip ? 0 : 1).'</div></span>';
3075  } else {
3076  // Picto must be a photo
3077  $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>';
3078  }
3079  $result .= $picto;
3080  }
3081  if ($withpictoimg > -2 && $withpictoimg != 2) {
3082  if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3083  $result .= '<span class="nopadding usertext'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
3084  }
3085  if ($mode == 'login') {
3086  $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
3087  } else {
3088  $result .= dol_string_nohtmltag($this->getFullName($langs, '', ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
3089  }
3090  if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3091  $result .= '</span>';
3092  }
3093  }
3094  $result .= (($option == 'nolink') ? '' : $linkend);
3095  //if ($withpictoimg == -1) $result.='</div>';
3096 
3097  $result .= $companylink;
3098 
3099  global $action;
3100  $hookmanager->initHooks(array('userdao'));
3101  $parameters = array('id' => $this->id, 'getnomurl' => &$result);
3102  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3103  if ($reshook > 0) {
3104  $result = $hookmanager->resPrint;
3105  } else {
3106  $result .= $hookmanager->resPrint;
3107  }
3108 
3109  return $result;
3110  }
3111 
3121  public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
3122  {
3123  global $langs, $user;
3124 
3125  $result = '';
3126 
3127  $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3128  $linkend = '</a>';
3129 
3130  //Check user's rights to see an other user
3131  if ((!$user->hasRight('user', 'user', 'lire') && $this->id != $user->id)) {
3132  $option = 'nolink';
3133  }
3134 
3135  if ($option == 'xxx') {
3136  $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3137  $linkend = '</a>';
3138  }
3139 
3140  if ($option == 'nolink') {
3141  $linkstart = '';
3142  $linkend = '';
3143  }
3144 
3145  $result .= $linkstart;
3146  if ($withpictoimg) {
3147  $paddafterimage = '';
3148  if (abs($withpictoimg) == 1) {
3149  $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3150  }
3151  // Only picto
3152  if ($withpictoimg > 0) {
3153  $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3154  } else {
3155  // Picto must be a photo
3156  $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>';
3157  }
3158  $result .= $picto;
3159  }
3160  $result .= $this->login;
3161  $result .= $linkend;
3162 
3163  return $result;
3164  }
3165 
3172  public function getLibStatut($mode = 0)
3173  {
3174  return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3175  }
3176 
3177  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3185  public function LibStatut($status, $mode = 0)
3186  {
3187  // phpcs:enable
3188  global $langs;
3189 
3190  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3191  global $langs;
3192  //$langs->load("mymodule");
3193  $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3194  $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3195  $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3196  $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3197  }
3198 
3199  $statusType = 'status5';
3200  if ($status == self::STATUS_ENABLED) {
3201  $statusType = 'status4';
3202  }
3203 
3204  $label = $this->labelStatus[$status];
3205  $labelshort = $this->labelStatusShort[$status];
3206 
3207  $now = dol_now();
3208  if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3209  $statusType = 'status3';
3210  $label .= ' ('.$langs->trans("UserNotYetValid").')';
3211  }
3212  if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3213  $statusType = 'status2';
3214  $label .= ' ('.$langs->trans("UserExpired").')';
3215  }
3216 
3217  return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3218  }
3219 
3220 
3228  public function getKanbanView($option = '', $arraydata = null)
3229  {
3230  global $langs;
3231 
3232  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3233 
3234  $return = '<div class="box-flex-item box-flex-grow-zero">';
3235  $return .= '<div class="info-box info-box-sm">';
3236  $return .= '<span class="info-box-icon bg-infobox-action">';
3237 
3238  $label = '';
3239  if (!empty($this->photo)) {
3240  //$label .= '<div class="photointooltip floatright">';
3241  $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
3242  //$label .= '</div>';
3243  //$label .= '<div style="clear: both;"></div>';
3244  $return .= $label;
3245  } else {
3246  $return .= img_picto('', $this->picto);
3247  }
3248 
3249  //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3250  $return .= '</span>';
3251  $return .= '<div class="info-box-content">';
3252  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3253  if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3254  $return .= img_picto($langs->trans("SuperAdministratorDesc"), 'redstar', 'class="valignmiddle paddingright paddingleft"');
3255  } elseif ($this->admin) {
3256  $return .= img_picto($langs->trans("AdministratorDesc"), 'star', 'class="valignmiddle paddingright paddingleft"');
3257  }
3258  $return .= '</span>';
3259  if ($selected >= 0) {
3260  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3261  }
3262  if (property_exists($this, 'label')) {
3263  $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3264  }
3265  if ($this->email) {
3266  $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3267  }
3268  if (method_exists($this, 'getLibStatut')) {
3269  $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3270  }
3271  $return .= '</div>';
3272  $return .= '</div>';
3273  $return .= '</div>';
3274 
3275  return $return;
3276  }
3277 
3278 
3279  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3280  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3290  public function _load_ldap_dn($info, $mode = 0)
3291  {
3292  // phpcs:enable
3293  global $conf;
3294  $dn = '';
3295  if ($mode == 0) {
3296  $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')]."," . getDolGlobalString('LDAP_USER_DN');
3297  } elseif ($mode == 1) {
3298  $dn = getDolGlobalString('LDAP_USER_DN');
3299  } elseif ($mode == 2) {
3300  $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')];
3301  }
3302  return $dn;
3303  }
3304 
3305  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3306  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3312  public function _load_ldap_info()
3313  {
3314  // phpcs:enable
3315  global $conf, $langs;
3316 
3317  $info = array();
3318 
3319  $socialnetworks = getArrayOfSocialNetworks();
3320 
3321  $keymodified = false;
3322 
3323  // Object classes
3324  $info["objectclass"] = explode(',', getDolGlobalString('LDAP_USER_OBJECT_CLASS'));
3325 
3326  $this->fullname = $this->getFullName($langs);
3327 
3328  // Possible LDAP KEY (constname => varname)
3329  $ldapkey = array(
3330  'LDAP_FIELD_FULLNAME' => 'fullname',
3331  'LDAP_FIELD_NAME' => 'lastname',
3332  'LDAP_FIELD_FIRSTNAME' => 'firstname',
3333  'LDAP_FIELD_LOGIN' => 'login',
3334  'LDAP_FIELD_LOGIN_SAMBA' => 'login',
3335  'LDAP_FIELD_PHONE' => 'office_phone',
3336  'LDAP_FIELD_MOBILE' => 'user_mobile',
3337  'LDAP_FIELD_FAX' => 'office_fax',
3338  'LDAP_FIELD_MAIL' => 'email',
3339  'LDAP_FIELD_SID' => 'ldap_sid',
3340  );
3341 
3342  // Champs
3343  foreach ($ldapkey as $constname => $varname) {
3344  if (!empty($this->$varname) && getDolGlobalString($constname)) {
3345  $info[getDolGlobalString($constname)] = $this->$varname;
3346 
3347  // Check if it is the LDAP key and if its value has been changed
3348  if (getDolGlobalString('LDAP_KEY_USERS') && $conf->global->LDAP_KEY_USERS == getDolGlobalString($constname)) {
3349  if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
3350  $keymodified = true; // For check if LDAP key has been modified
3351  }
3352  }
3353  }
3354  }
3355  foreach ($socialnetworks as $key => $value) {
3356  if (!empty($this->socialnetworks[$value['label']]) && getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))) {
3357  $info[getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3358  }
3359  }
3360  if ($this->address && getDolGlobalString('LDAP_FIELD_ADDRESS')) {
3361  $info[getDolGlobalString('LDAP_FIELD_ADDRESS')] = $this->address;
3362  }
3363  if ($this->zip && getDolGlobalString('LDAP_FIELD_ZIP')) {
3364  $info[getDolGlobalString('LDAP_FIELD_ZIP')] = $this->zip;
3365  }
3366  if ($this->town && getDolGlobalString('LDAP_FIELD_TOWN')) {
3367  $info[getDolGlobalString('LDAP_FIELD_TOWN')] = $this->town;
3368  }
3369  if ($this->note_public && getDolGlobalString('LDAP_FIELD_DESCRIPTION')) {
3370  $info[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_public, 2);
3371  }
3372  if ($this->socid > 0) {
3373  $soc = new Societe($this->db);
3374  $soc->fetch($this->socid);
3375 
3376  $info[getDolGlobalString('LDAP_FIELD_COMPANY')] = $soc->name;
3377  if ($soc->client == 1) {
3378  $info["businessCategory"] = "Customers";
3379  }
3380  if ($soc->client == 2) {
3381  $info["businessCategory"] = "Prospects";
3382  }
3383  if ($soc->fournisseur == 1) {
3384  $info["businessCategory"] = "Suppliers";
3385  }
3386  }
3387 
3388  // When password is modified
3389  if (!empty($this->pass)) {
3390  if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3391  $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass; // this->pass = unencrypted password
3392  }
3393  if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3394  $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3395  }
3396  } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3397  // Set LDAP password if possible
3398  // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3399  if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
3400  // Just for the default MD5 !
3401  if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) {
3402  if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3403  $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3404  }
3405  }
3406  } elseif (!empty($this->pass_indatabase)) {
3407  // Use $this->pass_indatabase value if exists
3408  if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3409  $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = unencrypted password
3410  }
3411  if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3412  $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3413  }
3414  }
3415  }
3416 
3417  if (getDolGlobalString('LDAP_SERVER_TYPE') == 'egroupware') {
3418  $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3419 
3420  $info['uidnumber'] = $this->id;
3421 
3422  $info['phpgwTz'] = 0;
3423  $info['phpgwMailType'] = 'INTERNET';
3424  $info['phpgwMailHomeType'] = 'INTERNET';
3425 
3426  $info["phpgwContactTypeId"] = 'n';
3427  $info["phpgwContactCatId"] = 0;
3428  $info["phpgwContactAccess"] = "public";
3429 
3430  /*
3431  if (dol_strlen($this->egroupware_id) == 0) {
3432  $this->egroupware_id = 1;
3433  }
3434  $info["phpgwContactOwner"] = $this->egroupware_id;
3435  */
3436  $info["phpgwContactOwner"] = 1;
3437 
3438  if ($this->email) {
3439  $info["rfc822Mailbox"] = $this->email;
3440  }
3441  if ($this->user_mobile) {
3442  $info["phpgwCellTelephoneNumber"] = $this->user_mobile;
3443  }
3444  }
3445 
3446  if (getDolGlobalString('LDAP_FIELD_USERID')) {
3447  $info[getDolGlobalString('LDAP_FIELD_USERID')] = $this->id;
3448  }
3449  if (getDolGlobalString('LDAP_FIELD_GROUPID')) {
3450  $usergroup = new UserGroup($this->db);
3451  $groupslist = $usergroup->listGroupsForUser($this->id);
3452  $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = '65534';
3453  if (!empty($groupslist)) {
3454  foreach ($groupslist as $groupforuser) {
3455  $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = $groupforuser->id; //Select first group in list
3456  break;
3457  }
3458  }
3459  }
3460  if (getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY') && getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')) {
3461  $info[getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY')] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->login";
3462  }
3463 
3464  return $info;
3465  }
3466 
3467 
3475  public function initAsSpecimen()
3476  {
3477  global $user, $langs;
3478 
3479  $now = dol_now();
3480 
3481  // Initialise parameters
3482  $this->id = 0;
3483  $this->ref = 'SPECIMEN';
3484  $this->specimen = 1;
3485 
3486  $this->lastname = 'DOLIBARR';
3487  $this->firstname = 'SPECIMEN';
3488  $this->gender = 'man';
3489  $this->note_public = 'This is a note public';
3490  $this->note_private = 'This is a note private';
3491  $this->email = 'email@specimen.com';
3492  $this->personal_email = 'personalemail@specimen.com';
3493  $this->socialnetworks = array(
3494  'skype' => 'skypepseudo',
3495  'twitter' => 'twitterpseudo',
3496  'facebook' => 'facebookpseudo',
3497  'linkedin' => 'linkedinpseudo',
3498  );
3499  $this->office_phone = '0999999999';
3500  $this->office_fax = '0999999998';
3501  $this->user_mobile = '0999999997';
3502  $this->personal_mobile = '0999999996';
3503  $this->admin = 0;
3504  $this->login = 'dolibspec';
3505  $this->pass = 'dolibSpec+@123';
3506  //$this->pass_indatabase='dolibspec'; Set after a fetch
3507  //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3508  $this->datec = $now;
3509  $this->datem = $now;
3510 
3511  $this->datelastlogin = $now;
3512  $this->iplastlogin = '127.0.0.1';
3513  $this->datepreviouslogin = $now;
3514  $this->ippreviouslogin = '127.0.0.1';
3515  $this->statut = 1; // deprecated
3516  $this->status = 1;
3517 
3518  $this->entity = 1;
3519 
3520  return 1;
3521  }
3522 
3529  public function info($id)
3530  {
3531  $sql = "SELECT u.rowid, u.login as ref, u.datec,";
3532  $sql .= " u.tms as date_modification, u.entity";
3533  $sql .= " FROM ".$this->db->prefix()."user as u";
3534  $sql .= " WHERE u.rowid = ".((int) $id);
3535 
3536  $result = $this->db->query($sql);
3537  if ($result) {
3538  if ($this->db->num_rows($result)) {
3539  $obj = $this->db->fetch_object($result);
3540 
3541  $this->id = $obj->rowid;
3542 
3543  $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3544  $this->date_creation = $this->db->jdate($obj->datec);
3545  $this->date_modification = $this->db->jdate($obj->date_modification);
3546  $this->entity = $obj->entity;
3547  }
3548 
3549  $this->db->free($result);
3550  } else {
3551  dol_print_error($this->db);
3552  }
3553  }
3554 
3555 
3561  public function getNbOfEMailings()
3562  {
3563  $sql = "SELECT count(mc.email) as nb";
3564  $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3565  $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3566  $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
3567 
3568  $resql = $this->db->query($sql);
3569  if ($resql) {
3570  $obj = $this->db->fetch_object($resql);
3571  $nb = $obj->nb;
3572 
3573  $this->db->free($resql);
3574  return $nb;
3575  } else {
3576  $this->error = $this->db->error();
3577  return -1;
3578  }
3579  }
3580 
3589  public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3590  {
3591  global $conf;
3592 
3593  $sql = "SELECT count(rowid) as nb";
3594  $sql .= " FROM ".$this->db->prefix()."user";
3595  if ($option == 'superadmin') {
3596  $sql .= " WHERE entity = 0";
3597  } else {
3598  $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3599  if ($limitTo == 'active') {
3600  $sql .= " AND statut = 1";
3601  }
3602  }
3603  if ($admin >= 0) {
3604  $sql .= " AND admin = ".(int) $admin;
3605  }
3606 
3607  $resql = $this->db->query($sql);
3608  if ($resql) {
3609  $obj = $this->db->fetch_object($resql);
3610  $nb = (int) $obj->nb;
3611 
3612  $this->db->free($resql);
3613  return $nb;
3614  } else {
3615  $this->error = $this->db->lasterror();
3616  return -1;
3617  }
3618  }
3619 
3620  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3627  public function update_ldap2dolibarr(&$ldapuser)
3628  {
3629  // phpcs:enable
3630  // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3631  global $user, $conf;
3632 
3633  $socialnetworks = getArrayOfSocialNetworks();
3634 
3635  $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3636  $this->firstname = $ldapuser->$tmpvar;
3637  $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3638  $this->lastname = $ldapuser->$tmpvar;
3639  $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3640  $this->login = $ldapuser->$tmpvar;
3641  $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3642  $this->pass = $ldapuser->$tmpvar;
3643  $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3644  $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3645 
3646  $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3647  $this->office_phone = $ldapuser->$tmpvar;
3648  $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3649  $this->user_mobile = $ldapuser->$tmpvar;
3650  $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3651  $this->office_fax = $ldapuser->$tmpvar;
3652  $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3653  $this->email = $ldapuser->$tmpvar;
3654  foreach ($socialnetworks as $key => $value) {
3655  $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3656  $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3657  }
3658  $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3659  $this->ldap_sid = $ldapuser->$tmpvar;
3660 
3661  $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3662  $this->job = $ldapuser->$tmpvar;
3663  $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3664  $this->note_public = $ldapuser->$tmpvar;
3665 
3666  $result = $this->update($user);
3667 
3668  dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3669 
3670  return $result;
3671  }
3672 
3673 
3674  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3681  public function get_children()
3682  {
3683  // phpcs:enable
3684  $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3685  $sql .= " WHERE fk_user = ".((int) $this->id);
3686 
3687  dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3688  $res = $this->db->query($sql);
3689  if ($res) {
3690  $users = array();
3691  while ($rec = $this->db->fetch_array($res)) {
3692  $user = new User($this->db);
3693  $user->fetch($rec['rowid']);
3694  $users[] = $user;
3695  }
3696  return $users;
3697  } else {
3698  dol_print_error($this->db);
3699  return -1;
3700  }
3701  }
3702 
3703 
3709  private function loadParentOf()
3710  {
3711  global $conf;
3712 
3713  $this->parentof = array();
3714 
3715  // Load array[child]=parent
3716  $sql = "SELECT fk_user as id_parent, rowid as id_son";
3717  $sql .= " FROM ".$this->db->prefix()."user";
3718  $sql .= " WHERE fk_user <> 0";
3719  $sql .= " AND entity IN (".getEntity('user').")";
3720 
3721  dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3722  $resql = $this->db->query($sql);
3723  if ($resql) {
3724  while ($obj = $this->db->fetch_object($resql)) {
3725  $this->parentof[$obj->id_son] = $obj->id_parent;
3726  }
3727  return 1;
3728  } else {
3729  dol_print_error($this->db);
3730  return -1;
3731  }
3732  }
3733 
3734  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3748  public function get_full_tree($deleteafterid = 0, $filter = '')
3749  {
3750  // phpcs:enable
3751  global $conf, $user;
3752  global $hookmanager;
3753 
3754  // Actions hooked (by external module)
3755  $hookmanager->initHooks(array('userdao'));
3756 
3757  $this->users = array();
3758 
3759  // Init this->parentof that is array(id_son=>id_parent, ...)
3760  $this->loadParentOf();
3761 
3762  // Init $this->users array
3763  $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
3764  $sql .= " FROM ".$this->db->prefix()."user as u";
3765  // Add fields from hooks
3766  $parameters = array();
3767  $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3768  if ($reshook > 0) {
3769  $sql .= $hookmanager->resPrint;
3770  } else {
3771  $sql .= " WHERE u.entity IN (".getEntity('user').")";
3772  }
3773  if ($filter) {
3774  $sql .= " AND ".$filter;
3775  }
3776 
3777  dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3778  $resql = $this->db->query($sql);
3779  if ($resql) {
3780  $i = 0;
3781  while ($obj = $this->db->fetch_object($resql)) {
3782  $this->users[$obj->rowid]['rowid'] = $obj->rowid;
3783  $this->users[$obj->rowid]['id'] = $obj->rowid;
3784  $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
3785  $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
3786  $this->users[$obj->rowid]['firstname'] = $obj->firstname;
3787  $this->users[$obj->rowid]['lastname'] = $obj->lastname;
3788  $this->users[$obj->rowid]['login'] = $obj->login;
3789  $this->users[$obj->rowid]['statut'] = $obj->statut;
3790  $this->users[$obj->rowid]['entity'] = $obj->entity;
3791  $this->users[$obj->rowid]['email'] = $obj->email;
3792  $this->users[$obj->rowid]['gender'] = $obj->gender;
3793  $this->users[$obj->rowid]['admin'] = $obj->admin;
3794  $this->users[$obj->rowid]['photo'] = $obj->photo;
3795  // fields are filled with build_path_from_id_user
3796  $this->users[$obj->rowid]['fullpath'] = '';
3797  $this->users[$obj->rowid]['fullname'] = '';
3798  $this->users[$obj->rowid]['level'] = 0;
3799  $i++;
3800  }
3801  } else {
3802  dol_print_error($this->db);
3803  return -1;
3804  }
3805 
3806  // We add the fullpath property to each element of the first level (no parent exists)
3807  dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3808  foreach ($this->users as $key => $val) {
3809  $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3810  if ($result < 0) {
3811  $this->error = 'ErrorLoopInHierarchy';
3812  return -1;
3813  }
3814  }
3815 
3816  // Exclude leaf including $deleteafterid from tree
3817  if ($deleteafterid) {
3818  //print "Look to discard user ".$deleteafterid."\n";
3819  $keyfilter1 = '^'.$deleteafterid.'$';
3820  $keyfilter2 = '_'.$deleteafterid.'$';
3821  $keyfilter3 = '^'.$deleteafterid.'_';
3822  $keyfilter4 = '_'.$deleteafterid.'_';
3823  foreach (array_keys($this->users) as $key) {
3824  $fullpath = (string) $this->users[$key]['fullpath'];
3825  if (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
3826  || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath)) {
3827  unset($this->users[$key]);
3828  }
3829  }
3830  }
3831 
3832  dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
3833  $this->users = dol_sort_array($this->users, 'fullname', 'asc', true, false, 1);
3834 
3835  //var_dump($this->users);
3836 
3837  return $this->users;
3838  }
3839 
3848  public function getAllChildIds($addcurrentuser = 0)
3849  {
3850  $childids = array();
3851 
3852  if (isset($this->cache_childids[$this->id])) {
3853  $childids = $this->cache_childids[$this->id];
3854  } else {
3855  // Init this->users
3856  $this->get_full_tree();
3857 
3858  $idtoscan = $this->id;
3859 
3860  dol_syslog("Build childid for id = ".$idtoscan);
3861  foreach ($this->users as $id => $val) {
3862  //var_dump($val['fullpath']);
3863  if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
3864  $childids[$val['id']] = $val['id'];
3865  }
3866  }
3867  }
3868  $this->cache_childids[$this->id] = $childids;
3869 
3870  if ($addcurrentuser) {
3871  $childids[$this->id] = $this->id;
3872  }
3873 
3874  return $childids;
3875  }
3876 
3877  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3886  public function build_path_from_id_user($id_user, $protection = 0)
3887  {
3888  // phpcs:enable
3889  //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
3890 
3891  if (!empty($this->users[$id_user]['fullpath'])) {
3892  // Already defined
3893  dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
3894  return 0;
3895  }
3896 
3897  // Define fullpath and fullname
3898  $this->users[$id_user]['fullpath'] = '_'.$id_user;
3899  $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
3900  $i = 0;
3901  $cursor_user = $id_user;
3902 
3903  $useridfound = array($id_user);
3904  while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) {
3905  if (in_array($this->parentof[$cursor_user], $useridfound)) {
3906  dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
3907  return -1; // Should not happen. Protection against looping hierarchy
3908  }
3909  $useridfound[] = $this->parentof[$cursor_user];
3910  $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
3911  $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
3912  $i++;
3913  $cursor_user = $this->parentof[$cursor_user];
3914  }
3915 
3916  // We count number of _ to have level
3917  $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
3918 
3919  return 1;
3920  }
3921 
3930  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3931  {
3932  $tables = array(
3933  'user',
3934  );
3935 
3936  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3937  }
3938 
3939 
3945  public function loadStateBoard()
3946  {
3947  global $conf;
3948 
3949  $this->nb = array();
3950 
3951  $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
3952  $sql .= " FROM ".$this->db->prefix()."user as u";
3953  if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
3954  $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
3955  $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
3956  $sql .= " AND ug.fk_user = u.rowid";
3957  } else {
3958  $sql .= " WHERE u.entity IN (".getEntity('user').")";
3959  }
3960  $sql .= " AND u.statut > 0";
3961  //$sql.= " AND employee != 0";
3962 
3963  $resql = $this->db->query($sql);
3964  if ($resql) {
3965  while ($obj = $this->db->fetch_object($resql)) {
3966  $this->nb["users"] = $obj->nb;
3967  }
3968  $this->db->free($resql);
3969  return 1;
3970  } else {
3971  dol_print_error($this->db);
3972  $this->error = $this->db->error();
3973  return -1;
3974  }
3975  }
3976 
3988  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3989  {
3990  global $conf, $user, $langs;
3991 
3992  $langs->load("user");
3993 
3994  // Set the '$modele' to the name of the document template (model) to use
3995  if (!dol_strlen($modele)) {
3996  if (getDolGlobalString('USER_ADDON_PDF')) {
3997  $modele = getDolGlobalString('USER_ADDON_PDF');
3998  } else {
3999  $modele = 'bluesky';
4000  }
4001  }
4002 
4003  $modelpath = "core/modules/user/doc/";
4004 
4005  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4006  }
4007 
4008  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4016  public function user_get_property($rowid, $mode)
4017  {
4018  // phpcs:enable
4019  $user_property = '';
4020 
4021  if (empty($rowid)) {
4022  return '';
4023  }
4024 
4025  $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
4026  $sql .= " FROM ".$this->db->prefix()."user";
4027  $sql .= " WHERE rowid = ".((int) $rowid);
4028 
4029  $resql = $this->db->query($sql);
4030  if ($resql) {
4031  $nump = $this->db->num_rows($resql);
4032 
4033  if ($nump) {
4034  $obj = $this->db->fetch_object($resql);
4035 
4036  if ($mode == 'email') {
4037  $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
4038  } elseif ($mode == 'mobile') {
4039  $user_property = $obj->user_mobile;
4040  } elseif ($mode == 'name') {
4041  $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname);
4042  }
4043  }
4044  return $user_property;
4045  } else {
4046  dol_print_error($this->db);
4047  }
4048 
4049  return '';
4050  }
4051 
4059  public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
4060  {
4061  global $dolibarr_main_url_root;
4062  global $conf;
4063 
4064  $encodedsecurekey = dol_hash($conf->file->instance_unique_id.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
4065  if (isModEnabled('multicompany')) {
4066  $entity_qr = '&entity='.((int) $conf->entity);
4067  } else {
4068  $entity_qr = '';
4069  }
4070  // Define $urlwithroot
4071  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
4072  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
4073  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
4074 
4075  if ($typeofurl == 'internal') {
4076  $urlwithroot = DOL_URL_ROOT;
4077  }
4078 
4079  return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
4080  }
4081 
4095  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND', $entityfilter = false)
4096  {
4097  global $conf, $user;
4098 
4099  $sql = "SELECT t.rowid";
4100  $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
4101 
4102  if ($entityfilter) {
4103  if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4104  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
4105  $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
4106  } else {
4107  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
4108  $sql .= " WHERE ((ug.fk_user = t.rowid";
4109  $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
4110  $sql .= " OR t.entity = 0)"; // Show always superadmin
4111  }
4112  } else {
4113  $sql .= " WHERE t.entity IN (".getEntity('user').")";
4114  }
4115  } else {
4116  $sql .= " WHERE 1 = 1";
4117  }
4118 
4119  // Manage filter
4120  $errormessage = '';
4121  $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
4122  if ($errormessage) {
4123  $this->errors[] = $errormessage;
4124  dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
4125  return -1;
4126  }
4127 
4128  $sql .= $this->db->order($sortfield, $sortorder);
4129  if ($limit) {
4130  $sql .= $this->db->plimit($limit + 1, $offset);
4131  }
4132 
4133  dol_syslog(__METHOD__, LOG_DEBUG);
4134 
4135  $resql = $this->db->query($sql);
4136  if ($resql) {
4137  $this->users = array();
4138  $num = $this->db->num_rows($resql);
4139  if ($num) {
4140  while ($obj = $this->db->fetch_object($resql)) {
4141  $line = new self($this->db);
4142  $result = $line->fetch($obj->rowid);
4143  if ($result > 0 && !empty($line->id)) {
4144  $this->users[$obj->rowid] = clone $line;
4145  }
4146  }
4147  $this->db->free($resql);
4148  }
4149  return $num;
4150  } else {
4151  $this->errors[] = $this->db->lasterror();
4152  return -1;
4153  }
4154  }
4155 
4163  private $findUserIdByEmailCache;
4164 
4175  public function findUserIdByEmail($email)
4176  {
4177  if (isset($this->findUserIdByEmailCache[$email])) {
4178  return $this->findUserIdByEmailCache[$email];
4179  }
4180 
4181  $this->findUserIdByEmailCache[$email] = -1;
4182 
4183  $sql = 'SELECT rowid';
4184  $sql .= ' FROM '.$this->db->prefix().'user';
4185  if (getDolGlobalString('AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR')) {
4186  $sql .= " WHERE email LIKE '%".$this->db->escape($this->db->escapeforlike($email))."%'";
4187  } else {
4188  $sql .= " WHERE email = '".$this->db->escape($email)."'";
4189  }
4190  $sql .= ' LIMIT 1';
4191 
4192  $resql = $this->db->query($sql);
4193  if (!$resql) {
4194  return -1;
4195  }
4196 
4197  $obj = $this->db->fetch_object($resql);
4198  if (!$obj) {
4199  return -1;
4200  }
4201 
4202  $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4203 
4204  return $this->findUserIdByEmailCache[$email];
4205  }
4206 }
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition: security.php:607
$object ref
Definition: info.php:79
Class to manage members of a foundation.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage contact/addresses.
Class for MyObject.
Class to manage Dolibarr database access.
Class to manage warehouses.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
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:50
fetch($id=0, $login='', $sid='', $loadpersonalconf=0, $entity=-1, $email='', $fk_socpeople=0, $use_email_oauth2=0)
Load a user from database with its id or ref (login).
Definition: user.class.php:450
SetInGroup($group, $entity, $notrigger=0)
Add user into a group.
LibStatut($status, $mode=0)
Return the label of a status of user (active, inactive)
loadRights($moduletag='', $forcereload=0)
Load permissions granted to a user->id into object user->rights.
get_children()
Return and array with all instantiated 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.
loadStateBoard()
Load metrics this->nb for dashboard.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
Definition: user.class.php:772
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.
update_last_login_date()
Update the user's last login date in the database.
__construct($db)
Constructor of the class.
Definition: user.class.php:409
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.
set_default_rights()
Assign rights by default.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND', $entityfilter=false)
Load all objects into $this->users.
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 (optionally 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 children 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 user ids in hierarchy (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 optionally the picto) Use this->id,this->lastname,...
clearrights()
Clear all permissions array of user.
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.
loadPersonalConf()
Load const values from database table user_param and set it into user->conf->XXX.
Definition: user.class.php:684
_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:253
loadDefaultValues()
Load default values from database table into property ->default_values.
Definition: user.class.php:720
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 a user->id into object user->rights TODO Remove this method.
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 (optionally with 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:927
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.
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
Support class for thirdparties, contacts, members, users or resources.
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('invoice') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&!getDolGlobalString('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') && $user->hasRight('tax', 'charges', 'lire')) if(isModEnabled('invoice') &&isModEnabled('order') && $user->hasRight("commande", "lire") &&!getDolGlobalString('WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER')) $sql
Social contributions to pay.
Definition: index.php:745
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:655
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:641
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
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_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
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 a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
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:419
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 symmetric 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 symmetric encryption.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.