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