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