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