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