dolibarr 21.0.0-alpha
user.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (c) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
4 * Copyright (c) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
7 * Copyright (C) 2005-2024 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2005 Lionel Cousteix <etm_ltd@tiscali.co.uk>
9 * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
10 * Copyright (C) 2013-2019 Philippe Grand <philippe.grand@atoo-net.com>
11 * Copyright (C) 2013-2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
12 * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
13 * Copyright (C) 2018 charlene Benke <charlie@patas-monkey.com>
14 * Copyright (C) 2018-2021 Nicolas ZABOURI <info@inovea-conseil.com>
15 * Copyright (C) 2019-2024 Frédéric France <frederic.france@free.fr>
16 * Copyright (C) 2019 Abbes Bahfir <dolipar@dolipar.org>
17 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
18 * Copyright (C) 2024 Lenin Rivas <lenin.rivas777@gmail.com>
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 3 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <https://www.gnu.org/licenses/>.
32 */
33
40require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
41require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
42require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
43require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
44
45
49class User extends CommonObject
50{
51 use CommonPeople;
52
56 public $element = 'user';
57
61 public $table_element = 'user';
62
66 public $fk_element = 'fk_user';
67
71 public $picto = 'user';
72
76 public $id = 0;
77
81 public $oldcopy;
82
88 public $statut;
89
93 public $status;
94
98 public $openid;
99
103 public $ldap_sid;
107 public $search_sid;
111 public $employee;
115 public $civility_code;
116
120 public $fullname;
121
125 public $gender;
126
130 public $birth;
131
135 public $email;
136
140 public $email_oauth2;
141
145 public $personal_email;
146
150 public $socialnetworks;
151
155 public $job;
156
160 public $signature;
161
165 public $office_phone;
166
170 public $office_fax;
171
175 public $user_mobile;
176
180 public $personal_mobile;
181
185 public $admin;
186
190 public $login;
191
195 public $api_key;
196
200 public $entity;
201
205 public $pass;
206
210 public $pass_crypted;
211
215 public $pass_indatabase;
216
220 public $pass_indatabase_crypted;
221
225 public $pass_temp;
226
232 public $datec;
233
239 public $datem;
240
244 public $socid;
245
249 public $contact_id;
250
254 public $fk_member;
255
259 public $fk_user;
260
264 public $fk_user_expense_validator;
265
269 public $fk_user_holiday_validator;
270
274 public $clicktodial_url;
275
279 public $clicktodial_login;
280
284 public $clicktodial_password;
285
289 public $clicktodial_poste;
290
294 public $clicktodial_loaded;
295
296
300 public $datelastlogin;
304 public $datepreviouslogin;
308 public $flagdelsessionsbefore;
312 public $iplastlogin;
316 public $ippreviouslogin;
320 public $datestartvalidity;
324 public $dateendvalidity;
325
329 public $photo;
330
334 public $lang;
335
339 public $rights;
340
344 public $all_permissions_are_loaded;
345
349 public $nb_rights;
350
354 public $user_group_list;
355
359 private $_tab_loaded = array();
360
364 public $conf;
365
369 public $default_values; // To store default values for user. Loaded by loadDefaultValues().
370
374 public $lastsearch_values_tmp; // To store current search criteria for user
378 public $lastsearch_values; // To store last saved search criteria for user
379
383 public $users = array();
387 public $parentof; // To store an array of all parents for all ids.
391 private $cache_childids; // Cache array of already loaded children
392
396 public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
397
401 public $thm; // Average cost of employee - Used for valuation of time spent
405 public $tjm; // Average cost of employee
406
410 public $salary; // Monthly salary - Denormalized value from llx_user_employment
414 public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment
418 public $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment
419
423 public $color;
424
428 public $dateemployment; // Define date of employment by company
432 public $dateemploymentend; // Define date of employment end by company
433
437 public $default_c_exp_tax_cat;
438
442 public $ref_employee;
443
447 public $national_registration_number;
448
452 public $default_range;
453
457 public $fk_warehouse;
458
462 public $fk_establishment;
463
467 public $label_establishment;
468
472 //private $egroupware_id;
473
478 public $usergroup_entity;
479
480 public $fields = array(
481 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
482 'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 20, 'searchall' => 1),
483 'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1),
484 'ref_employee' => array('type' => 'varchar(50)', 'label' => 'RefEmployee', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 30, 'searchall' => 1),
485 'national_registration_number' => array('type' => 'varchar(50)', 'label' => 'NationalRegistrationNumber', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 40, 'searchall' => 1)
486 );
487
488 const STATUS_DISABLED = 0;
489 const STATUS_ENABLED = 1;
490
496 public function __construct($db)
497 {
498 $this->db = $db;
499
500 $this->ismultientitymanaged = 1;
501 $this->isextrafieldmanaged = 1;
502 // User preference
503 $this->clicktodial_loaded = 0;
504
505 // For cache usage
506 $this->all_permissions_are_loaded = 0;
507 $this->nb_rights = 0;
508
509 // Force some default values
510 $this->admin = 0;
511 $this->employee = 1;
512
513 $this->conf = new stdClass();
514 $this->rights = new stdClass();
515 $this->rights->user = new stdClass();
516 $this->rights->user->user = new stdClass();
517 $this->rights->user->self = new stdClass();
518 $this->rights->user->user_advance = new stdClass();
519 $this->rights->user->self_advance = new stdClass();
520 $this->rights->user->group_advance = new stdClass();
521 }
522
537 public function fetch($id = 0, $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1, $email = '', $fk_socpeople = 0, $use_email_oauth2 = 0)
538 {
539 global $conf, $user;
540
541 // Clean parameters
542 $login = trim($login);
543
544 // Get user
545 $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.civility as civility_code, u.birth, u.job,";
546 $sql .= " u.email, u.email_oauth2, u.personal_email,";
547 $sql .= " u.socialnetworks,";
548 $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile, u.personal_mobile,";
549 $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
550 $sql .= " u.admin, u.login, u.note_private, u.note_public,";
551 $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.api_key,";
552 $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,";
553 $sql .= " u.statut as status, u.lang, u.entity,";
554 $sql .= " u.datec as datec,";
555 $sql .= " u.tms as datem,";
556 $sql .= " u.datelastlogin as datel,";
557 $sql .= " u.datepreviouslogin as datep,";
558 $sql .= " u.flagdelsessionsbefore,";
559 $sql .= " u.iplastlogin,";
560 $sql .= " u.ippreviouslogin,";
561 $sql .= " u.datelastpassvalidation,";
562 $sql .= " u.datestartvalidity,";
563 $sql .= " u.dateendvalidity,";
564 $sql .= " u.photo as photo,";
565 $sql .= " u.openid as openid,";
566 $sql .= " u.accountancy_code,";
567 $sql .= " u.thm,";
568 $sql .= " u.tjm,";
569 $sql .= " u.salary,";
570 $sql .= " u.salaryextra,";
571 $sql .= " u.weeklyhours,";
572 $sql .= " u.color,";
573 $sql .= " u.dateemployment, u.dateemploymentend,";
574 $sql .= " u.fk_warehouse,";
575 $sql .= " u.ref_ext,";
576 $sql .= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode
577 $sql .= " u.national_registration_number,";
578 $sql .= " u.ref_employee,";
579 $sql .= " c.code as country_code, c.label as country,";
580 $sql .= " d.code_departement as state_code, d.nom as state,";
581 $sql .= " s.label as label_establishment, u.fk_establishment";
582 $sql .= " FROM ".$this->db->prefix()."user as u";
583 $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as c ON u.fk_country = c.rowid";
584 $sql .= " LEFT JOIN ".$this->db->prefix()."c_departements as d ON u.fk_state = d.rowid";
585 $sql .= " LEFT JOIN ".$this->db->prefix()."establishment as s ON u.fk_establishment = s.rowid";
586
587 if ($entity < 0) {
588 if ((!isModEnabled('multicompany') || !getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) && (!empty($user->entity))) {
589 $sql .= " WHERE u.entity IN (0, ".((int) $conf->entity).")";
590 } else {
591 $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
592 }
593 } else {
594 // The fetch was forced on an entity
595 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
596 $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
597 } else {
598 $sql .= " WHERE u.entity IN (0, ".((int) (($entity != '' && $entity >= 0) ? $entity : $conf->entity)).")"; // search in entity provided in parameter
599 }
600 }
601
602 if ($sid) {
603 // permet une recherche du user par son SID ActiveDirectory ou Samba
604 $sql .= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."')";
605 } elseif ($login) {
606 $sql .= " AND u.login = '".$this->db->escape($login)."'";
607 } elseif ($email) {
608 $sql .= " AND (u.email = '".$this->db->escape($email)."'";
609 if ($use_email_oauth2) {
610 $sql .= " OR u.email_oauth2 = '".$this->db->escape($email)."'";
611 }
612 $sql .= ")";
613 } elseif ($fk_socpeople > 0) {
614 $sql .= " AND u.fk_socpeople = ".((int) $fk_socpeople);
615 } else {
616 $sql .= " AND u.rowid = ".((int) $id);
617 }
618 $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
619
620 if ($sid) {
621 // permet une recherche du user par son SID ActiveDirectory ou Samba
622 $sql .= ' '.$this->db->plimit(1);
623 }
624
625 $resql = $this->db->query($sql);
626 if ($resql) {
627 $num = $this->db->num_rows($resql);
628 if ($num > 1) {
629 $this->error = "USERDUPLICATEFOUND";
630 dol_syslog(get_class($this)."::fetch more than 1 user found", LOG_WARNING);
631
632 $this->db->free($resql);
633 return 0;
634 }
635
636 $obj = $this->db->fetch_object($resql);
637 if ($obj) {
638 $this->id = $obj->rowid;
639 $this->ref = $obj->rowid;
640
641 $this->ref_ext = $obj->ref_ext;
642
643 $this->ldap_sid = $obj->ldap_sid;
644 $this->civility_code = $obj->civility_code;
645 $this->lastname = $obj->lastname;
646 $this->firstname = $obj->firstname;
647 $this->ref_employee = $obj->ref_employee;
648 $this->national_registration_number = $obj->national_registration_number;
649
650 $this->employee = $obj->employee;
651
652 $this->login = $obj->login;
653 $this->gender = $obj->gender;
654 $this->birth = $this->db->jdate($obj->birth);
655 $this->pass_indatabase = $obj->pass;
656 $this->pass_indatabase_crypted = $obj->pass_crypted;
657 $this->pass = $obj->pass;
658 $this->pass_temp = $obj->pass_temp;
659 $this->api_key = dolDecrypt($obj->api_key);
660
661 $this->address = $obj->address;
662 $this->zip = $obj->zip;
663 $this->town = $obj->town;
664
665 $this->country_id = $obj->country_id;
666 $this->country_code = $obj->country_id ? $obj->country_code : '';
667 //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
668
669 $this->state_id = $obj->state_id;
670 $this->state_code = $obj->state_code;
671 $this->state = ($obj->state != '-' ? $obj->state : '');
672
673 $this->office_phone = $obj->office_phone;
674 $this->office_fax = $obj->office_fax;
675 $this->user_mobile = $obj->user_mobile;
676 $this->personal_mobile = $obj->personal_mobile;
677 $this->email = $obj->email;
678 $this->email_oauth2 = $obj->email_oauth2;
679 $this->personal_email = $obj->personal_email;
680 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
681
682 $this->job = $obj->job;
683 $this->signature = $obj->signature;
684 $this->admin = $obj->admin;
685 $this->note_public = $obj->note_public;
686 $this->note_private = $obj->note_private;
687
688 $this->statut = $obj->status; // deprecated
689 $this->status = $obj->status;
690
691 $this->photo = $obj->photo;
692 $this->openid = $obj->openid;
693 $this->lang = $obj->lang;
694 $this->entity = $obj->entity;
695 $this->accountancy_code = $obj->accountancy_code;
696 $this->thm = $obj->thm;
697 $this->tjm = $obj->tjm;
698 $this->salary = $obj->salary;
699 $this->salaryextra = $obj->salaryextra;
700 $this->weeklyhours = $obj->weeklyhours;
701 $this->color = $obj->color;
702 $this->dateemployment = $this->db->jdate($obj->dateemployment);
703 $this->dateemploymentend = $this->db->jdate($obj->dateemploymentend);
704
705 $this->datec = $this->db->jdate($obj->datec);
706 $this->datem = $this->db->jdate($obj->datem);
707 $this->datelastlogin = $this->db->jdate($obj->datel);
708 $this->datepreviouslogin = $this->db->jdate($obj->datep);
709 $this->flagdelsessionsbefore = $this->db->jdate($obj->flagdelsessionsbefore, 'gmt');
710 $this->iplastlogin = $obj->iplastlogin;
711 $this->ippreviouslogin = $obj->ippreviouslogin;
712 $this->datestartvalidity = $this->db->jdate($obj->datestartvalidity);
713 $this->dateendvalidity = $this->db->jdate($obj->dateendvalidity);
714
715 $this->socid = $obj->fk_soc;
716 $this->contact_id = $obj->fk_socpeople;
717 $this->fk_member = $obj->fk_member;
718 $this->fk_user = $obj->fk_user;
719 $this->fk_user_expense_validator = $obj->fk_user_expense_validator;
720 $this->fk_user_holiday_validator = $obj->fk_user_holiday_validator;
721
722 $this->default_range = $obj->default_range;
723 $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
724 $this->fk_warehouse = $obj->fk_warehouse;
725 $this->fk_establishment = $obj->fk_establishment;
726 $this->label_establishment = $obj->label_establishment;
727
728 // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
729 // in such case, this admin user must be admin for ALL entities.
730 if (!isModEnabled('multicompany') && $this->admin && $this->entity == 1) {
731 $this->entity = 0;
732 }
733
734 // Retrieve all extrafield
735 // fetch optionals attributes and labels
736 $this->fetch_optionals();
737
738 $this->db->free($resql);
739 } else {
740 $this->error = "USERNOTFOUND";
741 dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
742
743 $this->db->free($resql);
744 return 0;
745 }
746 } else {
747 $this->error = $this->db->lasterror();
748 return -1;
749 }
750
751 // To get back the global configuration unique to the user
752 if ($loadpersonalconf) {
753 $result = $this->loadPersonalConf();
754
755 $result = $this->loadDefaultValues();
756
757 if ($result < 0) {
758 $this->error = $this->db->lasterror();
759 return -3;
760 }
761 }
762
763 return 1;
764 }
765
766
772 public function loadPersonalConf()
773 {
774 global $conf;
775
776 // Load user->conf for user
777 $sql = "SELECT param, value FROM ".$this->db->prefix()."user_param";
778 $sql .= " WHERE fk_user = ".((int) $this->id);
779 $sql .= " AND entity = ".((int) $conf->entity);
780 //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
781 $resql = $this->db->query($sql);
782 if ($resql) {
783 $num = $this->db->num_rows($resql);
784 $i = 0;
785 while ($i < $num) {
786 $obj = $this->db->fetch_object($resql);
787 $p = (!empty($obj->param) ? $obj->param : '');
788 if (!empty($p)) {
789 $this->conf->$p = $obj->value;
790 }
791 $i++;
792 }
793 $this->db->free($resql);
794
795 return $num;
796 } else {
797 $this->error = $this->db->lasterror();
798
799 return -2;
800 }
801 }
802
808 public function loadDefaultValues()
809 {
810 global $conf;
811
812 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
813 // Load user->default_values for user. TODO Save this in memcached ?
814 require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php';
815
816 $defaultValues = new DefaultValues($this->db);
817 $result = $defaultValues->fetchAll('', '', 0, 0, '(t.user_id:in:0,'.$this->id.') AND (entity:in:'.(isset($this->entity) ? $this->entity : $conf->entity).','.$conf->entity.')'); // User 0 (all) + me (if defined)
818 //$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)
819
820 if (!is_array($result) && $result < 0) {
821 setEventMessages($defaultValues->error, $defaultValues->errors, 'errors');
822 dol_print_error($this->db);
823 return -1;
824 } elseif (count($result) > 0) {
825 foreach ($result as $defval) {
826 if (!empty($defval->page) && !empty($defval->type) && !empty($defval->param)) {
827 $pagewithoutquerystring = $defval->page;
828 $pagequeries = '';
829 $reg = array();
830 if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
831 $pagewithoutquerystring = $reg[1];
832 $pagequeries = $reg[2];
833 }
834 $this->default_values[$pagewithoutquerystring][$defval->type][$pagequeries ? $pagequeries : '_noquery_'][$defval->param] = $defval->value;
835 }
836 }
837 }
838 if (!empty($this->default_values)) {
839 foreach ($this->default_values as $a => $b) {
840 foreach ($b as $c => $d) {
841 krsort($this->default_values[$a][$c]);
842 }
843 }
844 }
845 }
846 return 1;
847 }
848
860 public function hasRight($module, $permlevel1, $permlevel2 = '')
861 {
862 // For compatibility with bad naming permissions on module
863 $moduletomoduletouse = array(
864 'compta' => 'comptabilite',
865 'contract' => 'contrat',
866 'member' => 'adherent',
867 'mo' => 'mrp',
868 'order' => 'commande',
869 'produit' => 'product',
870 'project' => 'projet',
871 'propale' => 'propal',
872 'shipping' => 'expedition',
873 'task' => 'task@projet',
874 'fichinter' => 'ficheinter',
875 'inventory' => 'stock',
876 'invoice' => 'facture',
877 'invoice_supplier' => 'fournisseur',
878 'order_supplier' => 'fournisseur',
879 'knowledgerecord' => 'knowledgerecord@knowledgemanagement',
880 'skill@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
881 'job@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
882 'position@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
883 'facturerec' => 'facture',
884 'margins' => 'margin',
885 );
886
887 if (!empty($moduletomoduletouse[$module])) {
888 $module = $moduletomoduletouse[$module];
889 }
890
891 $moduleRightsMapping = array(
892 'product' => 'produit',
893 'margin' => 'margins',
894 'comptabilite' => 'compta'
895 );
896
897 $rightsPath = $module;
898 if (!empty($moduleRightsMapping[$rightsPath])) {
899 $rightsPath = $moduleRightsMapping[$rightsPath];
900 }
901
902 // If module is abc@module, we check permission user->hasRight(module, abc, permlevel1)
903 $tmp = explode('@', $rightsPath, 2);
904 if (!empty($tmp[1])) {
905 if (strpos($module, '@') !== false) {
906 $module = $tmp[1];
907 }
908 if ($tmp[0] != $tmp[1]) {
909 // If $module = 'myobject@mymodule'
910 $rightsPath = $tmp[1];
911 $permlevel2 = $permlevel1;
912 $permlevel1 = $tmp[0];
913 } else {
914 // If $module = 'abc@abc'
915 $rightsPath = $tmp[1];
916 }
917 }
918
919 // In $conf->modules, we have 'accounting', 'product', 'facture', ...
920 // In $user->rights, we have 'accounting', 'produit', 'facture', ...
921 //var_dump($this->rights->$rightsPath);
922 //var_dump($conf->modules);
923 //var_dump($module.' '.isModEnabled($module).' '.$rightsPath.' '.$permlevel1.' '.$permlevel2);
924 if (!isModEnabled($module)) {
925 return 0;
926 }
927
928 // Special case for external user
929 if (!empty($this->socid)) {
930 if ($module == 'societe' && ($permlevel1 == 'creer' || $permlevel1 == 'write')) {
931 return 0; // An external user never has the permission ->societe->write to see all thirdparties (always restricted to himself)
932 }
933 if ($module == 'societe' && $permlevel1 == 'client' && $permlevel2 == 'voir') {
934 return 0; // An external user never has the permission ->societe->client->voir to see all thirdparties (always restricted to himself)
935 }
936 if ($module == 'societe' && $permlevel1 == 'export') {
937 return 0; // An external user never has the permission ->societe->export to see all thirdparties (always restricted to himself)
938 }
939 if ($module == 'societe' && ($permlevel1 == 'supprimer' || $permlevel1 == 'delete')) {
940 return 0; // An external user never has the permission ->societe->delete to see all thirdparties (always restricted to himself)
941 }
942 }
943
944 // For compatibility with bad naming permissions on permlevel1
945 if ($permlevel1 == 'propale') {
946 $permlevel1 = 'propal';
947 }
948 if ($permlevel1 == 'member') {
949 $permlevel1 = 'adherent';
950 }
951 if ($permlevel1 == 'recruitmentcandidature') {
952 $permlevel1 = 'recruitmentjobposition';
953 }
954
955 //var_dump($this->rights);
956 //var_dump($rightsPath.' '.$permlevel1.' '.$permlevel2);
957 if (empty($rightsPath) || empty($this->rights) || empty($this->rights->$rightsPath) || empty($permlevel1)) {
958 return 0;
959 }
960
961 if ($permlevel2) {
962 if (!empty($this->rights->$rightsPath->$permlevel1)) {
963 if (!empty($this->rights->$rightsPath->$permlevel1->$permlevel2)) {
964 return $this->rights->$rightsPath->$permlevel1->$permlevel2;
965 }
966 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
967 // instead of "read", "write", "delete"
968 if ($permlevel2 == 'read' && !empty($this->rights->$rightsPath->$permlevel1->lire)) {
969 return $this->rights->$rightsPath->$permlevel1->lire;
970 }
971 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->creer)) {
972 return $this->rights->$rightsPath->$permlevel1->creer;
973 }
974 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->create)) {
975 return $this->rights->$rightsPath->$permlevel1->create;
976 }
977 if ($permlevel2 == 'delete' && !empty($this->rights->$rightsPath->$permlevel1->supprimer)) {
978 return $this->rights->$rightsPath->$permlevel1->supprimer;
979 }
980 }
981 } else {
982 if (!empty($this->rights->$rightsPath->$permlevel1)) {
983 return $this->rights->$rightsPath->$permlevel1;
984 }
985 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
986 // instead of "read", "write", "delete"
987 if ($permlevel1 == 'read' && !empty($this->rights->$rightsPath->lire)) {
988 return $this->rights->$rightsPath->lire;
989 }
990 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->creer)) {
991 return $this->rights->$rightsPath->creer;
992 }
993 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->create)) {
994 return $this->rights->$rightsPath->create;
995 }
996 if ($permlevel1 == 'delete' && !empty($this->rights->$rightsPath->supprimer)) {
997 return $this->rights->$rightsPath->supprimer;
998 }
999 }
1000
1001 return 0;
1002 }
1003
1015 public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1016 {
1017 global $conf, $user, $langs;
1018
1019 $entity = (empty($entity) ? $conf->entity : $entity);
1020
1021 dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity, $notrigger for user id=".$this->id);
1022
1023 if (empty($this->id)) {
1024 $this->error = 'Try to call addrights on an object user with an empty id';
1025 return -1;
1026 }
1027
1028 $error = 0;
1029 $whereforadd = '';
1030
1031 $this->db->begin();
1032
1033 if (!empty($rid)) {
1034 $module = $perms = $subperms = '';
1035
1036 // If we ask to add a given permission, we first load properties of this permission (module, perms and subperms).
1037 $sql = "SELECT module, perms, subperms";
1038 $sql .= " FROM ".$this->db->prefix()."rights_def";
1039 $sql .= " WHERE id = ".((int) $rid);
1040 $sql .= " AND entity = ".((int) $entity);
1041
1042 $result = $this->db->query($sql);
1043 if ($result) {
1044 $obj = $this->db->fetch_object($result);
1045
1046 if ($obj) {
1047 $module = $obj->module;
1048 $perms = $obj->perms;
1049 $subperms = $obj->subperms;
1050 }
1051 } else {
1052 $error++;
1053 dol_print_error($this->db);
1054 }
1055
1056 // Define the where for the permission to add
1057 $whereforadd = "id=".((int) $rid);
1058 // Add also inherited permissions
1059 if (!empty($subperms)) {
1060 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))";
1061 } elseif (!empty($perms)) {
1062 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND (subperms IS NULL or subperms = ''))";
1063 }
1064 } else {
1065 // A list of permission was requested (not a single specific permission)
1066 // based on the name of a module of permissions
1067 // Used in the where clause to determine the list of permissions to add.
1068 if (!empty($allmodule)) {
1069 if ($allmodule == 'allmodules') {
1070 $whereforadd = 'allmodules';
1071 } else {
1072 $whereforadd = "module='".$this->db->escape($allmodule)."'";
1073 if (!empty($allperms)) {
1074 $whereforadd .= " AND perms='".$this->db->escape($allperms)."'";
1075 }
1076 }
1077 }
1078 }
1079
1080 // Add automatically other permission using the criteria whereforadd
1081 // $whereforadd can be a SQL filter or the string 'allmodules'
1082 if (!empty($whereforadd)) {
1083 //print "$module-$perms-$subperms";
1084 $sql = "SELECT id";
1085 $sql .= " FROM ".$this->db->prefix()."rights_def";
1086 $sql .= " WHERE entity = ".((int) $entity);
1087 if (!empty($whereforadd) && $whereforadd != 'allmodules') {
1088 $sql .= " AND (".$whereforadd.")"; // Note: parenthesis are important because whereforadd can contains OR. Also note that $whereforadd is already sanitized
1089 }
1090
1091 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1092 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1093 $sqldelete .= $sql;
1094 $sqldelete .= ") AND entity = ".((int) $entity);
1095 if (!$this->db->query($sqldelete)) {
1096 $error++;
1097 }
1098
1099 if (!$error) {
1100 $resql = $this->db->query($sql);
1101 if ($resql) {
1102 $num = $this->db->num_rows($resql);
1103 $i = 0;
1104 while ($i < $num) {
1105 $obj = $this->db->fetch_object($resql);
1106
1107 if ($obj) {
1108 $nid = $obj->id;
1109
1110 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id) VALUES (".((int) $entity).", ".((int) $this->id).", ".((int) $nid).")";
1111 if (!$this->db->query($sql)) {
1112 $error++;
1113 }
1114 }
1115
1116 $i++;
1117 }
1118 } else {
1119 $error++;
1120 dol_print_error($this->db);
1121 }
1122 }
1123 }
1124
1125 if (!$error && !$notrigger) {
1126 $langs->load("other");
1127 $this->context = array('audit' => $langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : ''));
1128
1129 // Call trigger
1130 $result = $this->call_trigger('USER_MODIFY', $user);
1131 if ($result < 0) {
1132 $error++;
1133 }
1134 // End call triggers
1135 }
1136
1137 if ($error) {
1138 $this->db->rollback();
1139 return -$error;
1140 } else {
1141 $this->db->commit();
1142 return 1;
1143 }
1144 }
1145
1146
1158 public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1159 {
1160 global $conf, $user, $langs;
1161
1162 $error = 0;
1163 $wherefordel = '';
1164 $entity = (!empty($entity) ? $entity : $conf->entity);
1165
1166 $this->db->begin();
1167
1168 if (!empty($rid)) {
1169 $module = $perms = $subperms = '';
1170
1171 // When the request is to delete a specific permissions, this gets the
1172 // les charactis for the module, permissions and sub-permission of this permission.
1173 $sql = "SELECT module, perms, subperms";
1174 $sql .= " FROM ".$this->db->prefix()."rights_def";
1175 $sql .= " WHERE id = '".$this->db->escape($rid)."'";
1176 $sql .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1177
1178 $result = $this->db->query($sql);
1179 if ($result) {
1180 $obj = $this->db->fetch_object($result);
1181
1182 if ($obj) {
1183 $module = $obj->module;
1184 $perms = $obj->perms;
1185 $subperms = $obj->subperms;
1186 }
1187 } else {
1188 $error++;
1189 dol_print_error($this->db);
1190 }
1191
1192 // Where clause for the list of permissions to delete
1193 $wherefordel = "id=".((int) $rid);
1194 // Suppression des droits induits
1195 if ($subperms == 'lire' || $subperms == 'read') {
1196 $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)";
1197 }
1198 if ($perms == 'lire' || $perms == 'read') {
1199 $wherefordel .= " OR (module='".$this->db->escape($module)."')";
1200 }
1201 } else {
1202 // The deletion of the permissions concerns the name of a module or
1203 // list of permissions.
1204 // Used in the Where clause to determine the list of permission to delete
1205 if (!empty($allmodule)) {
1206 if ($allmodule == 'allmodules') {
1207 $wherefordel = 'allmodules';
1208 } else {
1209 $wherefordel = "module='".$this->db->escape($allmodule)."'";
1210 if (!empty($allperms)) {
1211 $wherefordel .= " AND perms='".$this->db->escape($allperms)."'";
1212 }
1213 }
1214 }
1215 }
1216
1217 // Delete permission according to a criteria set into $wherefordel
1218 if (!empty($wherefordel)) {
1219 //print "$module-$perms-$subperms";
1220 $sql = "SELECT id";
1221 $sql .= " FROM ".$this->db->prefix()."rights_def";
1222 $sql .= " WHERE entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1223 if (!empty($wherefordel) && $wherefordel != 'allmodules') {
1224 $sql .= " AND (".$wherefordel.")"; // Note: parenthesis are important because wherefordel can contains OR. Also note that $wherefordel is already sanitized
1225 }
1226
1227 // avoid admin to remove his own important rights
1228 if ($this->admin == 1) {
1229 $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
1230 $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
1231 $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
1232 $sql .= " AND id NOT IN (358)"; // user export
1233 }
1234
1235 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1236 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1237 $sqldelete .= $sql;
1238 $sqldelete .= ")";
1239 $sqldelete .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1240
1241 $resql = $this->db->query($sqldelete);
1242 if (!$resql) {
1243 $error++;
1244 dol_print_error($this->db);
1245 }
1246 }
1247
1248 if (!$error && !$notrigger) {
1249 $langs->load("other");
1250 $this->context = array('audit' => $langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : ''));
1251
1252 // Call trigger
1253 $result = $this->call_trigger('USER_MODIFY', $user);
1254 if ($result < 0) {
1255 $error++;
1256 }
1257 // End call triggers
1258 }
1259
1260 if ($error) {
1261 $this->db->rollback();
1262 return -$error;
1263 } else {
1264 $this->db->commit();
1265 return 1;
1266 }
1267 }
1268
1269
1276 public function clearrights()
1277 {
1278 dol_syslog(get_class($this)."::clearrights reset user->rights");
1279 $this->rights = new stdClass();
1280 $this->nb_rights = 0;
1281 $this->all_permissions_are_loaded = 0;
1282 $this->_tab_loaded = array();
1283 }
1284
1285
1294 public function loadRights($moduletag = '', $forcereload = 0)
1295 {
1296 global $conf;
1297
1298 $alreadyloaded = false;
1299
1300 if (empty($forcereload)) {
1301 if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
1302 // Rights for this module are already loaded, so we leave
1303 $alreadyloaded = true;
1304 }
1305
1306 if (!empty($this->all_permissions_are_loaded)) {
1307 // We already loaded all rights for this user, so we leave
1308 $alreadyloaded = true;
1309 }
1310 }
1311
1312 // More init to avoid warnings/errors
1313 if (!isset($this->rights) || !is_object($this->rights)) {
1314 $this->rights = new stdClass();
1315 }
1316 if (!isset($this->rights->user) || !is_object($this->rights->user)) {
1317 $this->rights->user = new stdClass();
1318 }
1319
1320 // Get permission of users + Get permissions of groups
1321
1322 if (!$alreadyloaded) {
1323 // First user permissions
1324 $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1325 $sql .= " FROM ".$this->db->prefix()."user_rights as ur,";
1326 $sql .= " ".$this->db->prefix()."rights_def as r";
1327 $sql .= " WHERE r.id = ur.fk_id";
1328 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1329 // On old version, we used entity defined into table r only
1330 // @FIXME Test on MULTICOMPANY_BACKWARD_COMPATIBILITY is a very strange business rules because the select should be always the
1331 // same than into user->loadRights() in user/perms.php and user/group/perms.php
1332 // We should never use and remove this case.
1333 $sql .= " AND r.entity IN (0,".(isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') ? "1," : "").$conf->entity.")";
1334 } else {
1335 // On table r=rights_def, the unique key is (id, entity) because id is hard coded into module descriptor and inserted during module activation.
1336 // So we must include the filter on entity on both table r. and ur.
1337 $sql .= " AND r.entity = ".((int) $conf->entity)." AND ur.entity = ".((int) $conf->entity);
1338 }
1339 $sql .= " AND ur.fk_user = ".((int) $this->id);
1340 $sql .= " AND r.perms IS NOT NULL";
1341 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1342 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1343 }
1344 if ($moduletag) {
1345 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1346 }
1347
1348 $resql = $this->db->query($sql);
1349 if ($resql) {
1350 $num = $this->db->num_rows($resql);
1351 $i = 0;
1352 while ($i < $num) {
1353 $obj = $this->db->fetch_object($resql);
1354
1355 if ($obj) {
1356 $module = $obj->module;
1357 $perms = $obj->perms;
1358 $subperms = $obj->subperms;
1359
1360 if (!empty($perms)) {
1361 if (!empty($module)) {
1362 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1363 $this->rights->$module = new stdClass();
1364 }
1365 if (!empty($subperms)) {
1366 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1367 $this->rights->$module->$perms = new stdClass();
1368 }
1369 if (empty($this->rights->$module->$perms->$subperms)) { // if not already counted
1370 $this->nb_rights++;
1371 }
1372 $this->rights->$module->$perms->$subperms = 1;
1373 } else {
1374 if (empty($this->rights->$module->$perms)) { // if not already counted
1375 $this->nb_rights++;
1376 }
1377 $this->rights->$module->$perms = 1;
1378 }
1379 }
1380 }
1381 }
1382 $i++;
1383 }
1384 $this->db->free($resql);
1385 }
1386
1387 // Now permissions of groups
1388 $sql = "SELECT DISTINCT r.module, r.perms, r.subperms, r.entity";
1389 $sql .= " FROM ".$this->db->prefix()."usergroup_rights as gr,";
1390 $sql .= " ".$this->db->prefix()."usergroup_user as gu,";
1391 $sql .= " ".$this->db->prefix()."rights_def as r";
1392 $sql .= " WHERE r.id = gr.fk_id";
1393 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1394 // @FIXME Test on MULTICOMPANY_BACKWARD_COMPATIBILITY is a very strange business rules because the select should be always the
1395 // same than into user->loadRights() in user/perms.php and user/group/perms.php
1396 // We should never use and remove this case.
1397 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1398 $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1399 } else {
1400 $sql .= " AND r.entity = ".((int) $conf->entity);
1401 }
1402 } else {
1403 $sql .= " AND gr.entity = ".((int) $conf->entity); // Only groups created in current entity
1404 // The entity on the table gu=usergroup_user should be useless and should never be used because it is already into gr and r.
1405 // but when using MULTICOMPANY_TRANSVERSE_MODE, we may have inserted record that make rubbish result here due to the duplicate record of
1406 // other entities, so we are forced to add a filter on gu here
1407 $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1408 $sql .= " AND r.entity = ".((int) $conf->entity); // Only permission of modules enabled in current entity
1409 }
1410 // End of strange business rule
1411 $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
1412 $sql .= " AND gu.fk_user = ".((int) $this->id);
1413 $sql .= " AND r.perms IS NOT NULL";
1414 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1415 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1416 }
1417 if ($moduletag) {
1418 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1419 }
1420
1421 $resql = $this->db->query($sql);
1422 if ($resql) {
1423 $num = $this->db->num_rows($resql);
1424 $i = 0;
1425 while ($i < $num) {
1426 $obj = $this->db->fetch_object($resql);
1427
1428 if ($obj) {
1429 $module = $obj->module;
1430 $perms = $obj->perms;
1431 $subperms = $obj->subperms;
1432
1433 if (!empty($perms)) {
1434 if (!empty($module)) {
1435 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1436 $this->rights->$module = new stdClass();
1437 }
1438 if (!empty($subperms)) {
1439 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1440 $this->rights->$module->$perms = new stdClass();
1441 }
1442 if (empty($this->rights->$module->$perms->$subperms)) { // if not already counted
1443 $this->nb_rights++;
1444 }
1445 $this->rights->$module->$perms->$subperms = 1;
1446 } else {
1447 // 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
1448 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1449 if (empty($this->rights->$module->$perms)) { // if not already counted
1450 $this->nb_rights++;
1451 }
1452 $this->rights->$module->$perms = 1;
1453 }
1454 }
1455 }
1456 }
1457 }
1458 $i++;
1459 }
1460 $this->db->free($resql);
1461 }
1462
1463 // Force permission on user for admin
1464 if (!empty($this->admin)) {
1465 if (empty($this->rights->user->user)) {
1466 $this->rights->user->user = new stdClass();
1467 }
1468 $listofpermtotest = array('lire', 'creer', 'password', 'supprimer', 'export');
1469 foreach ($listofpermtotest as $permtotest) {
1470 if (empty($this->rights->user->user->$permtotest)) {
1471 $this->rights->user->user->$permtotest = 1;
1472 $this->nb_rights++;
1473 }
1474 }
1475 if (empty($this->rights->user->self)) {
1476 $this->rights->user->self = new stdClass();
1477 }
1478 $listofpermtotest = array('creer', 'password');
1479 foreach ($listofpermtotest as $permtotest) {
1480 if (empty($this->rights->user->self->$permtotest)) {
1481 $this->rights->user->self->$permtotest = 1;
1482 $this->nb_rights++;
1483 }
1484 }
1485 // Add test on advanced permissions
1486 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1487 if (empty($this->rights->user->user_advance)) {
1488 $this->rights->user->user_advance = new stdClass();
1489 }
1490 $listofpermtotest = array('readperms', 'write');
1491 foreach ($listofpermtotest as $permtotest) {
1492 if (empty($this->rights->user->user_advance->$permtotest)) {
1493 $this->rights->user->user_advance->$permtotest = 1;
1494 $this->nb_rights++;
1495 }
1496 }
1497 if (empty($this->rights->user->self_advance)) {
1498 $this->rights->user->self_advance = new stdClass();
1499 }
1500 $listofpermtotest = array('readperms', 'writeperms');
1501 foreach ($listofpermtotest as $permtotest) {
1502 if (empty($this->rights->user->self_advance->$permtotest)) {
1503 $this->rights->user->self_advance->$permtotest = 1;
1504 $this->nb_rights++;
1505 }
1506 }
1507 if (empty($this->rights->user->group_advance)) {
1508 $this->rights->user->group_advance = new stdClass();
1509 }
1510 $listofpermtotest = array('read', 'readperms', 'write', 'delete');
1511 foreach ($listofpermtotest as $permtotest) {
1512 if (empty($this->rights->user) || empty($this->rights->user->group_advance->$permtotest)) {
1513 $this->rights->user->group_advance->$permtotest = 1;
1514 $this->nb_rights++;
1515 }
1516 }
1517 }
1518 }
1519
1520 // For backward compatibility
1521 if (isset($this->rights->propale) && !isset($this->rights->propal)) {
1522 $this->rights->propal = $this->rights->propale;
1523 }
1524 if (isset($this->rights->propal) && !isset($this->rights->propale)) {
1525 $this->rights->propale = $this->rights->propal;
1526 }
1527
1528 if (!$moduletag) {
1529 // If the module was not define, then everything is loaded.
1530 // Therefore, we can consider that the permissions are cached
1531 // because they were all loaded for this user instance.
1532 $this->all_permissions_are_loaded = 1;
1533 } else {
1534 // If the module is defined, we flag it as loaded into cache
1535 $this->_tab_loaded[$moduletag] = 1;
1536 }
1537 }
1538 }
1539
1552 public function getrights($moduletag = '', $forcereload = 0)
1553 {
1554 $this->loadRights($moduletag, $forcereload);
1555 }
1556
1563 public function setstatus($status)
1564 {
1565 global $conf, $langs, $user;
1566
1567 $error = 0;
1568
1569 // Check parameters
1570 if (isset($this->statut)) {
1571 if ($this->statut == $status) {
1572 return 0;
1573 }
1574 } elseif (isset($this->status) && $this->status == $status) {
1575 return 0;
1576 }
1577
1578 $this->db->begin();
1579
1580 // Save in database
1581 $sql = "UPDATE ".$this->db->prefix()."user";
1582 $sql .= " SET statut = ".((int) $status);
1583 $sql .= " WHERE rowid = ".((int) $this->id);
1584 $result = $this->db->query($sql);
1585
1586 dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1587 if ($result) {
1588 if ($status == 0) {
1589 $this->context['actionmsg'] = 'User '.$this->login.' disabled';
1590 } else {
1591 $this->context['actionmsg'] = 'User '.$this->login.' enabled';
1592 }
1593 // Call trigger
1594 $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
1595 if ($result < 0) {
1596 $error++;
1597 }
1598 // End call triggers
1599 }
1600
1601 if ($error) {
1602 $this->db->rollback();
1603 return -$error;
1604 } else {
1605 $this->status = $status;
1606 $this->statut = $status;
1607 $this->db->commit();
1608 return 1;
1609 }
1610 }
1611
1622 public function setCategories($categories)
1623 {
1624 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1625 return parent::setCategoriesCommon($categories, Categorie::TYPE_USER);
1626 }
1627
1634 public function delete(User $user)
1635 {
1636 global $conf, $langs;
1637
1638 $error = 0;
1639
1640 $this->db->begin();
1641
1642 $this->fetch($this->id);
1643
1644 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1645
1646 // Remove rights
1647 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1648
1649 if (!$error && !$this->db->query($sql)) {
1650 $error++;
1651 $this->error = $this->db->lasterror();
1652 }
1653
1654 // Remove group
1655 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1656 if (!$error && !$this->db->query($sql)) {
1657 $error++;
1658 $this->error = $this->db->lasterror();
1659 }
1660
1661 // Remove params
1662 $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1663 if (!$error && !$this->db->query($sql)) {
1664 $error++;
1665 $this->error = $this->db->lasterror();
1666 }
1667
1668 // If contact, remove link
1669 if ($this->contact_id > 0) {
1670 $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1671 if (!$error && !$this->db->query($sql)) {
1672 $error++;
1673 $this->error = $this->db->lasterror();
1674 }
1675 }
1676
1677 // Remove extrafields
1678 if (!$error) {
1679 $result = $this->deleteExtraFields();
1680 if ($result < 0) {
1681 $error++;
1682 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1683 }
1684 }
1685
1686 // Remove user
1687 if (!$error) {
1688 $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1689 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1690 if (!$this->db->query($sql)) {
1691 $error++;
1692 $this->error = $this->db->lasterror();
1693 }
1694 }
1695
1696 if (!$error) {
1697 // Call trigger
1698 $result = $this->call_trigger('USER_DELETE', $user);
1699 if ($result < 0) {
1700 $error++;
1701 $this->db->rollback();
1702 return -1;
1703 }
1704 // End call triggers
1705
1706 $this->db->commit();
1707 return 1;
1708 } else {
1709 $this->db->rollback();
1710 return -1;
1711 }
1712 }
1713
1721 public function create($user, $notrigger = 0)
1722 {
1723 global $conf, $langs;
1724 global $mysoc;
1725
1726 // Clean parameters
1727 $this->setUpperOrLowerCase();
1728
1729 $this->civility_code = trim((string) $this->civility_code);
1730 $this->login = trim((string) $this->login);
1731 if (!isset($this->entity)) {
1732 $this->entity = $conf->entity; // If not defined, we use default value
1733 }
1734
1735 dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1736
1737 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1738
1739 // Check parameters
1740 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
1741 $langs->load("errors");
1742 $this->error = $langs->trans("ErrorBadEMail", $this->email);
1743 return -1;
1744 }
1745 if (empty($this->login)) {
1746 $langs->load("errors");
1747 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1748 return -1;
1749 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1750 $langs->load("errors");
1751 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1752 return -1;
1753 }
1754
1755 $this->datec = dol_now();
1756
1757 $error = 0;
1758 $this->db->begin();
1759
1760 // Check if login already exists in same entity or into entity 0.
1761 if ($this->login) {
1762 $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)."'";
1763 $resqltochecklogin = $this->db->query($sqltochecklogin);
1764 if ($resqltochecklogin) {
1765 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1766 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1767 $langs->load("errors");
1768 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1769 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1770 $this->db->rollback();
1771 return -6;
1772 }
1773 $this->db->free($resqltochecklogin);
1774 }
1775 }
1776 if (!empty($this->email)) {
1777 $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)."'";
1778 $resqltochecklogin = $this->db->query($sqltochecklogin);
1779 if ($resqltochecklogin) {
1780 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1781 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1782 $langs->load("errors");
1783 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1784 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1785 $this->db->rollback();
1786 return -6;
1787 }
1788 $this->db->free($resqltochecklogin);
1789 }
1790 }
1791
1792 // Insert into database
1793 $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, entity)";
1794 $sql .= " VALUES('".$this->db->idate($this->datec)."', '".$this->db->escape($this->login)."', '".$this->db->escape($this->ldap_sid)."', ".((int) $this->entity).")";
1795 $result = $this->db->query($sql);
1796
1797 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1798 if ($result) {
1799 $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1800
1801 // Set default rights
1802 if ($this->set_default_rights() < 0) {
1803 $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1804 $this->db->rollback();
1805 return -5;
1806 }
1807
1808 if (getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && getDolGlobalString('STOCK_USERSTOCK_AUTOCREATE')) {
1809 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1810 $langs->load("stocks");
1811
1812 $entrepot = new Entrepot($this->db);
1813 $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1814 $entrepot->libelle = $entrepot->label; // For backward compatibility
1815 $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1816 $entrepot->statut = 1;
1817 $entrepot->country_id = $mysoc->country_id;
1818
1819 $warehouseid = $entrepot->create($user);
1820
1821 $this->fk_warehouse = $warehouseid;
1822 }
1823
1824 // Update minor fields
1825 $result = $this->update($user, 1, 1);
1826 if ($result < 0) {
1827 $this->db->rollback();
1828 return -4;
1829 }
1830
1831 if (!$notrigger) {
1832 // Call trigger
1833 $result = $this->call_trigger('USER_CREATE', $user);
1834 if ($result < 0) {
1835 $error++;
1836 }
1837 // End call triggers
1838 }
1839
1840 if (!$error) {
1841 $this->db->commit();
1842 return $this->id;
1843 } else {
1844 //$this->error=$interface->error;
1845 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1846 $this->db->rollback();
1847 return -3;
1848 }
1849 } else {
1850 $this->error = $this->db->lasterror();
1851 $this->db->rollback();
1852 return -2;
1853 }
1854 }
1855
1856
1857 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1866 public function create_from_contact($contact, $login = '', $password = '')
1867 {
1868 // phpcs:enable
1869 global $conf, $user, $langs;
1870
1871 $error = 0;
1872
1873 // Define parameters
1874 $this->admin = 0;
1875 $this->civility_code = $contact->civility_code;
1876 $this->lastname = $contact->lastname;
1877 $this->firstname = $contact->firstname;
1878 //$this->gender = $contact->gender; // contact has no gender
1879 $this->email = $contact->email;
1880 $this->socialnetworks = $contact->socialnetworks;
1881 $this->office_phone = $contact->phone_pro;
1882 $this->office_fax = $contact->fax;
1883 $this->user_mobile = $contact->phone_mobile;
1884 $this->address = $contact->address;
1885 $this->zip = $contact->zip;
1886 $this->town = $contact->town;
1887 $this->setUpperOrLowerCase();
1888 $this->state_id = $contact->state_id;
1889 $this->country_id = $contact->country_id;
1890 $this->employee = 0;
1891
1892 if (empty($login)) {
1893 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1894 $login = dol_buildlogin($contact->lastname, $contact->firstname);
1895 }
1896 $this->login = $login;
1897
1898 $this->db->begin();
1899
1900 // Create user and set $this->id. Trigger is disabled because executed later.
1901 $result = $this->create($user, 1);
1902 if ($result > 0) {
1903 $sql = "UPDATE ".$this->db->prefix()."user";
1904 $sql .= " SET fk_socpeople=".((int) $contact->id);
1905 $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
1906 if ($contact->socid > 0) {
1907 $sql .= ", fk_soc=".((int) $contact->socid);
1908 }
1909 $sql .= " WHERE rowid=".((int) $this->id);
1910
1911 $resql = $this->db->query($sql);
1912
1913 dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1914 if ($resql) {
1915 $this->context['createfromcontact'] = 'createfromcontact';
1916
1917 // Call trigger
1918 $result = $this->call_trigger('USER_CREATE', $user);
1919 if ($result < 0) {
1920 $error++;
1921 $this->db->rollback();
1922 return -1;
1923 }
1924 // End call triggers
1925
1926 $this->db->commit();
1927 return $this->id;
1928 } else {
1929 $this->error = $this->db->error();
1930
1931 $this->db->rollback();
1932 return -1;
1933 }
1934 } else {
1935 // $this->error deja positionne
1936 dol_syslog(get_class($this)."::create_from_contact - 0");
1937
1938 $this->db->rollback();
1939 return $result;
1940 }
1941 }
1942
1943 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1952 public function create_from_member($member, $login = '')
1953 {
1954 // phpcs:enable
1955 global $user;
1956
1957 // Set properties on new user
1958 $this->admin = 0;
1959 $this->civility_code = $member->civility_code;
1960 $this->lastname = $member->lastname;
1961 $this->firstname = $member->firstname;
1962 $this->gender = $member->gender;
1963 $this->email = $member->email;
1964 $this->fk_member = $member->id;
1965 $this->address = $member->address;
1966 $this->zip = $member->zip;
1967 $this->town = $member->town;
1968 $this->setUpperOrLowerCase();
1969 $this->state_id = $member->state_id;
1970 $this->country_id = $member->country_id;
1971 $this->socialnetworks = $member->socialnetworks;
1972
1973 $this->pass = $member->pass;
1974 $this->pass_crypted = $member->pass_indatabase_crypted;
1975
1976 if (empty($login)) {
1977 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1978 $login = dol_buildlogin($member->lastname, $member->firstname);
1979 }
1980 $this->login = $login;
1981
1982 $this->db->begin();
1983
1984 // Create and set $this->id
1985 $result = $this->create($user);
1986 if ($result > 0) {
1987 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
1988 $newpass = $this->setPassword($user, $this->pass);
1989 if (is_int($newpass) && $newpass < 0) {
1990 $result = -2;
1991 }
1992 } elseif (!empty($this->pass_crypted)) { // If an encrypted password is already known, we save it directly into database because the previous create did not save it.
1993 $sql = "UPDATE ".$this->db->prefix()."user";
1994 $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
1995 $sql .= " WHERE rowid=".((int) $this->id);
1996
1997 $resql = $this->db->query($sql);
1998 if (!$resql) {
1999 $result = -1;
2000 }
2001 }
2002
2003 if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
2004 $sql = "UPDATE ".$this->db->prefix()."user";
2005 $sql .= " SET fk_soc=".((int) $member->socid);
2006 $sql .= " WHERE rowid=".((int) $this->id);
2007
2008 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
2009 $resql = $this->db->query($sql);
2010 if ($resql) {
2011 $this->db->commit();
2012 return $this->id;
2013 } else {
2014 $this->error = $this->db->lasterror();
2015
2016 $this->db->rollback();
2017 return -1;
2018 }
2019 }
2020 }
2021
2022 if ($result > 0) {
2023 $this->db->commit();
2024 return $this->id;
2025 } else {
2026 // $this->error was already set
2027 $this->db->rollback();
2028 return -2;
2029 }
2030 }
2031
2032 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2038 public function set_default_rights()
2039 {
2040 // phpcs:enable
2041 global $conf;
2042
2043 $rd = array();
2044 $num = 0;
2045 $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
2046 $sql .= " WHERE bydefault = 1";
2047 $sql .= " AND entity = ".((int) $conf->entity);
2048
2049 $resql = $this->db->query($sql);
2050 if ($resql) {
2051 $num = $this->db->num_rows($resql);
2052 $i = 0;
2053 while ($i < $num) {
2054 $row = $this->db->fetch_row($resql);
2055 $rd[$i] = $row[0];
2056 $i++;
2057 }
2058 $this->db->free($resql);
2059 }
2060 $i = 0;
2061 while ($i < $num) {
2062 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
2063 $result = $this->db->query($sql);
2064
2065 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
2066 $result = $this->db->query($sql);
2067 if (!$result) {
2068 return -1;
2069 }
2070 $i++;
2071 }
2072
2073 return $i;
2074 }
2075
2086 public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
2087 {
2088 global $conf, $langs;
2089
2090 $nbrowsaffected = 0;
2091 $error = 0;
2092
2093 dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
2094
2095 // Clean parameters
2096 $this->civility_code = trim((string) $this->civility_code);
2097 $this->lastname = trim((string) $this->lastname);
2098 $this->firstname = trim((string) $this->firstname);
2099 $this->ref_employee = trim((string) $this->ref_employee);
2100 $this->national_registration_number = trim((string) $this->national_registration_number);
2101 $this->employee = ($this->employee > 0 ? $this->employee : 0);
2102 $this->login = trim((string) $this->login);
2103 $this->gender = trim((string) $this->gender);
2104
2105 $this->pass = trim((string) $this->pass);
2106 $this->api_key = trim((string) $this->api_key);
2107 $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
2108 $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
2109
2110 $this->address = trim((string) $this->address);
2111 $this->zip = trim((string) $this->zip);
2112 $this->town = trim((string) $this->town);
2113
2114 $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
2115 $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
2116 $this->office_phone = trim((string) $this->office_phone);
2117 $this->office_fax = trim((string) $this->office_fax);
2118 $this->user_mobile = trim((string) $this->user_mobile);
2119 $this->personal_mobile = trim((string) $this->personal_mobile);
2120 $this->email = trim((string) $this->email);
2121 $this->personal_email = trim((string) $this->personal_email);
2122
2123 $this->job = trim((string) $this->job);
2124 $this->signature = trim((string) $this->signature);
2125 $this->note_public = trim((string) $this->note_public);
2126 $this->note_private = trim((string) $this->note_private);
2127 $this->openid = trim((string) $this->openid);
2128 $this->admin = ($this->admin > 0 ? $this->admin : 0);
2129
2130 $this->accountancy_code = trim((string) $this->accountancy_code);
2131 $this->color = trim((string) $this->color);
2132 $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
2133 $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
2134
2135 $this->birth = empty($this->birth) ? '' : $this->birth;
2136 $this->fk_warehouse = (int) $this->fk_warehouse;
2137 $this->fk_establishment = (int) $this->fk_establishment;
2138
2139 $this->setUpperOrLowerCase();
2140
2141 // Check parameters
2142 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
2143
2144 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
2145 $langs->load("errors");
2146 $this->error = $langs->trans("ErrorBadEMail", $this->email);
2147 return -1;
2148 }
2149 if (empty($this->login)) {
2150 $langs->load("errors");
2151 $this->error = $langs->trans("ErrorFieldRequired", 'Login');
2152 return -1;
2153 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
2154 $langs->load("errors");
2155 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
2156 return -1;
2157 }
2158
2159 $this->db->begin();
2160
2161 // Check if login already exists in same entity or into entity 0.
2162 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->oldcopy->login != $this->login) {
2163 $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)."'";
2164 $resqltochecklogin = $this->db->query($sqltochecklogin);
2165 if ($resqltochecklogin) {
2166 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2167 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2168 $langs->load("errors");
2169 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
2170 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2171 $this->db->rollback();
2172 return -1;
2173 }
2174 }
2175 }
2176 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && !empty($this->email) && $this->oldcopy->email != $this->email) {
2177 $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)."'";
2178 $resqltochecklogin = $this->db->query($sqltochecklogin);
2179 if ($resqltochecklogin) {
2180 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2181 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2182 $langs->load("errors");
2183 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
2184 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2185 $this->db->rollback();
2186 return -1;
2187 }
2188 }
2189 }
2190
2191 // Update data
2192 $sql = "UPDATE ".$this->db->prefix()."user SET";
2193 $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
2194 $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
2195 $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
2196 $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
2197 $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
2198 $sql .= ", employee = ".(int) $this->employee;
2199 $sql .= ", login = '".$this->db->escape($this->login)."'";
2200 $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
2201 $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' or 'other'
2202 $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
2203 if (!empty($user->admin)) {
2204 $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
2205 }
2206 $sql .= ", address = '".$this->db->escape($this->address)."'";
2207 $sql .= ", zip = '".$this->db->escape($this->zip)."'";
2208 $sql .= ", town = '".$this->db->escape($this->town)."'";
2209 $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".$this->db->escape($this->state_id)."'" : "null");
2210 $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".$this->db->escape($this->country_id)."'" : "null");
2211 $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
2212 $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
2213 $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
2214 $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
2215 $sql .= ", email = '".$this->db->escape($this->email)."'";
2216 $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
2217 $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
2218 $sql .= ", job = '".$this->db->escape($this->job)."'";
2219 $sql .= ", signature = '".$this->db->escape($this->signature)."'";
2220 $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
2221 $sql .= ", color = '".$this->db->escape($this->color)."'";
2222 $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
2223 $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
2224 $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2225 $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2226 $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2227 $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2228 $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2229 $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2230 $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".$this->db->escape($this->fk_user)."'" : "null");
2231 $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".$this->db->escape($this->fk_user_expense_validator)."'" : "null");
2232 $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".$this->db->escape($this->fk_user_holiday_validator)."'" : "null");
2233 if (isset($this->thm) || $this->thm != '') {
2234 $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2235 }
2236 if (isset($this->tjm) || $this->tjm != '') {
2237 $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2238 }
2239 if (isset($this->salary) || $this->salary != '') {
2240 $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2241 }
2242 if (isset($this->salaryextra) || $this->salaryextra != '') {
2243 $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2244 }
2245 $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2246 if (!empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2247 $sql .= ", entity = ".((int) $this->entity); // entity flag can be set/unset only by an another superadmin user
2248 }
2249 $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
2250 $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
2251 $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
2252 $sql .= ", fk_establishment = ".($this->fk_establishment > 0 ? $this->fk_establishment : "null");
2253 $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2254 $sql .= " WHERE rowid = ".((int) $this->id);
2255
2256 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2257 $resql = $this->db->query($sql);
2258 if ($resql) {
2259 $nbrowsaffected += $this->db->affected_rows($resql);
2260
2261 // Update password
2262 if (!empty($this->pass)) {
2263 if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2264 // If a new value for password is set and different than the one encrypted into database
2265 $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2266 if (is_int($result) && $result < 0) {
2267 return -5;
2268 }
2269 }
2270 }
2271
2272 // If user is linked to a member, remove old link to this member
2273 if ($this->fk_member > 0) {
2274 dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2275 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2276 $resql = $this->db->query($sql);
2277 if (!$resql) {
2278 $this->error = $this->db->error();
2279 $this->db->rollback();
2280 return -5;
2281 }
2282 }
2283 // Set link to user
2284 dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2285 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2286 $resql = $this->db->query($sql);
2287 if (!$resql) {
2288 $this->error = $this->db->error();
2289 $this->db->rollback();
2290 return -5;
2291 }
2292
2293 if ($nbrowsaffected) { // If something has changed in data
2294 if ($this->fk_member > 0 && !$nosyncmember) {
2295 dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2296
2297 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2298
2299 // This user is linked with a member, so we also update member information
2300 // if this is an update.
2301 $adh = new Adherent($this->db);
2302 $result = $adh->fetch($this->fk_member);
2303
2304 if ($result > 0) {
2305 $adh->civility_code = $this->civility_code;
2306 $adh->firstname = $this->firstname;
2307 $adh->lastname = $this->lastname;
2308 $adh->login = $this->login;
2309 $adh->gender = $this->gender;
2310 $adh->birth = $this->birth;
2311
2312 $adh->pass = $this->pass;
2313
2314 $adh->address = $this->address;
2315 $adh->town = $this->town;
2316 $adh->zip = $this->zip;
2317 $adh->state_id = $this->state_id;
2318 $adh->country_id = $this->country_id;
2319
2320 $adh->email = $this->email;
2321
2322 $adh->socialnetworks = $this->socialnetworks;
2323
2324 $adh->phone = $this->office_phone;
2325 $adh->phone_mobile = $this->user_mobile;
2326
2327 $adh->default_lang = $this->lang;
2328
2329 $adh->user_id = $this->id;
2330 $adh->user_login = $this->login;
2331
2332 $result = $adh->update($user, 0, 1, 0);
2333 if ($result < 0) {
2334 $this->error = $adh->error;
2335 $this->errors = $adh->errors;
2336 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2337 $error++;
2338 }
2339 } elseif ($result < 0) {
2340 $this->error = $adh->error;
2341 $this->errors = $adh->errors;
2342 $error++;
2343 }
2344 }
2345
2346 if ($this->contact_id > 0 && !$nosynccontact) {
2347 dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2348
2349 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2350
2351 // This user is linked with a contact, so we also update contact information if this is an update.
2352 $tmpobj = new Contact($this->db);
2353 $result = $tmpobj->fetch($this->contact_id);
2354
2355 if ($result >= 0) {
2356 $tmpobj->civility_code = $this->civility_code;
2357 $tmpobj->firstname = $this->firstname;
2358 $tmpobj->lastname = $this->lastname;
2359 $tmpobj->login = $this->login;
2360 $tmpobj->gender = $this->gender;
2361 $tmpobj->birth = $this->birth;
2362
2363 //$tmpobj->pass=$this->pass;
2364
2365 $tmpobj->email = $this->email;
2366
2367 $tmpobj->socialnetworks = $this->socialnetworks;
2368
2369 $tmpobj->phone_pro = $this->office_phone;
2370 $tmpobj->phone_mobile = $this->user_mobile;
2371 $tmpobj->fax = $this->office_fax;
2372
2373 $tmpobj->default_lang = $this->lang;
2374
2375 $tmpobj->address = $this->address;
2376 $tmpobj->town = $this->town;
2377 $tmpobj->zip = $this->zip;
2378 $tmpobj->state_id = $this->state_id;
2379 $tmpobj->country_id = $this->country_id;
2380
2381 $tmpobj->user_id = $this->id;
2382 $tmpobj->user_login = $this->login;
2383
2384 $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2385 if ($result < 0) {
2386 $this->error = $tmpobj->error;
2387 $this->errors = $tmpobj->errors;
2388 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2389 $error++;
2390 }
2391 } else {
2392 $this->error = $tmpobj->error;
2393 $this->errors = $tmpobj->errors;
2394 $error++;
2395 }
2396 }
2397 }
2398
2399 $action = 'update';
2400
2401 // Actions on extra fields
2402 if (!$error) {
2403 $result = $this->insertExtraFields();
2404 if ($result < 0) {
2405 $error++;
2406 }
2407 }
2408
2409 if (!$error && !$notrigger) {
2410 // Call trigger
2411 $result = $this->call_trigger('USER_MODIFY', $user);
2412 if ($result < 0) {
2413 $error++;
2414 }
2415 // End call triggers
2416 }
2417
2418 if (!$error) {
2419 $this->db->commit();
2420 return $nbrowsaffected;
2421 } else {
2422 dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2423 $this->db->rollback();
2424 return -1;
2425 }
2426 } else {
2427 $this->error = $this->db->lasterror();
2428 $this->db->rollback();
2429 return -2;
2430 }
2431 }
2432
2433 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2440 public function update_last_login_date()
2441 {
2442 // phpcs:enable
2443 $now = dol_now();
2444
2445 $userremoteip = getUserRemoteIP();
2446
2447 $sql = "UPDATE ".$this->db->prefix()."user SET";
2448 $sql .= " datepreviouslogin = datelastlogin,";
2449 $sql .= " ippreviouslogin = iplastlogin,";
2450 $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2451 $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2452 $sql .= " tms = tms"; // The last update date must change because the last login date is updated
2453 $sql .= " WHERE rowid = ".((int) $this->id);
2454
2455 dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2456 $resql = $this->db->query($sql);
2457 if ($resql) {
2458 $this->datepreviouslogin = $this->datelastlogin;
2459 $this->datelastlogin = $now;
2460 $this->ippreviouslogin = $this->iplastlogin;
2461 $this->iplastlogin = $userremoteip;
2462 return 1;
2463 } else {
2464 $this->error = $this->db->lasterror().' sql='.$sql;
2465 return -1;
2466 }
2467 }
2468
2469
2482 public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2483 {
2484 global $conf, $langs;
2485 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2486
2487 $error = 0;
2488
2489 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2490
2491 // If new password not provided, we generate one
2492 if (!$password) {
2493 $password = getRandomPassword(false);
2494 }
2495
2496 $password_crypted = null;
2497 // Check and encrypt the password
2498 if (empty($passwordalreadycrypted)) {
2499 if (getDolGlobalString('USER_PASSWORD_GENERATED')) {
2500 // Add a check on rules for password syntax using the setup of the password generator
2501 $modGeneratePassClass = 'modGeneratePass'.ucfirst($conf->global->USER_PASSWORD_GENERATED);
2502
2503 include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2504 if (class_exists($modGeneratePassClass)) {
2505 $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2506 '@phan-var-force ModeleGenPassword $modGeneratePass';
2507
2508 // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2509 $modGeneratePass->WithoutAmbi = 0;
2510
2511 // Call to validatePassword($password) to check pass match rules
2512 $testpassword = $modGeneratePass->validatePassword($password);
2513 if (!$testpassword) {
2514 $this->error = $modGeneratePass->error;
2515 return -1;
2516 }
2517 }
2518 }
2519
2520
2521 // Now, we encrypt the new password
2522 $password_crypted = dol_hash($password);
2523 }
2524
2525 // Update password
2526 if (!$changelater) {
2527 if (!is_object($this->oldcopy)) {
2528 $this->oldcopy = clone $this;
2529 }
2530
2531 $this->db->begin();
2532
2533 $sql = "UPDATE ".$this->db->prefix()."user";
2534 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2535 $sql .= " pass_temp = null";
2536 if (!empty($flagdelsessionsbefore)) {
2537 $sql .= ", flagdelsessionsbefore = '".$this->db->idate(dol_now() - 5, 'gmt')."'";
2538 }
2539 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
2540 $sql .= ", pass = null";
2541 } else {
2542 $sql .= ", pass = '".$this->db->escape($password)."'";
2543 }
2544 $sql .= " WHERE rowid = ".((int) $this->id);
2545
2546 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2547 $result = $this->db->query($sql);
2548 if ($result) {
2549 if ($this->db->affected_rows($result)) {
2550 $this->pass = $password;
2551 $this->pass_indatabase = $password;
2552 $this->pass_indatabase_crypted = (string) $password_crypted;
2553
2554 if ($this->fk_member && !$nosyncmember) {
2555 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2556
2557 // This user is linked with a member, so we also update members information
2558 // if this is an update.
2559 $adh = new Adherent($this->db);
2560 $result = $adh->fetch($this->fk_member);
2561
2562 if ($result >= 0) {
2563 $result = $adh->setPassword($user, $this->pass, (!getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 0 : 1), 1); // The encryption is not managed in the 'adherent' module
2564 if (is_int($result) && $result < 0) {
2565 $this->error = $adh->error;
2566 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2567 $error++;
2568 }
2569 } else {
2570 $this->error = $adh->error;
2571 $error++;
2572 }
2573 }
2574
2575 dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2576
2577 if (!$error && !$notrigger) {
2578 // Call trigger
2579 $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2580 if ($result < 0) {
2581 $error++;
2582 $this->db->rollback();
2583 return -1;
2584 }
2585 // End call triggers
2586 }
2587
2588 $this->db->commit();
2589 return $this->pass;
2590 } else {
2591 $this->db->rollback();
2592 return 0;
2593 }
2594 } else {
2595 $this->db->rollback();
2596 dol_print_error($this->db);
2597 return -1;
2598 }
2599 } else {
2600 // We store password in password temporary field.
2601 // After receiving confirmation link, we will erase and store it in pass_crypted
2602 $sql = "UPDATE ".$this->db->prefix()."user";
2603 $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2604 $sql .= " WHERE rowid = ".((int) $this->id);
2605
2606 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2607 $result = $this->db->query($sql);
2608 if ($result) {
2609 return $password;
2610 } else {
2611 dol_print_error($this->db);
2612 return -3;
2613 }
2614 }
2615 }
2616
2617 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2626 public function send_password($user, $password = '', $changelater = 0)
2627 {
2628 // phpcs:enable
2629 global $conf, $langs, $mysoc;
2630 global $dolibarr_main_url_root;
2631
2632 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2633
2634 $msgishtml = 0;
2635
2636 // Define $msg
2637 $mesg = '';
2638
2639 $outputlangs = new Translate("", $conf);
2640
2641 if (isset($this->conf->MAIN_LANG_DEFAULT)
2642 && $this->conf->MAIN_LANG_DEFAULT != 'auto') { // If user has defined its own language (rare because in most cases, auto is used)
2643 $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2644 }
2645
2646 if ($this->conf->MAIN_LANG_DEFAULT) {
2647 $outputlangs->setDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2648 } else { // If user has not defined its own language, we used current language
2649 $outputlangs = $langs;
2650 }
2651
2652 // Load translation files required by the page
2653 $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2654
2655 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', constant('DOL_APPLICATION_TITLE'));
2656
2657 $subject = '['.$appli.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2658
2659 // Define $urlwithroot
2660 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2661 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2662
2663 if (!$changelater) {
2664 $url = $urlwithroot.'/';
2665 if (getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD')) {
2666 $url = getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD');
2667 }
2668
2669 dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2670
2671 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2672 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2673 $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2674 $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2675 $mesg .= "\n";
2676
2677 $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2678 $mesg .= "--\n";
2679 $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2680 } else {
2681 //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2682 $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2683 $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2684 if (isModEnabled('multicompany')) {
2685 $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2686 }
2687
2688 dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2689
2690 $msgishtml = 1;
2691
2692 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2693 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2694 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2695 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2696 $mesg .= "<br>\n";
2697 $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2698 $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2699 $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2700 }
2701
2702 $trackid = 'use'.$this->id;
2703 $sendcontext = 'passwordreset';
2704
2705 $mailfile = new CMailFile(
2706 $subject,
2707 $this->email,
2708 $conf->global->MAIN_MAIL_EMAIL_FROM,
2709 $mesg,
2710 array(),
2711 array(),
2712 array(),
2713 '',
2714 '',
2715 0,
2716 $msgishtml,
2717 '',
2718 '',
2719 $trackid,
2720 '',
2721 $sendcontext
2722 );
2723
2724 if ($mailfile->sendfile()) {
2725 return 1;
2726 } else {
2727 $langs->trans("errors");
2728 $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2729 return -1;
2730 }
2731 }
2732
2738 public function error()
2739 {
2740 return $this->error;
2741 }
2742
2743
2744 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2750 public function fetch_clicktodial()
2751 {
2752 // phpcs:enable
2753 $sql = "SELECT url, login, pass, poste ";
2754 $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2755 $sql .= " WHERE u.fk_user = ".((int) $this->id);
2756
2757 $resql = $this->db->query($sql);
2758 if ($resql) {
2759 if ($this->db->num_rows($resql)) {
2760 $obj = $this->db->fetch_object($resql);
2761
2762 $this->clicktodial_url = $obj->url;
2763 $this->clicktodial_login = $obj->login;
2764 $this->clicktodial_password = $obj->pass;
2765 $this->clicktodial_poste = $obj->poste;
2766 }
2767
2768 $this->clicktodial_loaded = 1; // Data loaded (found or not)
2769
2770 $this->db->free($resql);
2771 return 1;
2772 } else {
2773 $this->error = $this->db->error();
2774 return -1;
2775 }
2776 }
2777
2778 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2784 public function update_clicktodial()
2785 {
2786 // phpcs:enable
2787 $this->db->begin();
2788
2789 $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2790 $sql .= " WHERE fk_user = ".((int) $this->id);
2791
2792 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2793
2794 $result = $this->db->query($sql);
2795
2796 $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
2797 $sql .= " (fk_user,url,login,pass,poste)";
2798 $sql .= " VALUES (".$this->id;
2799 $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2800 $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2801 $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2802 $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2803
2804 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2805
2806 $result = $this->db->query($sql);
2807 if ($result) {
2808 $this->db->commit();
2809 return 1;
2810 } else {
2811 $this->db->rollback();
2812 $this->error = $this->db->lasterror();
2813 return -1;
2814 }
2815 }
2816
2817
2818 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2827 public function SetInGroup($group, $entity, $notrigger = 0)
2828 {
2829 // phpcs:enable
2830 global $conf, $langs, $user;
2831
2832 $error = 0;
2833
2834 $this->db->begin();
2835
2836 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2837 $sql .= " WHERE fk_user = ".((int) $this->id);
2838 $sql .= " AND fk_usergroup = ".((int) $group);
2839 $sql .= " AND entity = ".((int) $entity);
2840
2841 $result = $this->db->query($sql);
2842
2843 $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
2844 $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
2845
2846 $result = $this->db->query($sql);
2847 if ($result) {
2848 if (!$error && !$notrigger) {
2849 $this->context = array('audit' => $langs->trans("UserSetInGroup"), 'newgroupid' => $group);
2850
2851 // Call trigger
2852 $result = $this->call_trigger('USER_MODIFY', $user);
2853 if ($result < 0) {
2854 $error++;
2855 }
2856 // End call triggers
2857 }
2858
2859 if (!$error) {
2860 $this->db->commit();
2861 return 1;
2862 } else {
2863 dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2864 $this->db->rollback();
2865 return -2;
2866 }
2867 } else {
2868 $this->error = $this->db->lasterror();
2869 $this->db->rollback();
2870 return -1;
2871 }
2872 }
2873
2874 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2883 public function RemoveFromGroup($group, $entity, $notrigger = 0)
2884 {
2885 // phpcs:enable
2886 global $conf, $langs, $user;
2887
2888 $error = 0;
2889
2890 $this->db->begin();
2891
2892 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2893 $sql .= " WHERE fk_user = ".((int) $this->id);
2894 $sql .= " AND fk_usergroup = ".((int) $group);
2895 if (empty($entity)) {
2896 $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
2897 } else {
2898 $sql .= " AND entity = ".((int) $entity);
2899 }
2900
2901 $result = $this->db->query($sql);
2902 if ($result) {
2903 if (!$error && !$notrigger) {
2904 $this->context = array('audit' => $langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
2905
2906 // Call trigger
2907 $result = $this->call_trigger('USER_MODIFY', $user);
2908 if ($result < 0) {
2909 $error++;
2910 }
2911 // End call triggers
2912 }
2913
2914 if (!$error) {
2915 $this->db->commit();
2916 return 1;
2917 } else {
2918 dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2919 $this->db->rollback();
2920 return -2;
2921 }
2922 } else {
2923 $this->error = $this->db->lasterror();
2924 $this->db->rollback();
2925 return -1;
2926 }
2927 }
2928
2929
2937 {
2938 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2939
2940 $now = dol_now();
2941
2942 //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
2943
2944 // Check date start validity
2945 if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
2946 return 1;
2947 }
2948 // Check date end validity
2949 if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
2950 return 1;
2951 }
2952
2953 return 0;
2954 }
2955
2956
2968 public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
2969 {
2970 $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2971 $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
2972 $result .= '</a>';
2973
2974 return $result;
2975 }
2976
2983 public function getTooltipContentArray($params)
2984 {
2985 global $conf, $langs, $menumanager;
2986 global $dolibarr_main_demo;
2987
2988 $infologin = $params['infologin'] ?? 0;
2989 $option = $params['option'] ?? '';
2990
2991 $data = [];
2992 if (!empty($this->photo)) {
2993 $photo = '<div class="photointooltip floatright">';
2994 $photo .= Form::showphoto('userphoto', $this, 0, 60, 0, 'photoref photowithmargin photologintooltip', 'small', 0, 1); // Force height to 60 so we total height of tooltip can be calculated and collision can be managed
2995 $photo .= '</div>';
2996 $data['photo'] = $photo;
2997 //$label .= '<div style="clear: both;"></div>';
2998 }
2999
3000 // Info Login
3001 $data['opendiv'] = '<div class="centpercent divtooltip">';
3002 $data['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
3003 $data['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs));
3004 if (!empty($this->login)) {
3005 $data['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
3006 }
3007 if (!empty($this->job)) {
3008 $data['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
3009 }
3010 $data['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
3011 if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
3012 $phonelist = array();
3013 if ($this->office_phone) {
3014 $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3015 }
3016 if ($this->office_fax) {
3017 $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3018 }
3019 if ($this->user_mobile) {
3020 $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3021 }
3022 $data['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
3023 }
3024 if (!empty($this->admin)) {
3025 $data['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
3026 }
3027 if (!empty($this->accountancy_code) || $option == 'accountancy') {
3028 $langs->load("companies");
3029 $data['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
3030 }
3031 $company = '';
3032 if (!empty($this->socid)) { // Add thirdparty for external users
3033 $thirdpartystatic = new Societe($this->db);
3034 $thirdpartystatic->fetch($this->socid);
3035 $companyimg = '';
3036 if (empty($params['hidethirdpartylogo'])) {
3037 $companyimg = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3038 }
3039 $company = ' ('.$langs->trans("Company").': '.($companyimg ? $companyimg : img_picto('', 'company')).' '.dol_string_nohtmltag($thirdpartystatic->name).')';
3040 }
3041 $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
3042 $data['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
3043 $data['closediv'] = '</div>';
3044
3045 if ($infologin > 0) {
3046 $data['newlinelogin'] = '<br>';
3047 $data['session'] = '<br><u>'.$langs->trans("Session").'</u>';
3048 $data['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
3049 if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
3050 $data['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
3051 }
3052 $data['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
3053 $data['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
3054 $data['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
3055 $data['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
3056 // @phan-suppress-next-line PhanRedefinedClassReference
3057 $data['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
3058 $s = picto_from_langcode($langs->getDefaultLang());
3059 $data['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
3060 $data['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
3061 $data['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
3062 $data['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
3063 if ($conf->browser->layout == 'phone') {
3064 $data['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
3065 }
3066 if (!empty($_SESSION["disablemodules"])) {
3067 $data['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(implode(', ', explode(',', $_SESSION["disablemodules"])));
3068 }
3069 }
3070
3071 return $data;
3072 }
3073
3089 public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
3090 {
3091 global $langs, $hookmanager, $user;
3092
3093 if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
3094 $option = 'nolink';
3095 }
3096
3097 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
3098 $withpictoimg = 0;
3099 }
3100
3101 $result = '';
3102 $params = [
3103 'id' => $this->id,
3104 'objecttype' => $this->element,
3105 'infologin' => $infologin,
3106 'option' => $option,
3107 'hidethirdpartylogo' => $hidethirdpartylogo,
3108 ];
3109 $classfortooltip = 'classfortooltip';
3110 $dataparams = '';
3111 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3112 $classfortooltip = 'classforajaxtooltip';
3113 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3114 $label = '';
3115 } else {
3116 $label = implode($this->getTooltipContentArray($params));
3117 }
3118
3119 $companylink = '';
3120 if (!empty($this->socid)) { // Add thirdparty for external users
3121 $thirdpartystatic = new Societe($this->db);
3122 $thirdpartystatic->fetch($this->socid);
3123 if (empty($hidethirdpartylogo)) {
3124 $companylink = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3125 }
3126 }
3127
3128 if ($infologin < 0) {
3129 $label = '';
3130 }
3131
3132 $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id;
3133 if ($option == 'leave') {
3134 $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id;
3135 }
3136
3137 if ($option != 'nolink') {
3138 // Add param to save lastsearch_values or not
3139 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3140 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3141 $add_save_lastsearch_values = 1;
3142 }
3143 if ($add_save_lastsearch_values) {
3144 $url .= '&save_lastsearch_values=1';
3145 }
3146 }
3147
3148 $linkstart = '<a href="'.$url.'"';
3149 $linkclose = "";
3150 if (empty($notooltip)) {
3151 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3152 $langs->load("users");
3153 $label = $langs->trans("ShowUser");
3154 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
3155 }
3156 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3157 $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
3158 } else {
3159 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
3160 }
3161
3162 $linkstart .= $linkclose.'>';
3163 $linkend = '</a>';
3164
3165 //if ($withpictoimg == -1) $result.='<div class="nowrap">';
3166 $result .= (($option == 'nolink') ? '' : $linkstart);
3167 if ($withpictoimg) {
3168 $paddafterimage = '';
3169 if (abs((int) $withpictoimg) == 1) {
3170 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3171 }
3172 // Only picto
3173 if ($withpictoimg > 0) {
3174 $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'"><div class="valignmiddle userphoto inline-block center marginrightonlyshort"'.($paddafterimage ? ' '.$paddafterimage : '').'>'.img_object('', 'user', 'class=""', 0, 0, $notooltip ? 0 : 1).'</div></span>';
3175 } else {
3176 // Picto must be a photo
3177 $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>';
3178 }
3179 $result .= $picto;
3180 }
3181 if ($withpictoimg > -2 && $withpictoimg != 2) {
3182 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3183 $result .= '<span class="nopadding usertext'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
3184 }
3185 if ($mode == 'login') {
3186 $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
3187 } else {
3188 $result .= dol_string_nohtmltag($this->getFullName($langs, 0, ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
3189 }
3190 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3191 $result .= '</span>';
3192 }
3193 }
3194 $result .= (($option == 'nolink') ? '' : $linkend);
3195 //if ($withpictoimg == -1) $result.='</div>';
3196
3197 $result .= $companylink;
3198
3199 global $action;
3200 $hookmanager->initHooks(array('userdao'));
3201 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
3202 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3203 if ($reshook > 0) {
3204 $result = $hookmanager->resPrint;
3205 } else {
3206 $result .= $hookmanager->resPrint;
3207 }
3208
3209 return $result;
3210 }
3211
3221 public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
3222 {
3223 global $langs, $user;
3224
3225 $result = '';
3226
3227 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3228 $linkend = '</a>';
3229
3230 //Check user's rights to see an other user
3231 if ((!$user->hasRight('user', 'user', 'lire') && $this->id != $user->id)) {
3232 $option = 'nolink';
3233 }
3234
3235 if ($option == 'xxx') {
3236 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3237 $linkend = '</a>';
3238 }
3239
3240 if ($option == 'nolink') {
3241 $linkstart = '';
3242 $linkend = '';
3243 }
3244
3245 $result .= $linkstart;
3246 if ($withpictoimg) {
3247 $paddafterimage = '';
3248 if (abs($withpictoimg) == 1) {
3249 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3250 }
3251 // Only picto
3252 if ($withpictoimg > 0) {
3253 $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3254 } else {
3255 // Picto must be a photo
3256 $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>';
3257 }
3258 $result .= $picto;
3259 }
3260 $result .= $this->login;
3261 $result .= $linkend;
3262
3263 return $result;
3264 }
3265
3272 public function getLibStatut($mode = 0)
3273 {
3274 return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3275 }
3276
3277 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3285 public function LibStatut($status, $mode = 0)
3286 {
3287 // phpcs:enable
3288 global $langs;
3289
3290 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3291 global $langs;
3292 //$langs->load("mymodule");
3293 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3294 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3295 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3296 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3297 }
3298
3299 $statusType = 'status5';
3300 if ($status == self::STATUS_ENABLED) {
3301 $statusType = 'status4';
3302 }
3303
3304 $label = $this->labelStatus[$status];
3305 $labelshort = $this->labelStatusShort[$status];
3306
3307 $now = dol_now();
3308 if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3309 $statusType = 'status3';
3310 $label .= ' ('.$langs->trans("UserNotYetValid").')';
3311 }
3312 if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3313 $statusType = 'status2';
3314 $label .= ' ('.$langs->trans("UserExpired").')';
3315 }
3316
3317 return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3318 }
3319
3320
3328 public function getKanbanView($option = '', $arraydata = null)
3329 {
3330 global $langs;
3331
3332 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3333
3334 $return = '<div class="box-flex-item box-flex-grow-zero">';
3335 $return .= '<div class="info-box info-box-sm">';
3336 $return .= '<span class="info-box-icon bg-infobox-action">';
3337
3338 $label = '';
3339 if (!empty($this->photo)) {
3340 //$label .= '<div class="photointooltip floatright">';
3341 $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
3342 //$label .= '</div>';
3343 //$label .= '<div style="clear: both;"></div>';
3344 $return .= $label;
3345 } else {
3346 $return .= img_picto('', $this->picto);
3347 }
3348
3349 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3350 $return .= '</span>';
3351 $return .= '<div class="info-box-content">';
3352 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3353 if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3354 $return .= img_picto($langs->trans("SuperAdministratorDesc"), 'redstar', 'class="valignmiddle paddingright paddingleft"');
3355 } elseif ($this->admin) {
3356 $return .= img_picto($langs->trans("AdministratorDesc"), 'star', 'class="valignmiddle paddingright paddingleft"');
3357 }
3358 $return .= '</span>';
3359 if ($selected >= 0) {
3360 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3361 }
3362 if (property_exists($this, 'label')) {
3363 $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3364 }
3365 if ($this->email) {
3366 $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3367 }
3368 if (method_exists($this, 'getLibStatut')) {
3369 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3370 }
3371 $return .= '</div>';
3372 $return .= '</div>';
3373 $return .= '</div>';
3374
3375 return $return;
3376 }
3377
3378
3379 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3380 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3390 public function _load_ldap_dn($info, $mode = 0)
3391 {
3392 // phpcs:enable
3393 global $conf;
3394 $dn = '';
3395 if ($mode == 0) {
3396 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')]."," . getDolGlobalString('LDAP_USER_DN');
3397 } elseif ($mode == 1) {
3398 $dn = getDolGlobalString('LDAP_USER_DN');
3399 } elseif ($mode == 2) {
3400 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')];
3401 }
3402 return $dn;
3403 }
3404
3405 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3406 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3412 public function _load_ldap_info()
3413 {
3414 // phpcs:enable
3415 global $conf, $langs;
3416
3417 $info = array();
3418
3419 $socialnetworks = getArrayOfSocialNetworks();
3420
3421 $keymodified = false;
3422
3423 // Object classes
3424 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_USER_OBJECT_CLASS'));
3425
3426 $this->fullname = $this->getFullName($langs);
3427
3428 // Possible LDAP KEY (constname => varname)
3429 $ldapkey = array(
3430 'LDAP_FIELD_FULLNAME' => 'fullname',
3431 'LDAP_FIELD_NAME' => 'lastname',
3432 'LDAP_FIELD_FIRSTNAME' => 'firstname',
3433 'LDAP_FIELD_LOGIN' => 'login',
3434 'LDAP_FIELD_LOGIN_SAMBA' => 'login',
3435 'LDAP_FIELD_PHONE' => 'office_phone',
3436 'LDAP_FIELD_MOBILE' => 'user_mobile',
3437 'LDAP_FIELD_FAX' => 'office_fax',
3438 'LDAP_FIELD_MAIL' => 'email',
3439 'LDAP_FIELD_SID' => 'ldap_sid',
3440 );
3441
3442 // Champs
3443 foreach ($ldapkey as $constname => $varname) {
3444 if (!empty($this->$varname) && getDolGlobalString($constname)) {
3445 $info[getDolGlobalString($constname)] = $this->$varname;
3446
3447 // Check if it is the LDAP key and if its value has been changed
3448 if (getDolGlobalString('LDAP_KEY_USERS') && $conf->global->LDAP_KEY_USERS == getDolGlobalString($constname)) {
3449 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->$varname != $this->oldcopy->$varname) {
3450 $keymodified = true; // For check if LDAP key has been modified
3451 }
3452 }
3453 }
3454 }
3455 foreach ($socialnetworks as $key => $value) {
3456 if (!empty($this->socialnetworks[$value['label']]) && getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))) {
3457 $info[getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3458 }
3459 }
3460 if ($this->address && getDolGlobalString('LDAP_FIELD_ADDRESS')) {
3461 $info[getDolGlobalString('LDAP_FIELD_ADDRESS')] = $this->address;
3462 }
3463 if ($this->zip && getDolGlobalString('LDAP_FIELD_ZIP')) {
3464 $info[getDolGlobalString('LDAP_FIELD_ZIP')] = $this->zip;
3465 }
3466 if ($this->town && getDolGlobalString('LDAP_FIELD_TOWN')) {
3467 $info[getDolGlobalString('LDAP_FIELD_TOWN')] = $this->town;
3468 }
3469 if ($this->note_public && getDolGlobalString('LDAP_FIELD_DESCRIPTION')) {
3470 $info[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_public, 2);
3471 }
3472 if ($this->socid > 0) {
3473 $soc = new Societe($this->db);
3474 $soc->fetch($this->socid);
3475
3476 $info[getDolGlobalString('LDAP_FIELD_COMPANY')] = $soc->name;
3477 if ($soc->client == 1) {
3478 $info["businessCategory"] = "Customers";
3479 }
3480 if ($soc->client == 2) {
3481 $info["businessCategory"] = "Prospects";
3482 }
3483 if ($soc->fournisseur == 1) {
3484 $info["businessCategory"] = "Suppliers";
3485 }
3486 }
3487
3488 // When password is modified
3489 if (!empty($this->pass)) {
3490 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3491 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass; // this->pass = unencrypted password
3492 }
3493 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3494 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3495 }
3496 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3497 // Set LDAP password if possible
3498 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3499 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
3500 // Just for the default MD5 !
3501 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) {
3502 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3503 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3504 }
3505 }
3506 } elseif (!empty($this->pass_indatabase)) {
3507 // Use $this->pass_indatabase value if exists
3508 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3509 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = unencrypted password
3510 }
3511 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3512 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3513 }
3514 }
3515 }
3516
3517 if (getDolGlobalString('LDAP_SERVER_TYPE') == 'egroupware') {
3518 $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3519
3520 $info['uidnumber'] = $this->id;
3521
3522 $info['phpgwTz'] = 0;
3523 $info['phpgwMailType'] = 'INTERNET';
3524 $info['phpgwMailHomeType'] = 'INTERNET';
3525
3526 $info["phpgwContactTypeId"] = 'n';
3527 $info["phpgwContactCatId"] = 0;
3528 $info["phpgwContactAccess"] = "public";
3529
3530 /*
3531 if (dol_strlen($this->egroupware_id) == 0) {
3532 $this->egroupware_id = 1;
3533 }
3534 $info["phpgwContactOwner"] = $this->egroupware_id;
3535 */
3536 $info["phpgwContactOwner"] = 1;
3537
3538 if ($this->email) {
3539 $info["rfc822Mailbox"] = $this->email;
3540 }
3541 if ($this->user_mobile) {
3542 $info["phpgwCellTelephoneNumber"] = $this->user_mobile;
3543 }
3544 }
3545
3546 if (getDolGlobalString('LDAP_FIELD_USERID')) {
3547 $info[getDolGlobalString('LDAP_FIELD_USERID')] = $this->id;
3548 }
3549 if (getDolGlobalString('LDAP_FIELD_GROUPID')) {
3550 $usergroup = new UserGroup($this->db);
3551 $groupslist = $usergroup->listGroupsForUser($this->id);
3552 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = '65534';
3553 if (!empty($groupslist)) {
3554 foreach ($groupslist as $groupforuser) {
3555 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = $groupforuser->id; //Select first group in list
3556 break;
3557 }
3558 }
3559 }
3560 if (getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY') && getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')) {
3561 $info[getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY')] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->login";
3562 }
3563
3564 return $info;
3565 }
3566
3567
3575 public function initAsSpecimen()
3576 {
3577 global $user, $langs;
3578
3579 $now = dol_now();
3580
3581 // Initialise parameters
3582 $this->id = 0;
3583 $this->ref = 'SPECIMEN';
3584 $this->specimen = 1;
3585
3586 $this->lastname = 'DOLIBARR';
3587 $this->firstname = 'SPECIMEN';
3588 $this->gender = 'man';
3589 $this->note_public = 'This is a note public';
3590 $this->note_private = 'This is a note private';
3591 $this->email = 'email@specimen.com';
3592 $this->personal_email = 'personalemail@specimen.com';
3593 $this->socialnetworks = array(
3594 'skype' => 'skypepseudo',
3595 'twitter' => 'twitterpseudo',
3596 'facebook' => 'facebookpseudo',
3597 'linkedin' => 'linkedinpseudo',
3598 );
3599 $this->office_phone = '0999999999';
3600 $this->office_fax = '0999999998';
3601 $this->user_mobile = '0999999997';
3602 $this->personal_mobile = '0999999996';
3603 $this->admin = 0;
3604 $this->login = 'dolibspec';
3605 $this->pass = 'dolibSpec+@123';
3606 //$this->pass_indatabase='dolibspec'; Set after a fetch
3607 //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3608 $this->datec = $now;
3609 $this->datem = $now;
3610
3611 $this->datelastlogin = $now;
3612 $this->iplastlogin = '127.0.0.1';
3613 $this->datepreviouslogin = $now;
3614 $this->ippreviouslogin = '127.0.0.1';
3615 $this->statut = 1; // deprecated
3616 $this->status = 1;
3617
3618 $this->entity = 1;
3619
3620 return 1;
3621 }
3622
3629 public function info($id)
3630 {
3631 $sql = "SELECT u.rowid, u.login as ref, u.datec,";
3632 $sql .= " u.tms as date_modification, u.entity";
3633 $sql .= " FROM ".$this->db->prefix()."user as u";
3634 $sql .= " WHERE u.rowid = ".((int) $id);
3635
3636 $result = $this->db->query($sql);
3637 if ($result) {
3638 if ($this->db->num_rows($result)) {
3639 $obj = $this->db->fetch_object($result);
3640
3641 $this->id = $obj->rowid;
3642
3643 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3644 $this->date_creation = $this->db->jdate($obj->datec);
3645 $this->date_modification = $this->db->jdate($obj->date_modification);
3646 $this->entity = $obj->entity;
3647 }
3648
3649 $this->db->free($result);
3650 } else {
3651 dol_print_error($this->db);
3652 }
3653 }
3654
3655
3661 public function getNbOfEMailings()
3662 {
3663 $sql = "SELECT count(mc.email) as nb";
3664 $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3665 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3666 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
3667
3668 $resql = $this->db->query($sql);
3669 if ($resql) {
3670 $obj = $this->db->fetch_object($resql);
3671 $nb = $obj->nb;
3672
3673 $this->db->free($resql);
3674 return $nb;
3675 } else {
3676 $this->error = $this->db->error();
3677 return -1;
3678 }
3679 }
3680
3689 public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3690 {
3691 global $conf;
3692
3693 $sql = "SELECT count(rowid) as nb";
3694 $sql .= " FROM ".$this->db->prefix()."user";
3695 if ($option == 'superadmin') {
3696 $sql .= " WHERE entity = 0";
3697 } else {
3698 $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3699 if ($limitTo == 'active') {
3700 $sql .= " AND statut = 1";
3701 }
3702 }
3703 if ($admin >= 0) {
3704 $sql .= " AND admin = ".(int) $admin;
3705 }
3706
3707 $resql = $this->db->query($sql);
3708 if ($resql) {
3709 $obj = $this->db->fetch_object($resql);
3710 $nb = (int) $obj->nb;
3711
3712 $this->db->free($resql);
3713 return $nb;
3714 } else {
3715 $this->error = $this->db->lasterror();
3716 return -1;
3717 }
3718 }
3719
3720 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3727 public function update_ldap2dolibarr(&$ldapuser)
3728 {
3729 // phpcs:enable
3730 // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3731 global $user, $conf;
3732
3733 $socialnetworks = getArrayOfSocialNetworks();
3734
3735 $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3736 $this->firstname = $ldapuser->$tmpvar;
3737 $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3738 $this->lastname = $ldapuser->$tmpvar;
3739 $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3740 $this->login = $ldapuser->$tmpvar;
3741 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3742 $this->pass = $ldapuser->$tmpvar;
3743 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3744 $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3745
3746 $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3747 $this->office_phone = $ldapuser->$tmpvar;
3748 $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3749 $this->user_mobile = $ldapuser->$tmpvar;
3750 $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3751 $this->office_fax = $ldapuser->$tmpvar;
3752 $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3753 $this->email = $ldapuser->$tmpvar;
3754 foreach ($socialnetworks as $key => $value) {
3755 $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3756 $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3757 }
3758 $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3759 $this->ldap_sid = $ldapuser->$tmpvar;
3760
3761 $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3762 $this->job = $ldapuser->$tmpvar;
3763 $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3764 $this->note_public = $ldapuser->$tmpvar;
3765
3766 $result = $this->update($user);
3767
3768 dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3769
3770 return $result;
3771 }
3772
3773
3774 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3781 public function get_children()
3782 {
3783 // phpcs:enable
3784 $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3785 $sql .= " WHERE fk_user = ".((int) $this->id);
3786
3787 dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3788 $res = $this->db->query($sql);
3789 if ($res) {
3790 $users = array();
3791 while ($rec = $this->db->fetch_array($res)) {
3792 $user = new User($this->db);
3793 $user->fetch($rec['rowid']);
3794 $users[] = $user;
3795 }
3796 return $users;
3797 } else {
3798 dol_print_error($this->db);
3799 return -1;
3800 }
3801 }
3802
3803
3809 private function loadParentOf()
3810 {
3811 global $conf;
3812
3813 $this->parentof = array();
3814
3815 // Load array[child]=parent
3816 $sql = "SELECT fk_user as id_parent, rowid as id_son";
3817 $sql .= " FROM ".$this->db->prefix()."user";
3818 $sql .= " WHERE fk_user <> 0";
3819 $sql .= " AND entity IN (".getEntity('user').")";
3820
3821 dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3822 $resql = $this->db->query($sql);
3823 if ($resql) {
3824 while ($obj = $this->db->fetch_object($resql)) {
3825 $this->parentof[$obj->id_son] = $obj->id_parent;
3826 }
3827 return 1;
3828 } else {
3829 dol_print_error($this->db);
3830 return -1;
3831 }
3832 }
3833
3834 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3848 public function get_full_tree($deleteafterid = 0, $filter = '')
3849 {
3850 // phpcs:enable
3851 global $conf, $user;
3852 global $hookmanager;
3853
3854 // Actions hooked (by external module)
3855 $hookmanager->initHooks(array('userdao'));
3856
3857 $this->users = array();
3858
3859 // Init this->parentof that is array(id_son=>id_parent, ...)
3860 $this->loadParentOf();
3861
3862 // Init $this->users array
3863 $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
3864 $sql .= " FROM ".$this->db->prefix()."user as u";
3865 // Add fields from hooks
3866 $parameters = array();
3867 $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3868 if ($reshook > 0) {
3869 $sql .= $hookmanager->resPrint;
3870 } else {
3871 $sql .= " WHERE u.entity IN (".getEntity('user').")";
3872 }
3873 if ($filter) {
3874 $sql .= " AND ".$filter;
3875 }
3876
3877 dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3878 $resql = $this->db->query($sql);
3879 if ($resql) {
3880 $i = 0;
3881 while ($obj = $this->db->fetch_object($resql)) {
3882 $this->users[$obj->rowid]['rowid'] = $obj->rowid;
3883 $this->users[$obj->rowid]['id'] = $obj->rowid;
3884 $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
3885 $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
3886 $this->users[$obj->rowid]['firstname'] = $obj->firstname;
3887 $this->users[$obj->rowid]['lastname'] = $obj->lastname;
3888 $this->users[$obj->rowid]['login'] = $obj->login;
3889 $this->users[$obj->rowid]['statut'] = $obj->statut;
3890 $this->users[$obj->rowid]['entity'] = $obj->entity;
3891 $this->users[$obj->rowid]['email'] = $obj->email;
3892 $this->users[$obj->rowid]['gender'] = $obj->gender;
3893 $this->users[$obj->rowid]['admin'] = $obj->admin;
3894 $this->users[$obj->rowid]['photo'] = $obj->photo;
3895 // fields are filled with build_path_from_id_user
3896 $this->users[$obj->rowid]['fullpath'] = '';
3897 $this->users[$obj->rowid]['fullname'] = '';
3898 $this->users[$obj->rowid]['level'] = 0;
3899 $i++;
3900 }
3901 } else {
3902 dol_print_error($this->db);
3903 return -1;
3904 }
3905
3906 // We add the fullpath property to each element of the first level (no parent exists)
3907 dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3908 foreach ($this->users as $key => $val) {
3909 $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3910 if ($result < 0) {
3911 $this->error = 'ErrorLoopInHierarchy';
3912 return -1;
3913 }
3914 }
3915
3916 // Exclude leaf including $deleteafterid from tree
3917 if ($deleteafterid) {
3918 //print "Look to discard user ".$deleteafterid."\n";
3919 $keyfilter1 = '^'.$deleteafterid.'$';
3920 $keyfilter2 = '_'.$deleteafterid.'$';
3921 $keyfilter3 = '^'.$deleteafterid.'_';
3922 $keyfilter4 = '_'.$deleteafterid.'_';
3923 foreach (array_keys($this->users) as $key) {
3924 $fullpath = (string) $this->users[$key]['fullpath'];
3925 if (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
3926 || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath)) {
3927 unset($this->users[$key]);
3928 }
3929 }
3930 }
3931
3932 dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
3933 $this->users = dol_sort_array($this->users, 'fullname', 'asc', 1, 0, 1);
3934
3935 //var_dump($this->users);
3936
3937 return $this->users;
3938 }
3939
3948 public function getAllChildIds($addcurrentuser = 0)
3949 {
3950 $childids = array();
3951
3952 if (isset($this->cache_childids[$this->id])) {
3953 $childids = $this->cache_childids[$this->id];
3954 } else {
3955 // Init this->users
3956 $this->get_full_tree();
3957
3958 $idtoscan = $this->id;
3959
3960 dol_syslog("Build childid for id = ".$idtoscan);
3961 foreach ($this->users as $id => $val) {
3962 //var_dump($val['fullpath']);
3963 if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
3964 $childids[$val['id']] = $val['id'];
3965 }
3966 }
3967 }
3968 $this->cache_childids[$this->id] = $childids;
3969
3970 if ($addcurrentuser) {
3971 $childids[$this->id] = $this->id;
3972 }
3973
3974 return $childids;
3975 }
3976
3977 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3986 public function build_path_from_id_user($id_user, $protection = 0)
3987 {
3988 // phpcs:enable
3989 //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
3990
3991 if (!empty($this->users[$id_user]['fullpath'])) {
3992 // Already defined
3993 dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
3994 return 0;
3995 }
3996
3997 // Define fullpath and fullname
3998 $this->users[$id_user]['fullpath'] = '_'.$id_user;
3999 $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
4000 $i = 0;
4001 $cursor_user = $id_user;
4002
4003 $useridfound = array($id_user);
4004 while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) { // @phan-suppress-current-line PhanTypeMismatchProperty
4005 if (in_array($this->parentof[$cursor_user], $useridfound)) {
4006 dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
4007 return -1; // Should not happen. Protection against looping hierarchy
4008 }
4009 $useridfound[] = $this->parentof[$cursor_user];
4010 $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
4011 $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
4012 $i++;
4013 $cursor_user = $this->parentof[$cursor_user];
4014 }
4015
4016 // We count number of _ to have level
4017 $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
4018
4019 return 1;
4020 }
4021
4030 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4031 {
4032 $tables = array(
4033 'user',
4034 );
4035
4036 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4037 }
4038
4039
4045 public function loadStateBoard()
4046 {
4047 global $conf;
4048
4049 $this->nb = array();
4050
4051 $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
4052 $sql .= " FROM ".$this->db->prefix()."user as u";
4053 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4054 $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
4055 $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
4056 $sql .= " AND ug.fk_user = u.rowid";
4057 } else {
4058 $sql .= " WHERE u.entity IN (".getEntity('user').")";
4059 }
4060 $sql .= " AND u.statut > 0";
4061 //$sql.= " AND employee != 0";
4062
4063 $resql = $this->db->query($sql);
4064 if ($resql) {
4065 while ($obj = $this->db->fetch_object($resql)) {
4066 $this->nb["users"] = $obj->nb;
4067 }
4068 $this->db->free($resql);
4069 return 1;
4070 } else {
4071 dol_print_error($this->db);
4072 $this->error = $this->db->error();
4073 return -1;
4074 }
4075 }
4076
4088 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4089 {
4090 global $conf, $user, $langs;
4091
4092 $langs->load("user");
4093
4094 // Set the '$modele' to the name of the document template (model) to use
4095 if (!dol_strlen($modele)) {
4096 if (getDolGlobalString('USER_ADDON_PDF')) {
4097 $modele = getDolGlobalString('USER_ADDON_PDF');
4098 } else {
4099 $modele = 'bluesky';
4100 }
4101 }
4102
4103 $modelpath = "core/modules/user/doc/";
4104
4105 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4106 }
4107
4108 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4116 public function user_get_property($rowid, $mode)
4117 {
4118 // phpcs:enable
4119 $user_property = '';
4120
4121 if (empty($rowid)) {
4122 return '';
4123 }
4124
4125 $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
4126 $sql .= " FROM ".$this->db->prefix()."user";
4127 $sql .= " WHERE rowid = ".((int) $rowid);
4128
4129 $resql = $this->db->query($sql);
4130 if ($resql) {
4131 $nump = $this->db->num_rows($resql);
4132
4133 if ($nump) {
4134 $obj = $this->db->fetch_object($resql);
4135
4136 if ($mode == 'email') {
4137 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
4138 } elseif ($mode == 'mobile') {
4139 $user_property = $obj->user_mobile;
4140 } elseif ($mode == 'name') {
4141 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname);
4142 }
4143 }
4144 return $user_property;
4145 } else {
4146 dol_print_error($this->db);
4147 }
4148
4149 return '';
4150 }
4151
4159 public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
4160 {
4161 global $dolibarr_main_url_root;
4162 global $conf;
4163
4164 $encodedsecurekey = dol_hash($conf->file->instance_unique_id.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
4165 if (isModEnabled('multicompany')) {
4166 $entity_qr = '&entity='.((int) $conf->entity);
4167 } else {
4168 $entity_qr = '';
4169 }
4170 // Define $urlwithroot
4171 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
4172 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
4173 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
4174
4175 if ($typeofurl == 'internal') {
4176 $urlwithroot = DOL_URL_ROOT;
4177 }
4178
4179 return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
4180 }
4181
4195 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND', $entityfilter = false)
4196 {
4197 global $conf, $user;
4198
4199 $sql = "SELECT t.rowid";
4200 $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
4201
4202 if ($entityfilter) {
4203 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4204 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
4205 $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
4206 } else {
4207 $sql .= ",".$this->db->prefix()."usergroup_user as ug";
4208 $sql .= " WHERE ((ug.fk_user = t.rowid";
4209 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
4210 $sql .= " OR t.entity = 0)"; // Show always superadmin
4211 }
4212 } else {
4213 $sql .= " WHERE t.entity IN (".getEntity('user').")";
4214 }
4215 } else {
4216 $sql .= " WHERE 1 = 1";
4217 }
4218
4219 // Manage filter
4220 $errormessage = '';
4221 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
4222 if ($errormessage) {
4223 $this->errors[] = $errormessage;
4224 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
4225 return -1;
4226 }
4227
4228 $sql .= $this->db->order($sortfield, $sortorder);
4229 if ($limit) {
4230 $sql .= $this->db->plimit($limit + 1, $offset);
4231 }
4232
4233 dol_syslog(__METHOD__, LOG_DEBUG);
4234
4235 $resql = $this->db->query($sql);
4236 if ($resql) {
4237 $this->users = array();
4238 $num = $this->db->num_rows($resql);
4239 if ($num) {
4240 while ($obj = $this->db->fetch_object($resql)) {
4241 $line = new self($this->db);
4242 $result = $line->fetch($obj->rowid);
4243 if ($result > 0 && !empty($line->id)) {
4244 $this->users[$obj->rowid] = clone $line;
4245 }
4246 }
4247 $this->db->free($resql);
4248 }
4249 return $num;
4250 } else {
4251 $this->errors[] = $this->db->lasterror();
4252 return -1;
4253 }
4254 }
4255
4263 private $findUserIdByEmailCache;
4264
4275 public function findUserIdByEmail($email)
4276 {
4277 if (isset($this->findUserIdByEmailCache[$email])) {
4278 return $this->findUserIdByEmailCache[$email];
4279 }
4280
4281 $this->findUserIdByEmailCache[$email] = -1;
4282
4283 $sql = 'SELECT rowid';
4284 $sql .= ' FROM '.$this->db->prefix().'user';
4285 if (getDolGlobalString('AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR')) {
4286 $sql .= " WHERE email LIKE '%".$this->db->escape($this->db->escapeforlike($email))."%'";
4287 } else {
4288 $sql .= " WHERE email = '".$this->db->escape($email)."'";
4289 }
4290 $sql .= ' LIMIT 1';
4291
4292 $resql = $this->db->query($sql);
4293 if (!$resql) {
4294 return -1;
4295 }
4296
4297 $obj = $this->db->fetch_object($resql);
4298 if (!$obj) {
4299 return -1;
4300 }
4301
4302 $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4303
4304 return $this->findUserIdByEmailCache[$email];
4305 }
4306}
$object ref
Definition info.php:79
Class to manage members of a foundation.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage contact/addresses.
Class for MyObject.
Class to manage Dolibarr database access.
Class to manage warehouses.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage user groups.
Class to manage Dolibarr users.
fetch($id=0, $login='', $sid='', $loadpersonalconf=0, $entity=-1, $email='', $fk_socpeople=0, $use_email_oauth2=0)
Load a user from database with its id or ref (login).
SetInGroup($group, $entity, $notrigger=0)
Add user into a group.
LibStatut($status, $mode=0)
Return the label of a status of user (active, inactive)
loadRights($moduletag='', $forcereload=0)
Load permissions granted to a user->id into object user->rights.
get_children()
Return and array with all instantiated first level children users of current user.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
loadStateBoard()
Load metrics this->nb for dashboard.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
info($id)
Load info of user object.
create_from_contact($contact, $login='', $password='')
Create a user from a contact object.
setstatus($status)
Change status of a user.
get_full_tree($deleteafterid=0, $filter='')
Build the hierarchy/tree of users into an array.
_load_ldap_info()
Initialize the info array (array of LDAP values) that will be used to call LDAP functions.
delrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0)
Remove a right to the user.
update_last_login_date()
Update the user's last login date in the database.
__construct($db)
Constructor of the class.
RemoveFromGroup($group, $entity, $notrigger=0)
Remove a user from a group.
isNotIntoValidityDateRange()
Return a link with photo Use this->id,this->photo.
getNbOfUsers($limitTo, $option='', $admin=-1)
Return number of existing users.
set_default_rights()
Assign rights by default.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND', $entityfilter=false)
Load all objects into $this->users.
getOnlineVirtualCardUrl($mode='', $typeofurl='external')
Return string with full Url to virtual card.
update($user, $notrigger=0, $nosyncmember=0, $nosyncmemberpass=0, $nosynccontact=0)
Update a user into database (and also password if this->pass is defined)
getLoginUrl($withpictoimg=0, $option='', $notooltip=0, $morecss='')
Return clickable link of login (optionally with picto)
setCategories($categories)
Sets object to supplied categories.
loadParentOf()
Load this->parentof that is array(id_son=>id_parent, ...)
fetch_clicktodial()
Read clicktodial information for user.
build_path_from_id_user($id_user, $protection=0)
For user id_user and its children available in this->users, define property fullpath and fullname.
error()
Renvoie la derniere erreur fonctionnelle de manipulation de l'objet.
getAllChildIds($addcurrentuser=0)
Return list of all child user ids in hierarchy (all sublevels).
initAsSpecimen()
Initialise an instance with random values.
setPassword($user, $password='', $changelater=0, $notrigger=0, $nosyncmember=0, $passwordalreadycrypted=0, $flagdelsessionsbefore=1)
Change password of a user.
getNomUrl($withpictoimg=0, $option='', $infologin=0, $notooltip=0, $maxlen=24, $hidethirdpartylogo=0, $mode='', $morecss='', $save_lastsearch_value=-1)
Return a HTML link to the user card (with optionally the picto) Use this->id,this->lastname,...
clearrights()
Clear all permissions array of user.
update_clicktodial()
Update clicktodial info.
getLibStatut($mode=0)
Return the label of the status of user (active, inactive)
create_from_member($member, $login='')
Create a user into database from a member object.
loadPersonalConf()
Load const values from database table user_param and set it into user->conf->XXX.
_load_ldap_dn($info, $mode=0)
Retourne chaine DN complete dans l'annuaire LDAP pour l'objet.
loadDefaultValues()
Load default values from database table into property ->default_values.
getPhotoUrl($width, $height, $cssclass='', $imagesize='')
Return a link with photo Use this->id,this->photo.
update_ldap2dolibarr(&$ldapuser)
Update user using data from the LDAP.
getrights($moduletag='', $forcereload=0)
Load permissions granted to a user->id into object user->rights TODO Remove this method.
user_get_property($rowid, $mode)
Return property of user from its id.
send_password($user, $password='', $changelater=0)
Send a new password (or instructions to reset it) by email.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (optionally with picto)
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
addrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0)
Add a right to the user.
create($user, $notrigger=0)
Create a user into database.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
findUserIdByEmail($email)
Find a user by the given e-mail and return it's user id when found.
getTooltipContentArray($params)
getTooltipContentArray
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:162
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:656
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
Definition date.lib.php:642
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
getArrayOfSocialNetworks()
Get array of social network dictionary.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
getUserRemoteIP()
Return the IP of remote user.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
div refaddress div address
conf($dolibarr_main_document_root)
Load conf file (file must exists)
Definition inc.php:420
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dol_verifyHash($chain, $hash, $type='0')
Compute a hash and compare it to the given one For backward compatibility reasons,...
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dolGetLdapPasswordHash($password, $type='md5')
Returns a specific ldap hash of a password.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.