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