dolibarr 24.0.2
user.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (c) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
4 * Copyright (c) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
7 * Copyright (C) 2005-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-2026 Frédéric France <frederic.france@free.fr>
16 * Copyright (C) 2019 Abbes Bahfir <dolipar@dolipar.org>
17 * Copyright (C) 2024-2026 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 $pass;
196
200 public $pass_crypted;
201
205 public $pass_indatabase;
206
210 public $pass_indatabase_crypted;
211
215 public $pass_temp;
216
220 public $force_pass_change = 0;
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 $datelastpassvalidation;
299 public $datelastlogin;
303 public $datepreviouslogin;
307 public $flagdelsessionsbefore;
311 public $iplastlogin;
315 public $ippreviouslogin;
319 public $datestartvalidity;
323 public $dateendvalidity;
324
328 public $photo;
329
333 public $lang;
334
338 public $rights;
339
343 public $all_permissions_are_loaded;
344
348 public $nb_rights;
349
353 public $user_group_list;
354
358 private $_tab_loaded = array();
359
363 public $conf;
364
368 public $default_values; // To store default values for user. Loaded by loadDefaultValues().
369
373 public $lastsearch_values_tmp; // To store current search criteria for user
377 public $lastsearch_values; // To store last saved search criteria for user
378
382 public $users = array();
386 public $parentof; // To store an array of all parents for all ids.
390 private $cache_childids; // Cache array of already loaded children
391
396 public $accountancy_code_user_general; // Accountancy code in prevision of the complete accountancy module
397
401 public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
402
406 public $thm; // Average cost of employee - Used for valuation of time spent
410 public $tjm; // Average cost of employee
411
415 public $salary; // Monthly salary - Denormalized value from llx_user_employment
419 public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment
423 public $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment
424
428 public $color;
429
433 public $dateemployment; // Define date of employment by company
437 public $dateemploymentend; // Define date of employment end by company
438
442 public $default_c_exp_tax_cat;
443
447 public $ref_employee;
448
452 public $national_registration_number;
453
457 public $default_range;
458
462 public $fk_warehouse;
463
467 public $fk_establishment;
468
472 public $label_establishment;
473
478 public $usergroup_entity;
479
480 public $fields = array(
481 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
482 'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 20, 'searchall' => 1),
483 'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1),
484 'ref_employee' => array('type' => 'varchar(50)', 'label' => 'RefEmployee', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 30, 'searchall' => 1),
485 'national_registration_number' => array('type' => 'varchar(50)', 'label' => 'NationalRegistrationNumber', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 40, 'searchall' => 1)
486 );
487
488 const STATUS_DISABLED = 0;
489 const STATUS_ENABLED = 1;
490
496 public function __construct($db)
497 {
498 $this->db = $db;
499
500 $this->ismultientitymanaged = 1;
501 $this->isextrafieldmanaged = 1;
502 // User preference
503 $this->clicktodial_loaded = 0;
504
505 // For cache usage
506 $this->all_permissions_are_loaded = 0;
507 $this->nb_rights = 0;
508
509 // Force some default values
510 $this->admin = 0;
511 $this->employee = 1;
512
513 $this->conf = new stdClass();
514 $this->rights = new stdClass();
515 $this->rights->user = new stdClass();
516 $this->rights->user->user = new stdClass();
517 $this->rights->user->self = new stdClass();
518 $this->rights->user->user_advance = new stdClass();
519 $this->rights->user->self_advance = new stdClass();
520 $this->rights->user->group_advance = new stdClass();
521 }
522
537 public function fetch($id = 0, $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1, $email = '', $fk_socpeople = 0, $use_email_oauth2 = 0)
538 {
539 global $conf, $user;
540
541 // Clean parameters
542 $login = trim($login);
543
544 // Get user
545 $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.civility as civility_code, u.birth, u.job,";
546 $sql .= " u.email, u.email_oauth2, u.personal_email,";
547 $sql .= " u.socialnetworks,";
548 $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile, u.personal_mobile,";
549 $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
550 $sql .= " u.admin, u.login, u.note_private, u.note_public,";
551 $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.force_pass_change, u.api_key,";
552 $sql .= " u.fk_soc, u.fk_socpeople, u.fk_member, u.fk_user, u.ldap_sid, u.fk_user_expense_validator, u.fk_user_holiday_validator,";
553 $sql .= " fk_user_creat as user_creation_id, fk_user_modif as user_modification_id,";
554 $sql .= " u.statut as status, u.lang, u.entity,";
555 $sql .= " u.datec as datec,";
556 $sql .= " GREATEST(u.tms, COALESCE(uef.tms, 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()."user_extrafields as uef ON uef.fk_object = u.rowid";
586 $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as c ON u.fk_country = c.rowid";
587 $sql .= " LEFT JOIN ".$this->db->prefix()."c_departements as d ON u.fk_state = d.rowid";
588 $sql .= " LEFT JOIN ".$this->db->prefix()."establishment as s ON u.fk_establishment = s.rowid";
589
590 if ($id > 0) {
591 $sql .= " WHERE u.rowid = ".((int) $id);
592 } else {
593 if ($entity < 0) {
594 if ((! isModEnabled('multicompany') || ! getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) && (! empty($user->entity))) {
595 $sql .= " WHERE u.entity IN (0, " . ((int) $conf->entity) . ")";
596 } else {
597 $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
598 }
599 } else {
600 // The fetch was forced on an entity
601 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
602 $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
603 } else {
604 if ($entity != '' && $entity == 0) { // If $entity = 0
605 $sql .= " WHERE u.entity = 0";
606 } else { // if $entity is -1 or > 0
607 $sql .= " WHERE u.entity IN (0, " . ((int) ($entity > 0 ? ((int) $entity) : ((int) $conf->entity))) . ")";
608 }
609 }
610 }
611 }
612
613 if ($sid) {
614 // permet une recherche du user par son SID ActiveDirectory ou Samba
615 $sql .= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."')";
616 } elseif ($login) {
617 $sql .= " AND u.login = '".$this->db->escape($login)."'";
618 } elseif ($email) {
619 $sql .= " AND (u.email = '".$this->db->escape($email)."'";
620 if ($use_email_oauth2) {
621 $sql .= " OR u.email_oauth2 = '".$this->db->escape($email)."'";
622 }
623 $sql .= ")";
624 } elseif ($fk_socpeople > 0) {
625 $sql .= " AND u.fk_socpeople = ".((int) $fk_socpeople);
626 }
627
628 $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
629
630 if ($sid) {
631 // permet une recherche du user par son SID ActiveDirectory ou Samba
632 $sql .= ' '.$this->db->plimit(1);
633 }
634
635 $resql = $this->db->query($sql);
636 if ($resql) {
637 $num = $this->db->num_rows($resql);
638 if ($num > 1) {
639 $this->error = "USERDUPLICATEFOUND";
640 dol_syslog(get_class($this)."::fetch more than 1 user found", LOG_WARNING);
641
642 $this->db->free($resql);
643 return 0;
644 }
645
646 $obj = $this->db->fetch_object($resql);
647 if ($obj) {
648 $this->id = $obj->rowid;
649 $this->ref = $obj->rowid;
650
651 $this->ref_ext = $obj->ref_ext;
652
653 $this->ldap_sid = $obj->ldap_sid;
654 $this->civility_code = $obj->civility_code;
655 $this->lastname = $obj->lastname;
656 $this->firstname = $obj->firstname;
657 $this->ref_employee = $obj->ref_employee;
658 $this->national_registration_number = $obj->national_registration_number;
659
660 $this->employee = $obj->employee;
661
662 $this->login = $obj->login;
663 $this->gender = $obj->gender;
664 $this->birth = $this->db->jdate($obj->birth);
665 $this->pass_indatabase = $obj->pass;
666 $this->pass_indatabase_crypted = $obj->pass_crypted;
667 $this->pass = $obj->pass;
668 $this->pass_temp = $obj->pass_temp;
669
670 $this->force_pass_change = $obj->force_pass_change;
671 $this->datelastpassvalidation = $this->db->jdate($obj->datelastpassvalidation);
672
673 $this->api_key = dolDecrypt($obj->api_key);
674
675 $this->address = $obj->address;
676 $this->zip = $obj->zip;
677 $this->town = $obj->town;
678
679 $this->country_id = $obj->country_id;
680 $this->country_code = $obj->country_id ? $obj->country_code : '';
681 //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
682
683 $this->state_id = $obj->state_id;
684 $this->state_code = $obj->state_code;
685 $this->state = ($obj->state != '-' ? $obj->state : '');
686
687 $this->office_phone = $obj->office_phone;
688 $this->office_fax = $obj->office_fax;
689 $this->user_mobile = $obj->user_mobile;
690 $this->personal_mobile = $obj->personal_mobile;
691 $this->email = $obj->email;
692 $this->email_oauth2 = $obj->email_oauth2;
693 $this->personal_email = $obj->personal_email;
694 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
695 $this->user_creation_id = $obj->user_creation_id;
696 $this->user_modification_id = $obj->user_modification_id;
697
698 $this->job = $obj->job;
699 $this->signature = $obj->signature;
700 $this->admin = $obj->admin;
701 $this->note_public = $obj->note_public;
702 $this->note_private = $obj->note_private;
703
704 $this->statut = $obj->status; // deprecated
705 $this->status = $obj->status;
706
707 $this->photo = $obj->photo;
708 $this->openid = $obj->openid;
709 $this->lang = $obj->lang;
710 $this->entity = $obj->entity;
711
712 $this->accountancy_code_user_general = $obj->accountancy_code_user_general;
713 $this->accountancy_code = $obj->accountancy_code;
714
715 $this->thm = $obj->thm;
716 $this->tjm = $obj->tjm;
717 $this->salary = $obj->salary;
718 $this->salaryextra = $obj->salaryextra;
719 $this->weeklyhours = $obj->weeklyhours;
720 $this->color = $obj->color;
721 $this->dateemployment = $this->db->jdate($obj->dateemployment);
722 $this->dateemploymentend = $this->db->jdate($obj->dateemploymentend);
723
724 $this->datec = $this->db->jdate($obj->datec);
725 $this->datem = $this->db->jdate($obj->datem);
726 $this->datelastlogin = $this->db->jdate($obj->datel);
727 $this->datepreviouslogin = $this->db->jdate($obj->datep);
728 $this->flagdelsessionsbefore = $this->db->jdate($obj->flagdelsessionsbefore, 'gmt');
729 $this->iplastlogin = $obj->iplastlogin;
730 $this->ippreviouslogin = $obj->ippreviouslogin;
731 $this->datestartvalidity = $this->db->jdate($obj->datestartvalidity);
732 $this->dateendvalidity = $this->db->jdate($obj->dateendvalidity);
733
734 $this->socid = $obj->fk_soc;
735 $this->contact_id = $obj->fk_socpeople;
736 $this->fk_member = $obj->fk_member;
737 $this->fk_user = $obj->fk_user;
738 $this->fk_user_expense_validator = $obj->fk_user_expense_validator;
739 $this->fk_user_holiday_validator = $obj->fk_user_holiday_validator;
740
741 $this->default_range = $obj->default_range;
742 $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
743 $this->fk_warehouse = $obj->fk_warehouse;
744 $this->fk_establishment = $obj->fk_establishment;
745 $this->label_establishment = $obj->label_establishment;
746
747 // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
748 // in such case, this admin user must be admin for ALL entities.
749 if (!isModEnabled('multicompany') && $this->admin && $this->entity == 1) {
750 $this->entity = 0;
751 }
752
753 // Retrieve all extrafield
754 // fetch optionals attributes and labels
755 $this->fetch_optionals();
756
757 $this->db->free($resql);
758 } else {
759 $this->error = "USERNOTFOUND";
760 dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
761
762 $this->db->free($resql);
763 return 0;
764 }
765 } else {
766 $this->error = $this->db->lasterror();
767 return -1;
768 }
769
770 // To get back the global configuration unique to the user
771 if ($loadpersonalconf) {
772 $result = $this->loadPersonalConf($entity);
773
774 $result = $this->loadDefaultValues();
775
776 if ($result < 0) {
777 $this->error = $this->db->lasterror();
778 return -3;
779 }
780 }
781
782 // Add option to allow an admin internal user to make quick debug for internal users. Not yet implemented completely.
783 // This is a special cas that is allowed to have a GETPOST inside a class.
784 if (GETPOSTINT('forceexternaluser') && $this->admin && empty($this->socid)) {
785 $this->socid = GETPOSTINT('forceexternaluser');
786 }
787
788 return 1;
789 }
790
791
798 public function loadPersonalConf($entity = -1)
799 {
800 global $conf;
801
802 // Load user->conf for user
803 $sql = "SELECT param, value FROM ".$this->db->prefix()."user_param";
804 $sql .= " WHERE fk_user = ".((int) $this->id);
805 if ($entity < 0) {
806 $sql .= " AND entity IN (0, ".((int) $conf->entity).")"; // IN (0, x)
807 } else {
808 $sql .= " AND entity = ".((int) $entity); // 0 or x
809 }
810
811 //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
812 $resql = $this->db->query($sql);
813 if ($resql) {
814 $num = $this->db->num_rows($resql);
815 $i = 0;
816 while ($i < $num) {
817 $obj = $this->db->fetch_object($resql);
818 $p = (!empty($obj->param) ? $obj->param : '');
819 if (!empty($p)) {
820 $this->conf->$p = $obj->value;
821 }
822 $i++;
823 }
824 $this->db->free($resql);
825
826 return $num;
827 } else {
828 $this->error = $this->db->lasterror();
829
830 return -2;
831 }
832 }
833
839 public function loadDefaultValues()
840 {
841 global $conf;
842
843 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
844 // Load user->default_values for user. TODO Save this in memcached ?
845 require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php';
846
847 $defaultValues = new DefaultValues($this->db);
848 $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)
849 //$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)
850
851 if (!is_array($result) && $result < 0) {
852 setEventMessages($defaultValues->error, $defaultValues->errors, 'errors');
853 dol_print_error($this->db);
854 return -1;
855 } elseif (count($result) > 0) {
856 foreach ($result as $defval) {
857 if (!empty($defval->page) && !empty($defval->type) && !empty($defval->param)) {
858 $pagewithoutquerystring = $defval->page;
859 $pagequeries = '';
860 $reg = array();
861 if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
862 $pagewithoutquerystring = $reg[1];
863 $pagequeries = $reg[2];
864 }
865 $this->default_values[$pagewithoutquerystring][$defval->type][$pagequeries ? $pagequeries : '_noquery_'][$defval->param] = $defval->value;
866 }
867 }
868 }
869 if (!empty($this->default_values)) {
870 foreach ($this->default_values as $a => $b) {
871 foreach ($b as $c => $d) {
872 krsort($this->default_values[$a][$c]);
873 }
874 }
875 }
876 }
877 return 1;
878 }
879
886 public function isAdmin()
887 {
888 return $this->admin;
889 }
890
897 public function isExternalUser()
898 {
899 return $this->socid;
900 }
901
913 public function hasRight($module, $permlevel1, $permlevel2 = '')
914 {
915 // For compatibility with bad naming permissions on module
916 $moduletomoduletouse = array(
917 'category' => 'categorie',
918 'compta' => 'comptabilite',
919 'contract' => 'contrat',
920 'member' => 'adherent',
921 'mo' => 'mrp',
922 'order' => 'commande',
923 'produit' => 'product',
924 'productlot' => 'product',
925 'project' => 'projet',
926 'propale' => 'propal',
927 'shipping' => 'expedition',
928 'task' => 'task@projet',
929 'fichinter' => 'ficheinter',
930 'intervention' => 'ficheinter',
931 'inventory' => 'stock',
932 'invoice' => 'facture',
933 'invoice_supplier' => 'facture@fournisseur',
934 'order_supplier' => 'fournisseur',
935 'knowledgerecord' => 'knowledgerecord@knowledgemanagement',
936 'skill@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
937 'job@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
938 'position@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
939 'facturerec' => 'facture',
940 'margins' => 'margin',
941 );
942
943 if (!empty($moduletomoduletouse[$module])) {
944 $module = $moduletomoduletouse[$module];
945 }
946
947 // Compatibility layer for the supplier module split transition (MAIN_USE_NEW_SUPPLIERMOD).
948 // Allows both old and new permission syntaxes to work in parallel during migration.
949 // - Old: $user->hasRight('fournisseur', 'commande', 'lire')
950 // - New: $user->hasRight('supplier_order', 'lire')
951 // External modules are also transparently supported without any change on their side.
952 if (getDolGlobalInt('MAIN_USE_NEW_SUPPLIERMOD')) {
953 // New module names introduced by the split, mapped to their legacy equivalent.
954 // Format: 'new_module' => ['legacy_module', 'legacy_permlevel1']
955 $supplierNewToLegacy = array(
956 'supplier_order' => array('fournisseur', 'commande'),
957 'supplier_invoice' => array('fournisseur', 'facture'),
958 );
959
960 if (isset($supplierNewToLegacy[$module])) {
961 // Caller used new syntax: rewrite to legacy so the rights object resolves correctly.
962 // e.g. hasRight('supplier_order', 'lire') -> hasRight('fournisseur', 'commande', 'lire')
963 $permlevel2 = $permlevel1;
964 $permlevel1 = $supplierNewToLegacy[$module][1]; // e.g. 'commande'
965 $module = $supplierNewToLegacy[$module][0]; // e.g. 'fournisseur'
966 }
967 } else {
968 // Legacy mode: translate new module names back to old ones in case some
969 // updated code calls the new syntax while the option is not yet enabled.
970 $supplierLegacyCompat = array(
971 'supplier_order' => 'fournisseur',
972 'supplier_invoice' => 'fournisseur',
973 );
974
975 if (isset($supplierLegacyCompat[$module])) {
976 // e.g. hasRight('supplier_order', 'lire') stays routed through 'fournisseur'
977 $module = $supplierLegacyCompat[$module];
978 }
979 }
980
981 $moduleRightsMapping = array(
982 'product' => 'produit',
983 'margin' => 'margins',
984 'comptabilite' => 'compta'
985 );
986
987 $rightsPath = $module;
988 if (!empty($moduleRightsMapping[$rightsPath])) {
989 $rightsPath = $moduleRightsMapping[$rightsPath];
990 }
991
992 // If module is abc@module, we check permission user->hasRight(module, abc, permlevel1)
993 $tmp = explode('@', $rightsPath, 2);
994 if (!empty($tmp[1])) {
995 if (strpos($module, '@') !== false) {
996 $module = $tmp[1];
997 }
998 if ($tmp[0] != $tmp[1]) {
999 // If $module = 'myobject@mymodule'
1000 $rightsPath = $tmp[1];
1001 $permlevel2 = $permlevel1;
1002 $permlevel1 = $tmp[0];
1003 } else {
1004 // If $module = 'abc@abc'
1005 $rightsPath = $tmp[1];
1006 }
1007 }
1008
1009 // In $conf->modules, we have 'accounting', 'product', 'facture', ...
1010 // In $user->rights, we have 'accounting', 'produit', 'facture', ...
1011 //var_dump($this->rights->$rightsPath);
1012 //var_dump($conf->modules);
1013 //if ($module == 'fournisseur') { var_dump($module.' '.isModEnabled($module).' '.$rightsPath.' '.$permlevel1.' '.$permlevel2); }
1014
1015 if (!isModEnabled($module)) {
1016 return 0;
1017 }
1018
1019 // Special case for external user
1020 if (!empty($this->socid)) {
1021 if ($module == 'societe' && ($permlevel1 == 'creer' || $permlevel1 == 'write')) {
1022 return 0; // An external user never has the permission ->societe->write to see all thirdparties (always restricted to himself)
1023 }
1024 if ($module == 'societe' && $permlevel1 == 'client' && $permlevel2 == 'voir') {
1025 return 0; // An external user never has the permission ->societe->client->voir to see all thirdparties (always restricted to himself)
1026 }
1027 if ($module == 'societe' && $permlevel1 == 'export') {
1028 return 0; // An external user never has the permission ->societe->export to see all thirdparties (always restricted to himself)
1029 }
1030 if ($module == 'societe' && ($permlevel1 == 'supprimer' || $permlevel1 == 'delete')) {
1031 return 0; // An external user never has the permission ->societe->delete to see all thirdparties (always restricted to himself)
1032 }
1033 }
1034
1035 // For compatibility with bad naming permissions on permlevel1
1036 if ($permlevel1 == 'propale') {
1037 $permlevel1 = 'propal';
1038 }
1039 if ($permlevel1 == 'member') {
1040 $permlevel1 = 'adherent';
1041 }
1042 if ($permlevel1 == 'recruitmentcandidature') {
1043 $permlevel1 = 'recruitmentjobposition';
1044 }
1045
1046 //var_dump($this->rights);
1047 //var_dump($rightsPath.' '.$permlevel1.' '.$permlevel2);
1048 if (empty($rightsPath) || empty($this->rights) || empty($this->rights->$rightsPath) || empty($permlevel1)) {
1049 return 0;
1050 }
1051
1052 if ($permlevel2) {
1053 if (!empty($this->rights->$rightsPath->$permlevel1)) {
1054 if (!empty($this->rights->$rightsPath->$permlevel1->$permlevel2)) {
1055 return $this->rights->$rightsPath->$permlevel1->$permlevel2;
1056 }
1057 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
1058 // instead of "read", "write", "delete"
1059 if ($permlevel2 == 'read' && !empty($this->rights->$rightsPath->$permlevel1->lire)) {
1060 return $this->rights->$rightsPath->$permlevel1->lire;
1061 }
1062 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->creer)) {
1063 return $this->rights->$rightsPath->$permlevel1->creer;
1064 }
1065 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->create)) {
1066 return $this->rights->$rightsPath->$permlevel1->create;
1067 }
1068 if ($permlevel2 == 'delete' && !empty($this->rights->$rightsPath->$permlevel1->supprimer)) {
1069 return $this->rights->$rightsPath->$permlevel1->supprimer;
1070 }
1071 }
1072 } else {
1073 if (!empty($this->rights->$rightsPath->$permlevel1)) {
1074 return $this->rights->$rightsPath->$permlevel1;
1075 }
1076 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
1077 // instead of "read", "write", "delete"
1078 if ($permlevel1 == 'read' && !empty($this->rights->$rightsPath->lire)) {
1079 return $this->rights->$rightsPath->lire;
1080 }
1081 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->creer)) {
1082 return $this->rights->$rightsPath->creer;
1083 }
1084 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->create)) {
1085 return $this->rights->$rightsPath->create;
1086 }
1087 if ($permlevel1 == 'delete' && !empty($this->rights->$rightsPath->supprimer)) {
1088 return $this->rights->$rightsPath->supprimer;
1089 }
1090 }
1091
1092 return 0;
1093 }
1094
1106 public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1107 {
1108 global $conf, $user, $langs;
1109
1110 $entity = (empty($entity) ? $conf->entity : $entity);
1111
1112 dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity, $notrigger for user id=".$this->id);
1113
1114 if (empty($this->id)) {
1115 $this->error = 'Try to call addrights on an object user with an empty id';
1116 return -1;
1117 }
1118
1119 $error = 0;
1120 $whereforadd = '';
1121
1122 $this->db->begin();
1123
1124 if (!empty($rid)) {
1125 $module = $perms = $subperms = '';
1126
1127 // If we ask to add a given permission, we first load properties of this permission (module, perms and subperms).
1128 $sql = "SELECT module, perms, subperms";
1129 $sql .= " FROM ".$this->db->prefix()."rights_def";
1130 $sql .= " WHERE id = ".((int) $rid);
1131 $sql .= " AND entity = ".((int) $entity);
1132
1133 $result = $this->db->query($sql);
1134 if ($result) {
1135 $obj = $this->db->fetch_object($result);
1136
1137 if ($obj) {
1138 $module = $obj->module;
1139 $perms = $obj->perms;
1140 $subperms = $obj->subperms;
1141 }
1142 } else {
1143 $error++;
1144 dol_print_error($this->db);
1145 }
1146
1147 // Define the where for the permission to add
1148 $whereforadd = "id=".((int) $rid);
1149 // Add also inherited permissions
1150 if (!empty($subperms)) {
1151 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))";
1152 } elseif (!empty($perms)) {
1153 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND (subperms IS NULL or subperms = ''))";
1154 }
1155 } else {
1156 // A list of permission was requested (not a single specific permission)
1157 // based on the name of a module of permissions
1158 // Used in the where clause to determine the list of permissions to add.
1159 if (!empty($allmodule)) {
1160 if ($allmodule == 'allmodules') {
1161 $whereforadd = 'allmodules';
1162 } else {
1163 $whereforadd = "module='".$this->db->escape($allmodule)."'";
1164 if (!empty($allperms)) {
1165 $whereforadd .= " AND perms='".$this->db->escape($allperms)."'";
1166 }
1167 }
1168 }
1169 }
1170
1171 // Add automatically other permission using the criteria whereforadd
1172 // $whereforadd can be a SQL filter or the string 'allmodules'
1173 if (!empty($whereforadd)) {
1174 //print "$module-$perms-$subperms";
1175 $sql = "SELECT id";
1176 $sql .= " FROM ".$this->db->prefix()."rights_def";
1177 $sql .= " WHERE entity = ".((int) $entity);
1178 if (!empty($whereforadd) && $whereforadd != 'allmodules') {
1179 $sql .= " AND (".$whereforadd.")"; // Note: parenthesis are important because whereforadd can contains OR. Also note that $whereforadd is already sanitized
1180 }
1181
1182 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1183 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1184 $sqldelete .= $sql;
1185 $sqldelete .= ") AND entity = ".((int) $entity);
1186 if (!$this->db->query($sqldelete)) {
1187 $error++;
1188 }
1189
1190 if (!$error) {
1191 $resql = $this->db->query($sql);
1192 if ($resql) {
1193 $num = $this->db->num_rows($resql);
1194 $i = 0;
1195 while ($i < $num) {
1196 $obj = $this->db->fetch_object($resql);
1197
1198 if ($obj) {
1199 $nid = $obj->id;
1200
1201 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id) VALUES (".((int) $entity).", ".((int) $this->id).", ".((int) $nid).")";
1202 if (!$this->db->query($sql)) {
1203 $error++;
1204 }
1205 }
1206
1207 $i++;
1208 }
1209 } else {
1210 $error++;
1211 dol_print_error($this->db);
1212 }
1213 }
1214 }
1215
1216 if (!$error && !$notrigger) {
1217 $langs->load("other");
1218 $this->context = array('audit' => $langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : ''));
1219
1220 // Call trigger
1221 $result = $this->call_trigger('USER_MODIFY', $user);
1222 if ($result < 0) {
1223 $error++;
1224 }
1225 // End call triggers
1226 }
1227
1228 if ($error) {
1229 $this->db->rollback();
1230 return -$error;
1231 } else {
1232 $this->db->commit();
1233 return 1;
1234 }
1235 }
1236
1237
1249 public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1250 {
1251 global $conf, $user, $langs;
1252
1253 $error = 0;
1254 $wherefordel = '';
1255 $entity = (!empty($entity) ? $entity : $conf->entity);
1256
1257 $this->db->begin();
1258
1259 if (!empty($rid)) {
1260 $module = $perms = $subperms = '';
1261
1262 // When the request is to delete a specific permissions, this gets the
1263 // les charactis for the module, permissions and sub-permission of this permission.
1264 $sql = "SELECT module, perms, subperms";
1265 $sql .= " FROM ".$this->db->prefix()."rights_def";
1266 $sql .= " WHERE id = ".((int) $rid);
1267 $sql .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1268
1269 $result = $this->db->query($sql);
1270 if ($result) {
1271 $obj = $this->db->fetch_object($result);
1272
1273 if ($obj) {
1274 $module = $obj->module;
1275 $perms = $obj->perms;
1276 $subperms = $obj->subperms;
1277 }
1278 } else {
1279 $error++;
1280 dol_print_error($this->db);
1281 }
1282
1283 // Where clause for the list of permissions to delete
1284 $wherefordel = "id=".((int) $rid);
1285 // Removal of induced rights
1286 if ($subperms == 'lire' || $subperms == 'read') {
1287 $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)";
1288 }
1289 if ($perms == 'lire' || $perms == 'read') {
1290 $wherefordel .= " OR (module='".$this->db->escape($module)."')";
1291 }
1292 } else {
1293 // The deletion of the permissions concerns the name of a module or
1294 // list of permissions.
1295 // Used in the Where clause to determine the list of permission to delete
1296 if (!empty($allmodule)) {
1297 if ($allmodule == 'allmodules') {
1298 $wherefordel = 'allmodules';
1299 } else {
1300 $wherefordel = "module='".$this->db->escape($allmodule)."'";
1301 if (!empty($allperms)) {
1302 $wherefordel .= " AND perms='".$this->db->escape($allperms)."'";
1303 }
1304 }
1305 }
1306 }
1307
1308 // Delete permission according to a criteria set into $wherefordel
1309 if (!empty($wherefordel)) {
1310 //print "$module-$perms-$subperms";
1311 $sql = "SELECT id";
1312 $sql .= " FROM ".$this->db->prefix()."rights_def";
1313 $sql .= " WHERE entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1314 if (!empty($wherefordel) && $wherefordel != 'allmodules') {
1315 $sql .= " AND (".$wherefordel.")"; // Note: parenthesis are important because wherefordel can contains OR. Also note that $wherefordel is already sanitized
1316 }
1317
1318 // avoid admin to remove his own important rights
1319 if ($this->admin == 1) {
1320 $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
1321 $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
1322 $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
1323 $sql .= " AND id NOT IN (358)"; // user export
1324 }
1325
1326 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1327 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1328 $sqldelete .= $sql;
1329 $sqldelete .= ")";
1330 $sqldelete .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1331
1332 $resql = $this->db->query($sqldelete);
1333 if (!$resql) {
1334 $error++;
1335 dol_print_error($this->db);
1336 }
1337 }
1338
1339 if (!$error && !$notrigger) {
1340 $langs->load("other");
1341 $this->context = array('audit' => $langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : ''));
1342
1343 // Call trigger
1344 $result = $this->call_trigger('USER_MODIFY', $user);
1345 if ($result < 0) {
1346 $error++;
1347 }
1348 // End call triggers
1349 }
1350
1351 if ($error) {
1352 $this->db->rollback();
1353 return -$error;
1354 } else {
1355 $this->db->commit();
1356 return 1;
1357 }
1358 }
1359
1360
1367 public function clearrights()
1368 {
1369 dol_syslog(get_class($this)."::clearrights reset user->rights");
1370 $this->rights = new stdClass();
1371 $this->nb_rights = 0;
1372 $this->all_permissions_are_loaded = 0;
1373 $this->_tab_loaded = array();
1374 }
1375
1376
1385 public function loadRights($moduletag = '', $forcereload = 0)
1386 {
1387 global $conf;
1388
1389 $alreadyloaded = false;
1390
1391 if (empty($forcereload)) {
1392 if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
1393 // Rights for this module are already loaded, so we leave
1394 $alreadyloaded = true;
1395 }
1396
1397 if (!empty($this->all_permissions_are_loaded)) {
1398 // We already loaded all rights for this user, so we leave
1399 $alreadyloaded = true;
1400 }
1401 }
1402
1403 // More init to avoid warnings/errors
1404 if (!isset($this->rights) || !is_object($this->rights)) {
1405 $this->rights = new stdClass();
1406 }
1407 if (!isset($this->rights->user) || !is_object($this->rights->user)) {
1408 $this->rights->user = new stdClass();
1409 }
1410
1411 // Get permission of users + Get permissions of groups
1412
1413 if (!$alreadyloaded) {
1414 // First user permissions
1415 $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1416 $sql .= " FROM ".$this->db->prefix()."user_rights as ur,";
1417 $sql .= " ".$this->db->prefix()."rights_def as r";
1418 $sql .= " WHERE r.id = ur.fk_id";
1419 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1420 // On old version, we used entity defined into table r only
1421 // @FIXME Test on MULTICOMPANY_BACKWARD_COMPATIBILITY is a very strange business rules because the select should be always the
1422 // same than into user->loadRights() in user/perms.php and user/group/perms.php
1423 // We should never use and remove this case.
1424 $sql .= " AND r.entity IN (0,".(isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') ? "1," : "").((int) $conf->entity).")";
1425 } else {
1426 // On table r=rights_def, the unique key is (id, entity) because id is hard coded into module descriptor and inserted during module activation.
1427 // So we must include the filter on entity on both table r. and ur.
1428 $sql .= " AND r.entity = ".((int) $conf->entity)." AND ur.entity = ".((int) $conf->entity);
1429 }
1430 $sql .= " AND ur.fk_user = ".((int) $this->id);
1431 $sql .= " AND r.perms IS NOT NULL";
1432 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1433 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1434 }
1435 if ($moduletag) {
1436 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1437 }
1438
1439 $resql = $this->db->query($sql);
1440 if ($resql) {
1441 $num = $this->db->num_rows($resql);
1442 $i = 0;
1443 while ($i < $num) {
1444 $obj = $this->db->fetch_object($resql);
1445
1446 if ($obj) {
1447 $module = $obj->module;
1448 $perms = $obj->perms;
1449 $subperms = $obj->subperms;
1450
1451 if (!empty($perms)) {
1452 if (!empty($module)) {
1453 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1454 $this->rights->$module = new stdClass();
1455 }
1456 if (!empty($subperms)) {
1457 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1458 $this->rights->$module->$perms = new stdClass();
1459 }
1460 if (empty($this->rights->$module->$perms->$subperms)) { // if not already counted
1461 $this->nb_rights++;
1462 }
1463 $this->rights->$module->$perms->$subperms = 1;
1464 } else {
1465 if (empty($this->rights->$module->$perms)) { // if not already counted
1466 $this->nb_rights++;
1467 }
1468 $this->rights->$module->$perms = 1;
1469 }
1470 }
1471 }
1472 }
1473 $i++;
1474 }
1475 $this->db->free($resql);
1476 }
1477
1478 // Now permissions of groups
1479 $sql = "SELECT DISTINCT r.module, r.perms, r.subperms, r.entity";
1480 $sql .= " FROM ".$this->db->prefix()."usergroup_rights as gr,";
1481 $sql .= " ".$this->db->prefix()."usergroup_user as gu,";
1482 $sql .= " ".$this->db->prefix()."rights_def as r";
1483 $sql .= " WHERE r.id = gr.fk_id";
1484 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1485 // @FIXME Test on MULTICOMPANY_BACKWARD_COMPATIBILITY is a very strange business rules because the select should be always the
1486 // same than into user->loadRights() in user/perms.php and user/group/perms.php
1487 // We should never use and remove this case.
1488 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1489 $sql .= " AND gu.entity IN (0,".((int) $conf->entity).")";
1490 } else {
1491 $sql .= " AND r.entity = ".((int) $conf->entity);
1492 }
1493 } else {
1494 $sql .= " AND gr.entity = ".((int) $conf->entity); // Only groups created in current entity
1495 // The entity on the table gu=usergroup_user should be useless and should never be used because it is already into gr and r.
1496 // but when using MULTICOMPANY_TRANSVERSE_MODE, we may have inserted record that make rubbish result here due to the duplicate record of
1497 // other entities, so we are forced to add a filter on gu here
1498 $sql .= " AND gu.entity IN (0,".((int) $conf->entity).")";
1499 $sql .= " AND r.entity = ".((int) $conf->entity); // Only permission of modules enabled in current entity
1500 }
1501 // End of strange business rule
1502 $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
1503 $sql .= " AND gu.fk_user = ".((int) $this->id);
1504 $sql .= " AND r.perms IS NOT NULL";
1505 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1506 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1507 }
1508 if ($moduletag) {
1509 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1510 }
1511
1512 $resql = $this->db->query($sql);
1513 if ($resql) {
1514 $num = $this->db->num_rows($resql);
1515 $i = 0;
1516 while ($i < $num) {
1517 $obj = $this->db->fetch_object($resql);
1518
1519 if ($obj) {
1520 $module = $obj->module;
1521 $perms = $obj->perms;
1522 $subperms = $obj->subperms;
1523
1524 if (!empty($perms)) {
1525 if (!empty($module)) {
1526 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1527 $this->rights->$module = new stdClass();
1528 }
1529 if (!empty($subperms)) {
1530 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1531 $this->rights->$module->$perms = new stdClass();
1532 }
1533 if (empty($this->rights->$module->$perms->$subperms)) { // if not already counted
1534 $this->nb_rights++;
1535 }
1536 $this->rights->$module->$perms->$subperms = 1;
1537 } else {
1538 // 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
1539 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1540 if (empty($this->rights->$module->$perms)) { // if not already counted
1541 $this->nb_rights++;
1542 }
1543 $this->rights->$module->$perms = 1;
1544 }
1545 }
1546 }
1547 }
1548 }
1549 $i++;
1550 }
1551 $this->db->free($resql);
1552 }
1553
1554 // Force permission on user for admin
1555 if (!empty($this->admin)) {
1556 if (empty($this->rights->user->user)) {
1557 $this->rights->user->user = new stdClass();
1558 }
1559 $listofpermtotest = array('lire', 'creer', 'password', 'supprimer', 'export');
1560 foreach ($listofpermtotest as $permtotest) {
1561 if (empty($this->rights->user->user->$permtotest)) {
1562 $this->rights->user->user->$permtotest = 1;
1563 $this->nb_rights++;
1564 }
1565 }
1566 if (empty($this->rights->user->self)) {
1567 $this->rights->user->self = new stdClass();
1568 }
1569 $listofpermtotest = array('creer', 'password');
1570 foreach ($listofpermtotest as $permtotest) {
1571 if (empty($this->rights->user->self->$permtotest)) {
1572 $this->rights->user->self->$permtotest = 1;
1573 $this->nb_rights++;
1574 }
1575 }
1576 // Add test on advanced permissions
1577 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1578 if (empty($this->rights->user->user_advance)) {
1579 $this->rights->user->user_advance = new stdClass();
1580 }
1581 $listofpermtotest = array('readperms', 'write');
1582 foreach ($listofpermtotest as $permtotest) {
1583 if (empty($this->rights->user->user_advance->$permtotest)) {
1584 $this->rights->user->user_advance->$permtotest = 1;
1585 $this->nb_rights++;
1586 }
1587 }
1588 if (empty($this->rights->user->self_advance)) {
1589 $this->rights->user->self_advance = new stdClass();
1590 }
1591 $listofpermtotest = array('readperms', 'writeperms');
1592 foreach ($listofpermtotest as $permtotest) {
1593 if (empty($this->rights->user->self_advance->$permtotest)) {
1594 $this->rights->user->self_advance->$permtotest = 1;
1595 $this->nb_rights++;
1596 }
1597 }
1598 if (empty($this->rights->user->group_advance)) {
1599 $this->rights->user->group_advance = new stdClass();
1600 }
1601 $listofpermtotest = array('read', 'readperms', 'write', 'delete');
1602 foreach ($listofpermtotest as $permtotest) {
1603 if (empty($this->rights->user) || empty($this->rights->user->group_advance->$permtotest)) {
1604 $this->rights->user->group_advance->$permtotest = 1;
1605 $this->nb_rights++;
1606 }
1607 }
1608 }
1609 }
1610
1611 // For backward compatibility
1612 if (isset($this->rights->propale) && !isset($this->rights->propal)) {
1613 $this->rights->propal = $this->rights->propale;
1614 }
1615 if (isset($this->rights->propal) && !isset($this->rights->propale)) {
1616 $this->rights->propale = $this->rights->propal;
1617 }
1618
1619 if (!$moduletag) {
1620 // If the module was not define, then everything is loaded.
1621 // Therefore, we can consider that the permissions are cached
1622 // because they were all loaded for this user instance.
1623 $this->all_permissions_are_loaded = 1;
1624 } else {
1625 // If the module is defined, we flag it as loaded into cache
1626 $this->_tab_loaded[$moduletag] = 1;
1627 }
1628 }
1629 }
1630
1643 public function getrights($moduletag = '', $forcereload = 0)
1644 {
1645 $this->loadRights($moduletag, $forcereload);
1646 }
1647
1654 public function setstatus($status)
1655 {
1656 global $conf, $langs, $user;
1657
1658 $error = 0;
1659
1660 // Check parameters
1661 if (isset($this->statut)) {
1662 if ($this->statut == $status) {
1663 return 0;
1664 }
1665 } elseif (isset($this->status) && $this->status == $status) {
1666 return 0;
1667 }
1668
1669 $this->db->begin();
1670
1671 // Save in database
1672 $sql = "UPDATE ".$this->db->prefix()."user";
1673 $sql .= " SET statut = ".((int) $status);
1674 $sql .= " WHERE rowid = ".((int) $this->id);
1675 $result = $this->db->query($sql);
1676
1677 dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1678 if ($result) {
1679 if ($status == 0) {
1680 $this->context['actionmsg'] = 'User '.$this->login.' disabled';
1681 } else {
1682 $this->context['actionmsg'] = 'User '.$this->login.' enabled';
1683 }
1684 // Call trigger
1685 $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
1686 if ($result < 0) {
1687 $error++;
1688 }
1689 // End call triggers
1690 }
1691
1692 if ($error) {
1693 $this->db->rollback();
1694 return -$error;
1695 } else {
1696 $this->status = $status;
1697 $this->statut = $status;
1698 $this->db->commit();
1699 return 1;
1700 }
1701 }
1702
1710 public function setForcePasswordChange($user, $value)
1711 {
1712 $error = 0;
1713
1714 $value = (int) $value;
1715
1716 // Check parameters : no change short line
1717 if ($this->force_pass_change == $value) {
1718 return 0;
1719 }
1720
1721 $this->db->begin();
1722
1723 // Save in database
1724 $sql = "UPDATE ".$this->db->prefix()."user";
1725 $sql .= " SET force_pass_change = ".((int) $value);
1726 $sql .= " WHERE rowid = ".((int) $this->id);
1727 $result = $this->db->query($sql);
1728
1729 dol_syslog(get_class($this)."::setForcePasswordChange", LOG_DEBUG);
1730 if ($result) {
1731 $this->force_pass_change = $value;
1732 // Call trigger
1733 $result = $this->call_trigger('USER_MODIFY', $user);
1734 if ($result < 0) {
1735 $error++;
1736 }
1737 // End call triggers
1738 } else {
1739 $error++;
1740 $this->error = $this->db->lasterror();
1741 }
1742
1743 if ($error) {
1744 $this->db->rollback();
1745 return -$error;
1746 } else {
1747 $this->db->commit();
1748 return 1;
1749 }
1750 }
1751
1762 public function setCategories($categories)
1763 {
1764 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1765 return parent::setCategoriesCommon($categories, Categorie::TYPE_USER);
1766 }
1767
1774 public function delete(User $user)
1775 {
1776 $error = 0;
1777
1778 $this->db->begin();
1779
1780 $this->fetch($this->id);
1781
1782 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1783
1784 // A user that still has HRM data (competency assessments, job positions, skills) must not be deleted
1785 if (isModEnabled('hrm')) {
1786 global $langs;
1787
1788 $hrmtables = array(
1789 'hrm_evaluation' => array('label' => 'EvaluationCard', 'filter' => "fk_user = ".((int) $this->id)),
1790 'hrm_job_user' => array('label' => 'EmployeePosition', 'filter' => "fk_user = ".((int) $this->id)),
1791 'hrm_skillrank' => array('label' => 'Skill', 'filter' => "objecttype = 'user' AND fk_object = ".((int) $this->id)),
1792 );
1793 foreach ($hrmtables as $hrmtable => $sanitizedhrminfo) {
1794 $sanitizedfilter = $sanitizedhrminfo['filter']; // Built above from the id of the user only
1795 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->db->sanitize($hrmtable)." WHERE ".$sanitizedfilter;
1796 $resql = $this->db->query($sql);
1797 if ($resql) {
1798 $obj = $this->db->fetch_object($resql);
1799 if ($obj && $obj->nb > 0) {
1800 $langs->loadLangs(array('errors', 'hrm'));
1801 $this->error = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $this->login, $langs->transnoentitiesnoconv($sanitizedhrminfo['label']));
1802 $this->errors[] = $this->error;
1803 $this->db->rollback();
1804 return -1;
1805 }
1806 }
1807 }
1808 }
1809
1810 // Remove rights
1811 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1812
1813 if (!$error && !$this->db->query($sql)) {
1814 $error++;
1815 $this->error = $this->db->lasterror();
1816 }
1817
1818 // Remove group
1819 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1820 if (!$error && !$this->db->query($sql)) {
1821 $error++;
1822 $this->error = $this->db->lasterror();
1823 }
1824
1825 // Remove params
1826 $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1827 if (!$error && !$this->db->query($sql)) {
1828 $error++;
1829 $this->error = $this->db->lasterror();
1830 }
1831
1832 // Remove the private bookmarks of the user (the public ones have no owner and are kept)
1833 $sql = "DELETE FROM ".$this->db->prefix()."bookmark WHERE fk_user = ".((int) $this->id);
1834 if (!$error && !$this->db->query($sql)) {
1835 $error++;
1836 $this->error = $this->db->lasterror();
1837 }
1838
1839 // If contact, remove link
1840 if ($this->contact_id > 0) {
1841 $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1842 if (!$error && !$this->db->query($sql)) {
1843 $error++;
1844 $this->error = $this->db->lasterror();
1845 }
1846 }
1847
1848 // Remove extrafields
1849 if (!$error) {
1850 $result = $this->deleteExtraFields();
1851 if ($result < 0) {
1852 $error++;
1853 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1854 }
1855 }
1856
1857 // Remove user
1858 if (!$error) {
1859 $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1860 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1861 if (!$this->db->query($sql)) {
1862 $error++;
1863 $this->error = $this->db->lasterror();
1864 }
1865 }
1866
1867 if (!$error) {
1868 // Call trigger
1869 $result = $this->call_trigger('USER_DELETE', $user);
1870 if ($result < 0) {
1871 $error++;
1872 $this->db->rollback();
1873 return -1;
1874 }
1875 // End call triggers
1876
1877 $this->db->commit();
1878 return 1;
1879 } else {
1880 $this->db->rollback();
1881 return -1;
1882 }
1883 }
1884
1892 public function create($user, $notrigger = 0)
1893 {
1894 global $conf, $langs;
1895 global $mysoc;
1896
1897 // Clean parameters
1898 $this->setUpperOrLowerCase();
1899
1900 $this->civility_code = trim((string) $this->civility_code);
1901 $this->login = trim((string) $this->login);
1902 $this->user_creation_id = (int) $user->id;
1903 if (!isset($this->entity)) {
1904 $this->entity = $conf->entity; // If not defined, we use default value
1905 }
1906 dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1907
1908 $badCharUnauthorizedIntoLoginName = getDolGlobalLoginBadCharUnauthorized();
1909
1910 // Check parameters
1911 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
1912 $langs->load("errors");
1913 $this->error = $langs->trans("ErrorBadEMail", $this->email);
1914 return -1;
1915 }
1916 if (empty($this->login)) {
1917 $langs->load("errors");
1918 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1919 return -1;
1920 } elseif ($badCharUnauthorizedIntoLoginName !== '' && preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1921 $langs->load("errors");
1922 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1923 return -1;
1924 }
1925
1926 $this->datec = dol_now();
1927
1928 $error = 0;
1929 $this->db->begin();
1930
1931 // Check if login already exists in same entity or into entity 0.
1932 if ($this->login) {
1933 $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)."'";
1934 $resqltochecklogin = $this->db->query($sqltochecklogin);
1935 if ($resqltochecklogin) {
1936 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1937 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1938 $langs->load("errors");
1939 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1940 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1941 $this->db->rollback();
1942 return -6;
1943 }
1944 $this->db->free($resqltochecklogin);
1945 }
1946 }
1947 if (!empty($this->email)) {
1948 $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)."'";
1949 $resqltochecklogin = $this->db->query($sqltochecklogin);
1950 if ($resqltochecklogin) {
1951 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1952 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1953 $langs->load("errors");
1954 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1955 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1956 $this->db->rollback();
1957 return -6;
1958 }
1959 $this->db->free($resqltochecklogin);
1960 }
1961 }
1962
1963 // Insert into database
1964 $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, fk_user_creat, entity)";
1965 $sql .= " VALUES('".$this->db->idate($this->datec)."', '".$this->db->escape($this->login)."', '".$this->db->escape($this->ldap_sid)."', ".(int) $this->user_creation_id.", ".((int) $this->entity).")";
1966 $result = $this->db->query($sql);
1967
1968 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1969 if ($result) {
1970 $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1971
1972 // Set default rights
1973 if ($this->set_default_rights() < 0) {
1974 $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1975 $this->db->rollback();
1976 return -5;
1977 }
1978
1979 if (getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && getDolGlobalString('STOCK_USERSTOCK_AUTOCREATE')) {
1980 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1981 $langs->load("stocks");
1982
1983 $entrepot = new Entrepot($this->db);
1984 $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1985 $entrepot->libelle = $entrepot->label; // For backward compatibility
1986 $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1987 $entrepot->statut = 1;
1988 $entrepot->country_id = $mysoc->country_id;
1989
1990 $warehouseid = $entrepot->create($user);
1991
1992 $this->fk_warehouse = $warehouseid;
1993 }
1994
1995 // Update minor fields
1996 $result = $this->update($user, 1, 1);
1997 if ($result < 0) {
1998 $this->db->rollback();
1999 return -4;
2000 }
2001
2002 if (!$notrigger) {
2003 // Call trigger
2004 $result = $this->call_trigger('USER_CREATE', $user);
2005 if ($result < 0) {
2006 $error++;
2007 }
2008 // End call triggers
2009 }
2010
2011 if (!$error) {
2012 $this->db->commit();
2013 return $this->id;
2014 } else {
2015 //$this->error=$interface->error;
2016 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
2017 $this->db->rollback();
2018 return -3;
2019 }
2020 } else {
2021 $this->error = $this->db->lasterror();
2022 $this->db->rollback();
2023 return -2;
2024 }
2025 }
2026
2027
2028 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2037 public function create_from_contact($contact, $login = '', $password = '')
2038 {
2039 // phpcs:enable
2040 global $user;
2041
2042 $error = 0;
2043
2044 // Define parameters
2045 $this->admin = 0;
2046 $this->civility_code = $contact->civility_code;
2047 $this->lastname = $contact->lastname;
2048 $this->firstname = $contact->firstname;
2049 //$this->gender = $contact->gender; // contact has no gender
2050 $this->email = $contact->email;
2051 $this->socialnetworks = $contact->socialnetworks;
2052 $this->office_phone = $contact->phone_pro;
2053 $this->office_fax = $contact->fax;
2054 $this->user_mobile = $contact->phone_mobile;
2055 $this->address = $contact->address;
2056 $this->zip = $contact->zip;
2057 $this->town = $contact->town;
2058 $this->setUpperOrLowerCase();
2059 $this->state_id = $contact->state_id;
2060 $this->country_id = $contact->country_id;
2061 $this->employee = 0;
2062
2063 if (empty($login)) {
2064 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2065 $login = dol_buildlogin($contact->lastname, $contact->firstname);
2066 }
2067 $this->login = $login;
2068
2069 $this->db->begin();
2070
2071 // Create user and set $this->id. Trigger is disabled because executed later.
2072 $result = $this->create($user, 1);
2073 if ($result > 0) {
2074 $sql = "UPDATE ".$this->db->prefix()."user";
2075 $sql .= " SET fk_socpeople=".((int) $contact->id);
2076 $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
2077 if ($contact->socid > 0) {
2078 $sql .= ", fk_soc=".((int) $contact->socid);
2079 }
2080 $sql .= " WHERE rowid=".((int) $this->id);
2081
2082 $resql = $this->db->query($sql);
2083
2084 dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
2085 if ($resql) {
2086 $this->context['createfromcontact'] = 'createfromcontact';
2087
2088 // Call trigger
2089 $result = $this->call_trigger('USER_CREATE', $user);
2090 if ($result < 0) {
2091 $error++;
2092 $this->db->rollback();
2093 return -1;
2094 }
2095 // End call triggers
2096
2097 $this->db->commit();
2098 return $this->id;
2099 } else {
2100 $this->error = $this->db->error();
2101
2102 $this->db->rollback();
2103 return -1;
2104 }
2105 } else {
2106 // $this->error already set
2107 dol_syslog(get_class($this)."::create_from_contact - 0");
2108
2109 $this->db->rollback();
2110 return $result;
2111 }
2112 }
2113
2114 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2123 public function create_from_member($member, $login = '')
2124 {
2125 // phpcs:enable
2126 global $user;
2127
2128 // Set properties on new user
2129 $this->admin = 0;
2130 $this->civility_code = $member->civility_code;
2131 // A corporation member has no lastname/firstname (the name is in the company field), so use it as
2132 // the user lastname, otherwise the created user would have an empty name and login (#33642).
2133 if ($member->morphy == 'mor' && empty($member->lastname) && !empty($member->company)) {
2134 $this->lastname = $member->company;
2135 $this->firstname = '';
2136 } else {
2137 $this->lastname = $member->lastname;
2138 $this->firstname = $member->firstname;
2139 }
2140 $this->gender = $member->gender;
2141 $this->email = $member->email;
2142 $this->fk_member = $member->id;
2143 $this->address = $member->address;
2144 $this->zip = $member->zip;
2145 $this->town = $member->town;
2146 $this->setUpperOrLowerCase();
2147 $this->state_id = $member->state_id;
2148 $this->country_id = $member->country_id;
2149 $this->socialnetworks = $member->socialnetworks;
2150
2151 $this->pass = $member->pass;
2152 $this->pass_crypted = $member->pass_indatabase_crypted;
2153
2154 if (empty($login)) {
2155 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2156 // Use the resolved name so a corporation member (name in company field) still gets a login.
2157 $login = dol_buildlogin($this->lastname, $this->firstname);
2158 }
2159 $this->login = $login;
2160
2161 $this->db->begin();
2162
2163 // Create and set $this->id
2164 $result = $this->create($user);
2165 if ($result > 0) {
2166 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
2167 $newpass = $this->setPassword($user, $this->pass);
2168 if (is_int($newpass) && $newpass < 0) {
2169 $result = -2;
2170 }
2171 } 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.
2172 $sql = "UPDATE ".$this->db->prefix()."user";
2173 $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
2174 $sql .= " WHERE rowid=".((int) $this->id);
2175
2176 $resql = $this->db->query($sql);
2177 if (!$resql) {
2178 $result = -1;
2179 }
2180 }
2181
2182 if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
2183 $sql = "UPDATE ".$this->db->prefix()."user";
2184 $sql .= " SET fk_soc=".((int) $member->socid);
2185 $sql .= " WHERE rowid=".((int) $this->id);
2186
2187 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
2188 $resql = $this->db->query($sql);
2189 if ($resql) {
2190 $this->db->commit();
2191 return $this->id;
2192 } else {
2193 $this->error = $this->db->lasterror();
2194
2195 $this->db->rollback();
2196 return -1;
2197 }
2198 }
2199 }
2200
2201 if ($result > 0) {
2202 $this->db->commit();
2203 return $this->id;
2204 } else {
2205 // $this->error was already set
2206 $this->db->rollback();
2207 return -2;
2208 }
2209 }
2210
2211 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2217 public function set_default_rights()
2218 {
2219 // phpcs:enable
2220 global $conf;
2221
2222 $rd = array();
2223 $num = 0;
2224 $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
2225 $sql .= " WHERE bydefault = 1";
2226 $sql .= " AND entity = ".((int) $conf->entity);
2227
2228 $resql = $this->db->query($sql);
2229 if ($resql) {
2230 $num = $this->db->num_rows($resql);
2231 $i = 0;
2232 while ($i < $num) {
2233 $row = $this->db->fetch_row($resql);
2234 $rd[$i] = $row[0];
2235 $i++;
2236 }
2237 $this->db->free($resql);
2238 }
2239 $i = 0;
2240 while ($i < $num) {
2241 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id)." AND fk_id=".((int) $rd[$i]);
2242 $result = $this->db->query($sql);
2243
2244 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES (".((int) $this->id).", ".((int) $rd[$i]).")";
2245 $result = $this->db->query($sql);
2246 if (!$result) {
2247 return -1;
2248 }
2249 $i++;
2250 }
2251
2252 return $i;
2253 }
2254
2265 public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
2266 {
2267 global $langs;
2268
2269 if (empty($this->country_id) && !empty($this->country_code)) {
2270 $country_id = getCountry($this->country_code, '3');
2271 $this->country_id = is_int($country_id) ? $country_id : 0;
2272 }
2273
2274 $nbrowsaffected = 0;
2275 $error = 0;
2276
2277 dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
2278
2279 // Clean parameters
2280 $this->civility_code = trim((string) $this->civility_code);
2281 $this->lastname = trim((string) $this->lastname);
2282 $this->firstname = trim((string) $this->firstname);
2283 $this->ref_employee = trim((string) $this->ref_employee);
2284 $this->national_registration_number = trim((string) $this->national_registration_number);
2285 $this->employee = ($this->employee > 0 ? $this->employee : 0);
2286 $this->login = trim((string) $this->login);
2287 $this->gender = trim((string) $this->gender);
2288
2289 $this->pass = trim((string) $this->pass);
2290 $this->api_key = trim((string) $this->api_key);
2291 $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
2292 $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
2293
2294 $this->address = trim((string) $this->address);
2295 $this->zip = trim((string) $this->zip);
2296 $this->town = trim((string) $this->town);
2297
2298 $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
2299 $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
2300 $this->office_phone = trim((string) $this->office_phone);
2301 $this->office_fax = trim((string) $this->office_fax);
2302 $this->user_mobile = trim((string) $this->user_mobile);
2303 $this->personal_mobile = trim((string) $this->personal_mobile);
2304 $this->email = trim((string) $this->email);
2305 $this->personal_email = trim((string) $this->personal_email);
2306
2307 $this->job = trim((string) $this->job);
2308 $this->signature = trim((string) $this->signature);
2309 $this->note_public = trim((string) $this->note_public);
2310 $this->note_private = trim((string) $this->note_private);
2311 $this->openid = trim((string) $this->openid);
2312 $this->admin = ($this->admin > 0 ? $this->admin : 0);
2313 $this->user_modification_id = $user->id;
2314
2315 $this->accountancy_code_user_general = trim((string) $this->accountancy_code_user_general);
2316 $this->accountancy_code = trim((string) $this->accountancy_code);
2317 $this->color = trim(str_replace('#', '', (string) $this->color));
2318 $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
2319 $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
2320
2321 $this->birth = empty($this->birth) ? '' : $this->birth;
2322 $this->fk_warehouse = (int) $this->fk_warehouse;
2323 $this->fk_establishment = (int) $this->fk_establishment;
2324
2325 $this->setUpperOrLowerCase();
2326
2327 // Check parameters
2328 $badCharUnauthorizedIntoLoginName = getDolGlobalLoginBadCharUnauthorized();
2329
2330 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
2331 $langs->load("errors");
2332 $this->error = $langs->trans("ErrorBadEMail", $this->email);
2333 return -1;
2334 }
2335 if (empty($this->login)) {
2336 $langs->load("errors");
2337 $this->error = $langs->trans("ErrorFieldRequired", 'Login');
2338 return -1;
2339 } elseif ($badCharUnauthorizedIntoLoginName !== '' && preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
2340 $langs->load("errors");
2341 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
2342 return -1;
2343 }
2344
2345 $this->db->begin();
2346
2347 // Check if login already exists in same entity or into entity 0.
2348 if (is_object($this->oldcopy) && !empty($this->oldcopy->id) && $this->oldcopy->login != $this->login) {
2349 $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)."'";
2350 $resqltochecklogin = $this->db->query($sqltochecklogin);
2351 if ($resqltochecklogin) {
2352 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2353 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2354 $langs->load("errors");
2355 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
2356 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2357 $this->db->rollback();
2358 return -1;
2359 }
2360 }
2361 }
2362 if (is_object($this->oldcopy) && !empty($this->oldcopy->id) && !empty($this->email) && $this->oldcopy->email != $this->email) {
2363 $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)."'";
2364 $resqltochecklogin = $this->db->query($sqltochecklogin);
2365 if ($resqltochecklogin) {
2366 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2367 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2368 $langs->load("errors");
2369 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
2370 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2371 $this->db->rollback();
2372 return -1;
2373 }
2374 }
2375 }
2376
2377 // Update data
2378 $sql = "UPDATE ".$this->db->prefix()."user SET";
2379 $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
2380 $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
2381 $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
2382 $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
2383 $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
2384 $sql .= ", employee = ".(int) $this->employee;
2385 $sql .= ", login = '".$this->db->escape($this->login)."'";
2386 $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
2387 $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' or 'other'
2388 $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
2389 if (!empty($user->admin)) {
2390 $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
2391 }
2392 $sql .= ", address = '".$this->db->escape($this->address)."'";
2393 $sql .= ", zip = '".$this->db->escape($this->zip)."'";
2394 $sql .= ", town = '".$this->db->escape($this->town)."'";
2395 $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : "null");
2396 $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : "null");
2397 $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
2398 $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
2399 $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
2400 $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
2401 $sql .= ", email = '".$this->db->escape($this->email)."'";
2402 $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
2403 $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
2404 $sql .= ", job = '".$this->db->escape($this->job)."'";
2405 $sql .= ", signature = '".$this->db->escape($this->signature)."'";
2406 $sql .= ", accountancy_code_user_general = '".$this->db->escape($this->accountancy_code_user_general)."'";
2407 $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
2408 $sql .= ", color = '".$this->db->escape($this->color)."'";
2409 $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
2410 $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
2411 $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2412 $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2413 $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2414 $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2415 $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2416 $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2417 $sql .= ", fk_user = ".($this->fk_user > 0 ? ((int) $this->fk_user) : "null");
2418 $sql .= ", fk_user_modif = ".($this->user_modification_id > 0 ? ((int) $this->user_modification_id) : "null");
2419 $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? ((int) $this->fk_user_expense_validator) : "null");
2420 $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? ((int) $this->fk_user_holiday_validator) : "null");
2421 if (isset($this->thm) || $this->thm != '') {
2422 $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2423 }
2424 if (isset($this->tjm) || $this->tjm != '') {
2425 $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2426 }
2427 if (isset($this->salary) || $this->salary != '') {
2428 $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2429 }
2430 if (isset($this->salaryextra) || $this->salaryextra != '') {
2431 $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2432 }
2433 $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2434 if (isModEnabled('multicompany') && !empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2435 // entity flag can be set/unset only by another superadmin user, and only when multicompany is enabled.
2436 // Without multicompany, entity must never be written here: fetch() forces an admin's entity to 0 in memory
2437 // (an admin is a global admin without multicompany), and persisting that would wrongly turn the user into
2438 // a "whole database" (entity 0) admin.
2439 $sql .= ", entity = ".((int) $this->entity);
2440 }
2441
2442 $sql .= ", default_range = ".($this->default_range > 0 ? ((int) $this->default_range) : 'null');
2443 $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? ((int) $this->default_c_exp_tax_cat) : 'null');
2444 $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? ((int) $this->fk_warehouse) : "null");
2445 $sql .= ", fk_establishment = ".($this->fk_establishment > 0 ? ((int) $this->fk_establishment) : "null");
2446 $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2447 $sql .= ", force_pass_change = ".($this->force_pass_change ? ((int) $this->force_pass_change) : "0");
2448 $sql .= " WHERE rowid = ".((int) $this->id);
2449
2450 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2451 $resql = $this->db->query($sql);
2452 if ($resql) {
2453 $nbrowsaffected += $this->db->affected_rows($resql);
2454
2455 // Update password
2456 if (!empty($this->pass)) {
2457 if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2458 // If a new value for password is set and different than the one encrypted into database
2459 $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2460 if (is_int($result) && $result < 0) {
2461 return -5;
2462 }
2463 }
2464 }
2465
2466 // If user is linked to a member, remove old link to this member
2467 if ($this->fk_member > 0) {
2468 dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2469 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2470 $resql = $this->db->query($sql);
2471 if (!$resql) {
2472 $this->error = $this->db->error();
2473 $this->db->rollback();
2474 return -5;
2475 }
2476 }
2477 // Set link to user
2478 dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2479 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2480 $resql = $this->db->query($sql);
2481 if (!$resql) {
2482 $this->error = $this->db->error();
2483 $this->db->rollback();
2484 return -5;
2485 }
2486
2487 if ($nbrowsaffected) { // If something has changed in data
2488 if ($this->fk_member > 0 && !$nosyncmember) {
2489 dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2490
2491 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2492
2493 // This user is linked with a member, so we also update member information
2494 // if this is an update.
2495 $adh = new Adherent($this->db);
2496 $result = $adh->fetch($this->fk_member);
2497
2498 if ($result > 0) {
2499 $adh->civility_code = $this->civility_code;
2500 $adh->firstname = $this->firstname;
2501 $adh->lastname = $this->lastname;
2502 $adh->login = $this->login;
2503 $adh->gender = $this->gender;
2504 $adh->birth = $this->birth;
2505
2506 $adh->pass = $this->pass;
2507
2508 $adh->address = $this->address;
2509 $adh->town = $this->town;
2510 $adh->zip = $this->zip;
2511 $adh->state_id = $this->state_id;
2512 $adh->country_id = $this->country_id;
2513
2514 $adh->email = $this->email;
2515
2516 $adh->socialnetworks = $this->socialnetworks;
2517
2518 $adh->phone = $this->office_phone;
2519 $adh->phone_mobile = $this->user_mobile;
2520
2521 $adh->default_lang = $this->lang;
2522
2523 $adh->user_id = $this->id;
2524 $adh->user_login = $this->login;
2525
2526 $result = $adh->update($user, 0, 1, 0);
2527 if ($result < 0) {
2528 $this->error = $adh->error;
2529 $this->errors = $adh->errors;
2530 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2531 $error++;
2532 }
2533 } elseif ($result < 0) {
2534 $this->error = $adh->error;
2535 $this->errors = $adh->errors;
2536 $error++;
2537 }
2538 }
2539
2540 if ($this->contact_id > 0 && !$nosynccontact) {
2541 dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2542
2543 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2544
2545 // This user is linked with a contact, so we also update contact information if this is an update.
2546 $tmpobj = new Contact($this->db);
2547 $result = $tmpobj->fetch($this->contact_id);
2548
2549 if ($result >= 0) {
2550 $tmpobj->civility_code = $this->civility_code;
2551 $tmpobj->firstname = $this->firstname;
2552 $tmpobj->lastname = $this->lastname;
2553 $tmpobj->login = $this->login;
2554 $tmpobj->gender = $this->gender;
2555 $tmpobj->birth = $this->birth;
2556
2557 //$tmpobj->pass=$this->pass;
2558
2559 $tmpobj->email = $this->email;
2560
2561 $tmpobj->socialnetworks = $this->socialnetworks;
2562
2563 $tmpobj->phone_pro = $this->office_phone;
2564 $tmpobj->phone_mobile = $this->user_mobile;
2565 $tmpobj->fax = $this->office_fax;
2566
2567 $tmpobj->default_lang = $this->lang;
2568
2569 $tmpobj->address = $this->address;
2570 $tmpobj->town = $this->town;
2571 $tmpobj->zip = $this->zip;
2572 $tmpobj->state_id = $this->state_id;
2573 $tmpobj->country_id = $this->country_id;
2574
2575 $tmpobj->user_id = $this->id;
2576 $tmpobj->user_login = $this->login;
2577
2578 $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2579 if ($result < 0) {
2580 $this->error = $tmpobj->error;
2581 $this->errors = $tmpobj->errors;
2582 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2583 $error++;
2584 }
2585 } else {
2586 $this->error = $tmpobj->error;
2587 $this->errors = $tmpobj->errors;
2588 $error++;
2589 }
2590 }
2591 }
2592
2593 $action = 'update';
2594
2595 // Actions on extra fields
2596 if (!$error) {
2597 $result = $this->insertExtraFields();
2598 if ($result < 0) {
2599 $error++;
2600 }
2601 }
2602
2603 if (!$error && !$notrigger) {
2604 // Call trigger
2605 $result = $this->call_trigger('USER_MODIFY', $user);
2606 if ($result < 0) {
2607 $error++;
2608 }
2609 // End call triggers
2610 }
2611
2612 if (!$error) {
2613 $this->db->commit();
2614 return $nbrowsaffected;
2615 } else {
2616 dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2617 $this->db->rollback();
2618 return -1;
2619 }
2620 } else {
2621 $this->error = $this->db->lasterror();
2622 $this->db->rollback();
2623 return -2;
2624 }
2625 }
2626
2627 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2634 public function update_last_login_date()
2635 {
2636 // phpcs:enable
2637 $now = dol_now();
2638
2639 $userremoteip = getUserRemoteIP();
2640
2641 $sql = "UPDATE ".$this->db->prefix()."user SET";
2642 $sql .= " datepreviouslogin = datelastlogin,";
2643 $sql .= " ippreviouslogin = iplastlogin,";
2644 $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2645 $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2646 $sql .= " tms = tms"; // The last update date must change because the last login date is updated
2647 $sql .= " WHERE rowid = ".((int) $this->id);
2648
2649 dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2650 $resql = $this->db->query($sql);
2651 if ($resql) {
2652 $this->datepreviouslogin = $this->datelastlogin;
2653 $this->datelastlogin = $now;
2654 $this->ippreviouslogin = $this->iplastlogin;
2655 $this->iplastlogin = $userremoteip;
2656 return 1;
2657 } else {
2658 $this->error = $this->db->lasterror().' sql='.$sql;
2659 return -1;
2660 }
2661 }
2662
2663
2676 public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2677 {
2678 global $conf, $langs;
2679 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2680
2681 $error = 0;
2682
2683 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2684
2685 // If new password not provided, we generate one
2686 if (!$password) {
2687 $password = getRandomPassword(false);
2688 $passwordalreadycrypted = 0; // Just generated, so not crypted
2689 }
2690
2691 // Check and encrypt the password
2692 if (!empty($passwordalreadycrypted)) {
2693 $password_crypted = $password; // Reuse crypted password
2694 } else {
2695 if (getDolGlobalString('USER_PASSWORD_GENERATED')) {
2696 // Add a check on rules for password syntax using the setup of the password generator
2697 $modGeneratePassClass = 'modGeneratePass'.ucfirst(getDolGlobalString('USER_PASSWORD_GENERATED'));
2698
2699 include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2700 if (class_exists($modGeneratePassClass)) {
2701 $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2702 '@phan-var-force ModeleGenPassword $modGeneratePass';
2703
2704 // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2705 $modGeneratePass->WithoutAmbi = 0;
2706
2707 // Call to validatePassword($password) to check pass match rules
2708 $testpassword = $modGeneratePass->validatePassword($password);
2709 if (!$testpassword) {
2710 $this->error = $modGeneratePass->error;
2711 return -1;
2712 }
2713 }
2714 }
2715
2716
2717 // Now, we encrypt the new password
2718 $password_crypted = (string) dol_hash($password);
2719 }
2720
2721 // Update password
2722 if (!$changelater) {
2723 if (!is_object($this->oldcopy)) {
2724 $this->oldcopy = clone $this;
2725 }
2726
2727 $now = dol_now();
2728
2729 $this->db->begin();
2730
2731 $sql = "UPDATE ".$this->db->prefix()."user";
2732 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2733 $sql .= " datelastpassvalidation = '".$this->db->idate(dol_now())."',";
2734 $sql .= " pass_temp = null,";
2735 $sql .= " force_pass_change = 0";
2736 if (!empty($flagdelsessionsbefore)) {
2737 $sql .= ", flagdelsessionsbefore = '".$this->db->idate($now - 5, 'gmt')."'";
2738 }
2739 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
2740 $sql .= ", pass = null";
2741 } else {
2742 $sql .= ", pass = '".$this->db->escape($password)."'";
2743 }
2744 $sql .= " WHERE rowid = ".((int) $this->id);
2745
2746 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2747
2748 $result = $this->db->query($sql);
2749 if ($result) {
2750 if ($this->db->affected_rows($result)) {
2751 $this->pass = $password;
2752 $this->pass_indatabase = $password;
2753 $this->pass_indatabase_crypted = (string) $password_crypted;
2754 $this->force_pass_change = 0;
2755
2756 if ($this->fk_member && !$nosyncmember) {
2757 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2758
2759 // This user is linked with a member, so we also update members information
2760 // if this is an update.
2761 $adh = new Adherent($this->db);
2762 $result = $adh->fetch($this->fk_member);
2763
2764 if ($result >= 0) {
2765 $result = $adh->setPassword($user, $this->pass, (!getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 0 : 1), 1); // The encryption is not managed in the 'adherent' module
2766 if (is_int($result) && $result < 0) {
2767 $this->error = $adh->error;
2768 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2769 $error++;
2770 }
2771 } else {
2772 $this->error = $adh->error;
2773 $error++;
2774 }
2775 }
2776
2777 dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2778
2779 // Call trigger for the "security events" log
2780 $user->context['audit'] = 'login='.$user->login;
2781 if (!empty($flagdelsessionsbefore)) {
2782 $user->context['audit'] .= " - flagdelsessionsbefore set to '".$this->db->idate($now - 5, 'gmt')."'";
2783 }
2784
2785 if (!$error && !$notrigger) {
2786 // Call trigger
2787 $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2788 if ($result < 0) {
2789 $error++;
2790 $this->db->rollback();
2791 return -1;
2792 }
2793 // End call triggers
2794 }
2795
2796 $this->db->commit();
2797 return $this->pass;
2798 } else {
2799 $this->db->rollback();
2800 return 0;
2801 }
2802 } else {
2803 $this->db->rollback();
2804 dol_print_error($this->db);
2805 return -1;
2806 }
2807 } else {
2808 // We store password in password temporary field.
2809 // After receiving confirmation link, we will erase and store it in pass_crypted
2810 $sql = "UPDATE ".$this->db->prefix()."user";
2811 $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2812 $sql .= " WHERE rowid = ".((int) $this->id);
2813
2814 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2815 $result = $this->db->query($sql);
2816 if ($result) {
2817 return $password;
2818 } else {
2819 dol_print_error($this->db);
2820 return -3;
2821 }
2822 }
2823 }
2824
2825 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2834 public function send_password($user, $password = '', $changelater = 0)
2835 {
2836 // phpcs:enable
2837 global $conf, $langs;
2839
2840 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2841
2842 $msgishtml = 0;
2843
2844 // Define $msg
2845 $mesg = '';
2846
2847 $outputlangs = new Translate("", $conf);
2848
2849 if (getDolGlobalString('MAIN_LANG_DEFAULT')) {
2850 $outputlangs->setDefaultLang(getDolGlobalString('MAIN_LANG_DEFAULT'));
2851 } else { // If user has not defined its own language, we used current language
2852 $outputlangs = $langs;
2853 }
2854
2855 // Load translation files required by the page
2856 $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2857
2858 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', constant('DOL_APPLICATION_TITLE'));
2859
2860 $subject = '['.$appli.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2861
2862 // Define $urlwithroot
2863 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2864 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2865
2866 if (!$changelater) {
2867 $url = $urlwithroot.'/';
2868 if (getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD')) {
2869 $url = getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD');
2870 }
2871
2872 dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2873
2874 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."\n";
2875 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2876 $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2877 $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2878 $mesg .= "\n";
2879
2880 $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2881 $mesg .= "--\n";
2882 $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2883 } else {
2884 //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2885 $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2886 $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2887 if (isModEnabled('multicompany')) {
2888 $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2889 }
2890
2891 dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2892
2893 $msgishtml = 1;
2894
2895 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2896 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2897 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2898 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2899 $mesg .= "<br>\n";
2900 $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2901 $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2902 $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2903 }
2904
2905 $trackid = 'use'.$this->id;
2906 $sendcontext = 'passwordreset';
2907
2908 $mailfile = new CMailFile(
2909 $subject,
2910 $this->email,
2911 getDolGlobalString("MAIN_MAIL_EMAIL_FROM_PASSWORDRESET", getDolGlobalString("MAIN_MAIL_EMAIL_FROM")),
2912 $mesg,
2913 array(),
2914 array(),
2915 array(),
2916 '',
2917 '',
2918 0,
2919 $msgishtml,
2920 '',
2921 '',
2922 $trackid,
2923 '',
2924 $sendcontext
2925 );
2926
2927 if ($mailfile->sendfile()) {
2928 return 1;
2929 } else {
2930 $langs->trans("errors");
2931 $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2932 return -1;
2933 }
2934 }
2935
2941 public function error()
2942 {
2943 return $this->error;
2944 }
2945
2946
2947 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2953 public function fetch_clicktodial()
2954 {
2955 // phpcs:enable
2956 $sql = "SELECT url, login, pass, poste ";
2957 $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2958 $sql .= " WHERE u.fk_user = ".((int) $this->id);
2959
2960 $resql = $this->db->query($sql);
2961 if ($resql) {
2962 if ($this->db->num_rows($resql)) {
2963 $obj = $this->db->fetch_object($resql);
2964
2965 $this->clicktodial_url = $obj->url;
2966 $this->clicktodial_login = $obj->login;
2967 $this->clicktodial_password = $obj->pass;
2968 $this->clicktodial_poste = $obj->poste;
2969 }
2970
2971 $this->clicktodial_loaded = 1; // Data loaded (found or not)
2972
2973 $this->db->free($resql);
2974 return 1;
2975 } else {
2976 $this->error = $this->db->error();
2977 return -1;
2978 }
2979 }
2980
2981 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2987 public function update_clicktodial()
2988 {
2989 // phpcs:enable
2990 $this->db->begin();
2991
2992 $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2993 $sql .= " WHERE fk_user = ".((int) $this->id);
2994
2995 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2996
2997 $result = $this->db->query($sql);
2998
2999 $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
3000 $sql .= " (fk_user,url,login,pass,poste)";
3001 $sql .= " VALUES (".((int) $this->id);
3002 $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
3003 $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
3004 $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
3005 $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
3006
3007 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
3008
3009 $result = $this->db->query($sql);
3010 if ($result) {
3011 $this->db->commit();
3012 return 1;
3013 } else {
3014 $this->db->rollback();
3015 $this->error = $this->db->lasterror();
3016 return -1;
3017 }
3018 }
3019
3020
3021 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3030 public function SetInGroup($group, $entity, $notrigger = 0)
3031 {
3032 // phpcs:enable
3033 global $langs, $user;
3034
3035 $error = 0;
3036
3037 $this->db->begin();
3038
3039 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
3040 $sql .= " WHERE fk_user = ".((int) $this->id);
3041 $sql .= " AND fk_usergroup = ".((int) $group);
3042 $sql .= " AND entity = ".((int) $entity);
3043
3044 $result = $this->db->query($sql);
3045
3046 $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
3047 $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
3048
3049 $result = $this->db->query($sql);
3050 if ($result) {
3051 if (!$error && !$notrigger) {
3052 $this->context = array('audit' => $langs->trans("UserSetInGroup"), 'newgroupid' => $group);
3053
3054 // Call trigger
3055 $result = $this->call_trigger('USER_MODIFY', $user);
3056 if ($result < 0) {
3057 $error++;
3058 }
3059 // End call triggers
3060 }
3061
3062 if (!$error) {
3063 $this->db->commit();
3064 return 1;
3065 } else {
3066 dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
3067 $this->db->rollback();
3068 return -2;
3069 }
3070 } else {
3071 $this->error = $this->db->lasterror();
3072 $this->db->rollback();
3073 return -1;
3074 }
3075 }
3076
3077 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3086 public function RemoveFromGroup($group, $entity, $notrigger = 0)
3087 {
3088 // phpcs:enable
3089 global $langs, $user;
3090
3091 $error = 0;
3092
3093 $this->db->begin();
3094
3095 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
3096 $sql .= " WHERE fk_user = ".((int) $this->id);
3097 $sql .= " AND fk_usergroup = ".((int) $group);
3098 if (empty($entity)) {
3099 $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
3100 } else {
3101 $sql .= " AND entity = ".((int) $entity);
3102 }
3103
3104 $result = $this->db->query($sql);
3105 if ($result) {
3106 if (!$error && !$notrigger) {
3107 $this->context = array('audit' => $langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
3108
3109 // Call trigger
3110 $result = $this->call_trigger('USER_MODIFY', $user);
3111 if ($result < 0) {
3112 $error++;
3113 }
3114 // End call triggers
3115 }
3116
3117 if (!$error) {
3118 $this->db->commit();
3119 return 1;
3120 } else {
3121 dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
3122 $this->db->rollback();
3123 return -2;
3124 }
3125 } else {
3126 $this->error = $this->db->lasterror();
3127 $this->db->rollback();
3128 return -1;
3129 }
3130 }
3131
3132
3140 {
3141 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3142
3143 $now = dol_now();
3144
3145 //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
3146
3147 // Check date start validity
3148 if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
3149 return 1;
3150 }
3151 // Check date end validity
3152 if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
3153 return 1;
3154 }
3155
3156 return 0;
3157 }
3158
3159
3171 public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
3172 {
3173 $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3174 $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
3175 $result .= '</a>';
3176
3177 return $result;
3178 }
3179
3186 public function getTooltipContentArray($params)
3187 {
3188 global $conf, $langs, $menumanager;
3189 global $dolibarr_main_demo;
3190
3191 $infologin = $params['infologin'] ?? 0;
3192 $option = $params['option'] ?? '';
3193
3194 $data = [];
3195 if (!empty($this->photo)) {
3196 $photo = '<div class="photointooltip floatright">';
3197 $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
3198 $photo .= '</div>';
3199 $data['photo'] = $photo;
3200 //$label .= '<div style="clear: both;"></div>';
3201 }
3202
3203 // Info Login
3204 $data['opendiv'] = '<div class="centpercent divtooltip">';
3205 $data['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
3206 $data['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs));
3207 if (!empty($this->login)) {
3208 $data['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
3209 }
3210 if (!empty($this->job)) {
3211 $data['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
3212 }
3213 $data['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
3214 if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
3215 $phonelist = array();
3216 if ($this->office_phone) {
3217 $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3218 }
3219 if ($this->office_fax) {
3220 $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3221 }
3222 if ($this->user_mobile) {
3223 $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3224 }
3225 $data['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
3226 }
3227 if (!empty($this->admin)) {
3228 $data['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
3229 }
3230 if (!empty($this->accountancy_code) || $option == 'accountancy') {
3231 $langs->load("companies");
3232 $data['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
3233 }
3234 $company = '';
3235 if (!empty($this->socid)) { // Add thirdparty for external users
3236 $thirdpartystatic = new Societe($this->db);
3237 $thirdpartystatic->fetch($this->socid);
3238 $companyimg = '';
3239 if (empty($params['hidethirdpartylogo'])) {
3240 $companyimg = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3241 }
3242 $company = ' ('.$langs->trans("Company").': '.($companyimg ? $companyimg : img_picto('', 'company')).' '.dol_string_nohtmltag($thirdpartystatic->name).')';
3243 }
3244 $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
3245 $data['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
3246 $data['closediv'] = '</div>';
3247
3248 if ($infologin > 0) {
3249 $data['newlinelogin'] = '<br>';
3250 $data['session'] = '<br><u>'.$langs->trans("Session").'</u>';
3251 $data['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
3252 if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
3253 $data['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
3254 }
3255 $data['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
3256 $data['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
3257 $data['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
3258 $data['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
3259 // @phan-suppress-next-line PhanRedefinedClassReference
3260 $data['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
3261 $s = picto_from_langcode($langs->getDefaultLang());
3262 $data['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
3263 $data['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
3264 $data['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
3265 $data['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
3266 if ($conf->browser->layout == 'phone') {
3267 $data['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
3268 }
3269 if (!empty($_SESSION["disablemodules"])) {
3270 $data['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(implode(', ', explode(',', $_SESSION["disablemodules"])));
3271 }
3272 }
3273
3274 return $data;
3275 }
3276
3292 public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
3293 {
3294 global $langs, $hookmanager, $user;
3295
3296 if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
3297 $option = 'nolink';
3298 }
3299
3300 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
3301 $withpictoimg = 0;
3302 }
3303
3304 $result = '';
3305 $params = [
3306 'id' => $this->id,
3307 'objecttype' => $this->element,
3308 'infologin' => $infologin,
3309 'option' => $option,
3310 'hidethirdpartylogo' => $hidethirdpartylogo,
3311 ];
3312 $classfortooltip = 'classfortooltip';
3313 $dataparams = '';
3314 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3315 $classfortooltip = 'classforajaxtooltip';
3316 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3317 $label = '';
3318 } else {
3319 $label = implode($this->getTooltipContentArray($params));
3320 }
3321
3322 $companylink = '';
3323 if (!empty($this->socid)) { // Add thirdparty for external users
3324 $thirdpartystatic = new Societe($this->db);
3325 $thirdpartystatic->fetch($this->socid);
3326 if (empty($hidethirdpartylogo)) {
3327 $companylink = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3328 }
3329 }
3330
3331 if ($infologin < 0) {
3332 $label = '';
3333 }
3334
3335 $baseurl = DOL_URL_ROOT . '/user/card.php';
3336 if ($option == 'leave') {
3337 $baseurl = DOL_URL_ROOT . '/holiday/list.php';
3338 }
3339 $query = ['id' => $this->id];
3340 if ($option != 'nolink') {
3341 // Add param to save lastsearch_values or not
3342 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3343 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3344 $add_save_lastsearch_values = 1;
3345 }
3346 if ($add_save_lastsearch_values) {
3347 $query = array_merge($query, ['save_lastsearch_values' => 1]);
3348 }
3349 }
3350 $url = dolBuildUrl($baseurl, $query);
3351
3352 $linkstart = '<a href="'.$url.'"';
3353 $linkclose = "";
3354 if (empty($notooltip)) {
3355 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3356 $langs->load("users");
3357 $label = $langs->trans("ShowUser");
3358 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3359 }
3360 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3361 $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
3362 } else {
3363 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
3364 }
3365
3366 $linkstart .= $linkclose.'>';
3367 $linkend = '</a>';
3368
3369 //if ($withpictoimg == -1) $result.='<div class="nowrap">';
3370 $result .= (($option == 'nolink') ? '' : $linkstart);
3371 if ($withpictoimg) {
3372 $paddafterimage = '';
3373 if (abs((int) $withpictoimg) == 1 || abs((int) $withpictoimg) == 4) {
3374 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3375 }
3376 // Only picto
3377 if ($withpictoimg > 0) {
3378 $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>';
3379 } else {
3380 // Picto must be a photo
3381 $picto = '<!-- picto photo user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'"'.($paddafterimage ? ' '.$paddafterimage : '').'>';
3382 $picto .= Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto'.(($withpictoimg == -3 || $withpictoimg == -4) ? 'small' : ''), 'mini', 0, 1);
3383 $picto .= '</span>';
3384 }
3385 $result .= $picto;
3386 }
3387
3388 if ($withpictoimg == -4 || ($withpictoimg > -2 && $withpictoimg != 2)) {
3389 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3390 $result .= '<span class="nopadding usertext'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
3391 }
3392 if ($mode == 'login') {
3393 $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
3394 } else {
3395 $result .= dol_string_nohtmltag($this->getFullName($langs, 0, ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
3396 }
3397 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3398 $result .= '</span>';
3399 }
3400 }
3401 $result .= (($option == 'nolink') ? '' : $linkend);
3402 //if ($withpictoimg == -1) $result.='</div>';
3403
3404 $result .= $companylink;
3405
3406 global $action;
3407 $hookmanager->initHooks(array('userdao'));
3408 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
3409 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3410 if ($reshook > 0) {
3411 $result = $hookmanager->resPrint;
3412 } else {
3413 $result .= $hookmanager->resPrint;
3414 }
3415
3416 return $result;
3417 }
3418
3428 public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
3429 {
3430 global $langs, $user;
3431
3432 $result = '';
3433
3434 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3435 $linkend = '</a>';
3436
3437 //Check user's rights to see an other user
3438 if ((!$user->hasRight('user', 'user', 'lire') && $this->id != $user->id)) {
3439 $option = 'nolink';
3440 }
3441
3442 if ($option == 'xxx') {
3443 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3444 $linkend = '</a>';
3445 }
3446
3447 if ($option == 'nolink') {
3448 $linkstart = '';
3449 $linkend = '';
3450 }
3451
3452 $result .= $linkstart;
3453 if ($withpictoimg) {
3454 $paddafterimage = '';
3455 if (abs($withpictoimg) == 1) {
3456 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3457 }
3458 // Only picto
3459 if ($withpictoimg > 0) {
3460 $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3461 } else {
3462 // Picto must be a photo
3463 $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>';
3464 }
3465 $result .= $picto;
3466 }
3467 $result .= $this->login;
3468 $result .= $linkend;
3469
3470 return $result;
3471 }
3472
3479 public function getLibStatut($mode = 0)
3480 {
3481 return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3482 }
3483
3484 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3492 public function LibStatut($status, $mode = 0)
3493 {
3494 // phpcs:enable
3495 global $langs;
3496
3497 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3498 global $langs;
3499 //$langs->load("mymodule");
3500 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3501 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3502 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3503 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3504 }
3505
3506 $statusType = 'status5';
3507 if ($status == self::STATUS_ENABLED) {
3508 $statusType = 'status4';
3509 }
3510
3511 $label = $this->labelStatus[$status];
3512 $labelshort = $this->labelStatusShort[$status];
3513
3514 $now = dol_now();
3515 if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3516 $statusType = 'status3';
3517 $label .= ' ('.$langs->trans("UserNotYetValid").')';
3518 }
3519 if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3520 $statusType = 'status2';
3521 $label .= ' ('.$langs->trans("UserExpired").')';
3522 }
3523
3524 return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3525 }
3526
3527
3535 public function getKanbanView($option = '', $arraydata = null)
3536 {
3537 global $langs;
3538
3539 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3540
3541 $return = '<div class="box-flex-item box-flex-grow-zero">';
3542 $return .= '<div class="info-box info-box-sm">';
3543 $return .= '<span class="info-box-icon bg-infobox-action">';
3544
3545 $label = '';
3546 if (!empty($this->photo)) {
3547 //$label .= '<div class="photointooltip floatright">';
3548 $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
3549 //$label .= '</div>';
3550 //$label .= '<div style="clear: both;"></div>';
3551 $return .= $label;
3552 } else {
3553 $return .= img_picto('', $this->picto);
3554 }
3555
3556 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3557 $return .= '</span>';
3558 $return .= '<div class="info-box-content">';
3559 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3560 if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3561 $return .= img_picto($langs->trans("SuperAdministratorDesc"), 'superadmin', 'class="valignmiddle paddingright paddingleft"');
3562 } elseif ($this->admin) {
3563 $return .= img_picto($langs->trans("AdministratorDesc"), 'admin', 'class="valignmiddle paddingright paddingleft"');
3564 }
3565 $return .= '</span>';
3566 if ($selected >= 0) {
3567 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3568 }
3569 if (property_exists($this, 'label')) {
3570 $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3571 }
3572 if ($this->email) {
3573 $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3574 }
3575 if (method_exists($this, 'getLibStatut')) {
3576 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3577 }
3578 $return .= '</div>';
3579 $return .= '</div>';
3580 $return .= '</div>';
3581
3582 return $return;
3583 }
3584
3585
3586 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3587 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3597 public function _load_ldap_dn($info, $mode = 0)
3598 {
3599 // phpcs:enable
3600 global $conf;
3601 $dn = '';
3602 if ($mode == 0) {
3603 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')]."," . getDolGlobalString('LDAP_USER_DN');
3604 } elseif ($mode == 1) {
3605 $dn = getDolGlobalString('LDAP_USER_DN');
3606 } elseif ($mode == 2) {
3607 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')];
3608 }
3609 return $dn;
3610 }
3611
3612 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3613 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3619 public function _load_ldap_info()
3620 {
3621 // phpcs:enable
3622 global $conf, $langs;
3623
3624 $info = array();
3625
3626 $socialnetworks = getArrayOfSocialNetworks();
3627
3628 $keymodified = false;
3629
3630 // Object classes
3631 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_USER_OBJECT_CLASS'));
3632
3633 $this->fullname = $this->getFullName($langs);
3634
3635 // Possible LDAP KEY (constname => varname)
3636 $ldapkey = array(
3637 'LDAP_FIELD_FULLNAME' => 'fullname',
3638 'LDAP_FIELD_NAME' => 'lastname',
3639 'LDAP_FIELD_FIRSTNAME' => 'firstname',
3640 'LDAP_FIELD_LOGIN' => 'login',
3641 'LDAP_FIELD_LOGIN_SAMBA' => 'login',
3642 'LDAP_FIELD_PHONE' => 'office_phone',
3643 'LDAP_FIELD_MOBILE' => 'user_mobile',
3644 'LDAP_FIELD_FAX' => 'office_fax',
3645 'LDAP_FIELD_MAIL' => 'email',
3646 'LDAP_FIELD_SID' => 'ldap_sid',
3647 );
3648
3649 // Champs
3650 foreach ($ldapkey as $constname => $varname) {
3651 if (!empty($this->$varname) && getDolGlobalString($constname)) {
3652 $info[getDolGlobalString($constname)] = $this->$varname;
3653
3654 // Check if it is the LDAP key and if its value has been changed
3655 if (getDolGlobalString('LDAP_KEY_USERS') && getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString($constname)) {
3656 if (is_object($this->oldcopy) && !empty($this->oldcopy->id) && $this->$varname != $this->oldcopy->$varname) {
3657 $keymodified = true; // For check if LDAP key has been modified
3658 }
3659 }
3660 }
3661 }
3662 foreach ($socialnetworks as $key => $value) {
3663 if (!empty($this->socialnetworks[$value['label']]) && getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))) {
3664 $info[getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3665 }
3666 }
3667 if ($this->address && getDolGlobalString('LDAP_FIELD_ADDRESS')) {
3668 $info[getDolGlobalString('LDAP_FIELD_ADDRESS')] = $this->address;
3669 }
3670 if ($this->zip && getDolGlobalString('LDAP_FIELD_ZIP')) {
3671 $info[getDolGlobalString('LDAP_FIELD_ZIP')] = $this->zip;
3672 }
3673 if ($this->town && getDolGlobalString('LDAP_FIELD_TOWN')) {
3674 $info[getDolGlobalString('LDAP_FIELD_TOWN')] = $this->town;
3675 }
3676 if ($this->note_public && getDolGlobalString('LDAP_FIELD_DESCRIPTION')) {
3677 $info[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_public, 2);
3678 }
3679 if ($this->socid > 0 && getDolGlobalString('LDAP_FIELD_COMPANY')) {
3680 $soc = new Societe($this->db);
3681 $soc->fetch($this->socid);
3682
3683 $info[getDolGlobalString('LDAP_FIELD_COMPANY')] = $soc->name;
3684 if ($soc->client == 1) {
3685 $info["businessCategory"] = "Customers";
3686 }
3687 if ($soc->client == 2) {
3688 $info["businessCategory"] = "Prospects";
3689 }
3690 if ($soc->fournisseur == 1) {
3691 $info["businessCategory"] = "Suppliers";
3692 }
3693 }
3694
3695 // When password is modified
3696 if (!empty($this->pass)) {
3697 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3698 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass; // this->pass = unencrypted password
3699 }
3700 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3701 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3702 }
3703 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3704 // Set LDAP password if possible
3705 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3706 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
3707 // Just for the default MD5 !
3708 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) {
3709 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3710 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3711 }
3712 }
3713 } elseif (!empty($this->pass_indatabase)) {
3714 // Use $this->pass_indatabase value if exists
3715 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3716 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = unencrypted password
3717 }
3718 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3719 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3720 }
3721 }
3722 }
3723
3724 if (getDolGlobalString('LDAP_SERVER_TYPE') == 'egroupware') {
3725 $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3726
3727 $info['uidnumber'] = $this->id;
3728
3729 $info['phpgwTz'] = 0;
3730 $info['phpgwMailType'] = 'INTERNET';
3731 $info['phpgwMailHomeType'] = 'INTERNET';
3732
3733 $info["phpgwContactTypeId"] = 'n';
3734 $info["phpgwContactCatId"] = 0;
3735 $info["phpgwContactAccess"] = "public";
3736
3737 $info["phpgwContactOwner"] = 1;
3738
3739 if ($this->email) {
3740 $info["rfc822Mailbox"] = $this->email;
3741 }
3742 if ($this->user_mobile) {
3743 $info["phpgwCellTelephoneNumber"] = $this->user_mobile;
3744 }
3745 }
3746
3747 if (getDolGlobalString('LDAP_FIELD_USERID')) {
3748 $info[getDolGlobalString('LDAP_FIELD_USERID')] = $this->id;
3749 }
3750 if (getDolGlobalString('LDAP_FIELD_GROUPID')) {
3751 $usergroup = new UserGroup($this->db);
3752 $groupslist = $usergroup->listGroupsForUser($this->id);
3753 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = '65534';
3754 if (!empty($groupslist)) {
3755 foreach ($groupslist as $groupforuser) {
3756 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = $groupforuser->id; //Select first group in list
3757 break;
3758 }
3759 }
3760 }
3761 if (getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY') && getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')) {
3762 $info[getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY')] = getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')."/".$this->login;
3763 }
3764
3765 return $info;
3766 }
3767
3768
3776 public function initAsSpecimen()
3777 {
3778 global $user;
3779
3780 $now = dol_now();
3781
3782 // Initialise parameters
3783 $this->id = 0;
3784 $this->ref = 'SPECIMEN';
3785 $this->specimen = 1;
3786 $this->user_creation_id = $user->id;
3787
3788 $this->lastname = 'DOLIBARR';
3789 $this->firstname = 'SPECIMEN';
3790 $this->gender = 'man';
3791 $this->note_public = 'This is a note public';
3792 $this->note_private = 'This is a note private';
3793 $this->email = 'email@specimen.com';
3794 $this->personal_email = 'personalemail@specimen.com';
3795 $this->socialnetworks = array(
3796 'skype' => 'skypepseudo',
3797 'twitter' => 'twitterpseudo',
3798 'facebook' => 'facebookpseudo',
3799 'linkedin' => 'linkedinpseudo',
3800 );
3801 $this->office_phone = '0999999999';
3802 $this->office_fax = '0999999998';
3803 $this->user_mobile = '0999999997';
3804 $this->personal_mobile = '0999999996';
3805 $this->admin = 0;
3806 $this->login = 'dolibspec';
3807 $this->pass = 'dolibSpec+@123';
3808 //$this->pass_indatabase='dolibspec'; Set after a fetch
3809 //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3810 $this->datec = $now;
3811 $this->datem = $now;
3812
3813 $this->datelastlogin = $now;
3814 $this->iplastlogin = '127.0.0.1';
3815 $this->datepreviouslogin = $now;
3816 $this->ippreviouslogin = '127.0.0.1';
3817 $this->status = 1;
3818
3819 $this->entity = 1;
3820
3821 return 1;
3822 }
3823
3830 public function info($id)
3831 {
3832 $sql = "SELECT u.rowid, u.login as ref, u.datec, fk_user_creat as user_creation_id, fk_user_modif as user_modification_id,";
3833 $sql .= " GREATEST(u.tms, COALESCE(uef.tms, u.tms)) as date_modification, u.entity";
3834 $sql .= " FROM ".$this->db->prefix()."user as u";
3835 $sql .= " LEFT JOIN ".$this->db->prefix()."user_extrafields as uef ON uef.fk_object = u.rowid";
3836 $sql .= " WHERE u.rowid = ".((int) $id);
3837
3838 $result = $this->db->query($sql);
3839 if ($result) {
3840 if ($this->db->num_rows($result)) {
3841 $obj = $this->db->fetch_object($result);
3842
3843 $this->id = $obj->rowid;
3844
3845 $this->user_creation_id = $obj->user_creation_id;
3846 $this->user_modification_id = $obj->user_modification_id;
3847
3848 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3849 $this->date_creation = $this->db->jdate($obj->datec);
3850 $this->date_modification = $this->db->jdate($obj->date_modification);
3851 $this->entity = $obj->entity;
3852 }
3853
3854 $this->db->free($result);
3855 } else {
3856 dol_print_error($this->db);
3857 }
3858 }
3859
3860
3866 public function getNbOfEMailings()
3867 {
3868 $sql = "SELECT count(mc.email) as nb";
3869 $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3870 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3871 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
3872
3873 $resql = $this->db->query($sql);
3874 if ($resql) {
3875 $obj = $this->db->fetch_object($resql);
3876 $nb = (int) $obj->nb;
3877
3878 $this->db->free($resql);
3879 return $nb;
3880 } else {
3881 $this->error = $this->db->error();
3882 return -1;
3883 }
3884 }
3885
3894 public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3895 {
3896 $sql = "SELECT count(rowid) as nb";
3897 $sql .= " FROM ".$this->db->prefix()."user";
3898 if ($option == 'superadmin') {
3899 $sql .= " WHERE entity = 0";
3900 } else {
3901 $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3902 if ($limitTo == 'active') {
3903 $sql .= " AND statut = 1";
3904 }
3905 }
3906 if ($admin >= 0) {
3907 $sql .= " AND admin = ".(int) $admin;
3908 }
3909
3910 $resql = $this->db->query($sql);
3911 if ($resql) {
3912 $obj = $this->db->fetch_object($resql);
3913 $nb = (int) $obj->nb;
3914
3915 $this->db->free($resql);
3916 return $nb;
3917 } else {
3918 $this->error = $this->db->lasterror();
3919 return -1;
3920 }
3921 }
3922
3923 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3930 public function update_ldap2dolibarr(&$ldapuser)
3931 {
3932 // phpcs:enable
3933 // TODO: See why the update sets all values to empty (does global $user overwrite?)
3934 global $user;
3935
3936 $socialnetworks = getArrayOfSocialNetworks();
3937
3938 $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3939 $this->firstname = $ldapuser->$tmpvar;
3940 $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3941 $this->lastname = $ldapuser->$tmpvar;
3942 $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3943 $this->login = $ldapuser->$tmpvar;
3944 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3945 $this->pass = $ldapuser->$tmpvar;
3946 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3947 $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3948
3949 $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3950 $this->office_phone = $ldapuser->$tmpvar;
3951 $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3952 $this->user_mobile = $ldapuser->$tmpvar;
3953 $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3954 $this->office_fax = $ldapuser->$tmpvar;
3955 $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3956 $this->email = $ldapuser->$tmpvar;
3957 foreach ($socialnetworks as $key => $value) {
3958 $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3959 $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3960 }
3961 $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3962 $this->ldap_sid = $ldapuser->$tmpvar;
3963
3964 $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3965 $this->job = $ldapuser->$tmpvar;
3966 $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3967 $this->note_public = $ldapuser->$tmpvar;
3968
3969 $result = $this->update($user);
3970
3971 dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3972
3973 return $result;
3974 }
3975
3976
3977 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3984 public function get_children()
3985 {
3986 // phpcs:enable
3987 $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3988 $sql .= " WHERE fk_user = ".((int) $this->id);
3989
3990 dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3991 $res = $this->db->query($sql);
3992 if ($res) {
3993 $users = array();
3994 while ($rec = $this->db->fetch_array($res)) {
3995 $user = new User($this->db);
3996 $user->fetch($rec['rowid']);
3997 $users[] = $user;
3998 }
3999 return $users;
4000 } else {
4001 dol_print_error($this->db);
4002 return -1;
4003 }
4004 }
4005
4006
4012 private function loadParentOf()
4013 {
4014 $this->parentof = array();
4015
4016 // Load array[child]=parent
4017 $sql = "SELECT fk_user as id_parent, rowid as id_son";
4018 $sql .= " FROM ".$this->db->prefix()."user";
4019 $sql .= " WHERE fk_user <> 0";
4020 $sql .= " AND entity IN (".getEntity('user').")";
4021
4022 dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
4023 $resql = $this->db->query($sql);
4024 if ($resql) {
4025 while ($obj = $this->db->fetch_object($resql)) {
4026 $this->parentof[$obj->id_son] = $obj->id_parent;
4027 }
4028 return 1;
4029 } else {
4030 dol_print_error($this->db);
4031 return -1;
4032 }
4033 }
4034
4035 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4049 public function get_full_tree($deleteafterid = 0, $filter = '')
4050 {
4051 // phpcs:enable
4052 global $hookmanager;
4053
4054 // Actions hooked (by external module)
4055 $hookmanager->initHooks(array('userdao'));
4056
4057 $this->users = array();
4058
4059 // Init this->parentof that is array(id_son=>id_parent, ...)
4060 $this->loadParentOf();
4061
4062 // Init $this->users array
4063 $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
4064 $sql .= " FROM ".$this->db->prefix()."user as u";
4065 // Add fields from hooks
4066 $parameters = array();
4067 $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
4068 if ($reshook > 0) {
4069 $sql .= $hookmanager->resPrint;
4070 } else {
4071 $sql .= " WHERE u.entity IN (".getEntity('user').")";
4072 }
4073 if ($filter) {
4074 $sql .= forgeSQLFromUniversalSearchCriteria($filter);
4075 }
4076
4077 dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
4078 $resql = $this->db->query($sql);
4079 if ($resql) {
4080 $i = 0;
4081 while ($obj = $this->db->fetch_object($resql)) {
4082 $this->users[(int) $obj->rowid]
4083 = array(
4084 'rowid' => (int) $obj->rowid,
4085 'id' => (int) $obj->rowid,
4086 'fk_user' => (int) $obj->fk_user,
4087 'fk_soc' => (int) $obj->fk_soc,
4088 'firstname' => (string) $obj->firstname,
4089 'lastname' => (string) $obj->lastname,
4090 'login' => (string) $obj->login,
4091 'statut' => (int) $obj->statut,
4092 'entity' => (int) $obj->entity,
4093 'email' => (string) $obj->email,
4094 'gender' => (string) $obj->gender,
4095 'admin' => (int) $obj->admin,
4096 'photo' => (string) $obj->photo,
4097 // fields are filled with build_path_from_id_user
4098 'fullpath' => '',
4099 'fullname' => '',
4100 'level' => 0,
4101 );
4102 $i++;
4103 }
4104 } else {
4105 dol_print_error($this->db);
4106 return -1;
4107 }
4108
4109 // We add the fullpath property to each element of the first level (no parent exists)
4110 dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
4111 foreach ($this->users as $key => $val) {
4112 $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
4113 if ($result < 0) {
4114 $this->error = 'ErrorLoopInHierarchy';
4115 return -1;
4116 }
4117 }
4118
4119 // Exclude leaf including $deleteafterid from tree
4120 if ($deleteafterid) {
4121 //print "Look to discard user ".$deleteafterid."\n";
4122 $keyfilter1 = '^'.$deleteafterid.'$';
4123 $keyfilter2 = '_'.$deleteafterid.'$';
4124 $keyfilter3 = '^'.$deleteafterid.'_';
4125 $keyfilter4 = '_'.$deleteafterid.'_';
4126 foreach (array_keys($this->users) as $key) {
4127 $fullpath = (string) $this->users[$key]['fullpath'];
4128 if (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
4129 || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath)) {
4130 unset($this->users[$key]);
4131 }
4132 }
4133 }
4134
4135 dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
4136 $this->users = dol_sort_array($this->users, 'fullname', 'asc', 1, 0, 1);
4137
4138 return $this->users;
4139 }
4140
4149 public function getAllChildIds($addcurrentuser = 0)
4150 {
4151 $childids = array();
4152
4153 if (isset($this->cache_childids[$this->id])) {
4154 $childids = $this->cache_childids[$this->id];
4155 } else {
4156 // Init this->users
4157 $treeresult = $this->get_full_tree();
4158
4159 $idtoscan = $this->id;
4160
4161 dol_syslog("Build childid for id = ".$idtoscan);
4162 foreach ($this->users as $id => $val) {
4163 if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
4164 $childids[$val['id']] = $val['id'];
4165 }
4166 }
4167
4168 // A loop anywhere in the hierarchy aborts get_full_tree(), leaving the branches it had not
4169 // walked yet with an empty fullpath, so they silently drop out of the list above. Do not
4170 // cache such a truncated result, it would be reused for the whole request.
4171 if ($treeresult < 0) {
4172 dol_syslog(get_class($this)."::getAllChildIds got a truncated tree: ".$this->error, LOG_WARNING);
4173 return $addcurrentuser ? array($this->id => $this->id) : $childids;
4174 }
4175 }
4176 $this->cache_childids[$this->id] = $childids;
4177
4178 if ($addcurrentuser) {
4179 $childids[$this->id] = $this->id;
4180 }
4181
4182 return $childids;
4183 }
4184
4185 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4194 public function build_path_from_id_user($id_user, $protection = 0)
4195 {
4196 // phpcs:enable
4197 //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
4198
4199 if (!empty($this->users[$id_user]['fullpath'])) {
4200 // Already defined
4201 dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
4202 return 0;
4203 }
4204
4205 // Define fullpath and fullname
4206 $this->users[$id_user]['fullpath'] = '_'.$id_user;
4207 $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
4208 $i = 0;
4209 $cursor_user = $id_user;
4210
4211 $useridfound = array($id_user);
4212 while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) { // @phan-suppress-current-line PhanTypeMismatchProperty
4213 if (in_array($this->parentof[$cursor_user], $useridfound)) {
4214 dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
4215 return -1; // Should not happen. Protection against looping hierarchy
4216 }
4217 $useridfound[] = $this->parentof[$cursor_user];
4218 $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
4219 $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
4220 $i++;
4221 $cursor_user = $this->parentof[$cursor_user];
4222 }
4223
4224 // We count number of _ to have level
4225 $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
4226
4227 return 1;
4228 }
4229
4238 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4239 {
4240 $tables = array(
4241 'user',
4242 );
4243
4244 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4245 }
4246
4247
4253 public function loadStateBoard()
4254 {
4255 $this->nb = array();
4256
4257 $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
4258 $sql .= " FROM ".$this->db->prefix()."user as u";
4259 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4260 $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
4261 $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
4262 $sql .= " AND ug.fk_user = u.rowid";
4263 } else {
4264 $sql .= " WHERE u.entity IN (".getEntity('user').")";
4265 }
4266 $sql .= " AND u.statut > 0";
4267 //$sql.= " AND employee != 0";
4268
4269 $resql = $this->db->query($sql);
4270 if ($resql) {
4271 while ($obj = $this->db->fetch_object($resql)) {
4272 $this->nb["users"] = $obj->nb;
4273 }
4274 $this->db->free($resql);
4275 return 1;
4276 } else {
4277 dol_print_error($this->db);
4278 $this->error = $this->db->error();
4279 return -1;
4280 }
4281 }
4282
4294 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4295 {
4296 global $langs;
4297
4298 $langs->load("user");
4299
4300 // Set the '$modele' to the name of the document template (model) to use
4301 if (!dol_strlen($modele)) {
4302 if (getDolGlobalString('USER_ADDON_PDF')) {
4303 $modele = getDolGlobalString('USER_ADDON_PDF');
4304 } else {
4305 $modele = 'bluesky';
4306 }
4307 }
4308
4309 $modelpath = "core/modules/user/doc/";
4310
4311 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4312 }
4313
4314 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4322 public function user_get_property($rowid, $mode)
4323 {
4324 // phpcs:enable
4325 $user_property = '';
4326
4327 if (empty($rowid)) {
4328 return '';
4329 }
4330
4331 $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
4332 $sql .= " FROM ".$this->db->prefix()."user";
4333 $sql .= " WHERE rowid = ".((int) $rowid);
4334
4335 $resql = $this->db->query($sql);
4336 if ($resql) {
4337 $nump = $this->db->num_rows($resql);
4338
4339 if ($nump) {
4340 $obj = $this->db->fetch_object($resql);
4341
4342 if ($mode == 'email') {
4343 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
4344 } elseif ($mode == 'mobile') {
4345 $user_property = $obj->user_mobile;
4346 } elseif ($mode == 'name') {
4347 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname);
4348 }
4349 }
4350 return $user_property;
4351 } else {
4352 dol_print_error($this->db);
4353 }
4354
4355 return '';
4356 }
4357
4365 public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
4366 {
4368 global $conf;
4369
4370 $instanceuniqueid = empty($conf->file->instance_unique_id) ? '' : $conf->file->instance_unique_id;
4371 $encodedsecurekey = dol_hash($instanceuniqueid.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
4372 if (isModEnabled('multicompany')) {
4373 $entity_qr = '&entity='.((int) $conf->entity);
4374 } else {
4375 $entity_qr = '';
4376 }
4377 // Define $urlwithroot
4378 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
4379 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
4380 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
4381
4382 if ($typeofurl == 'internal') {
4383 $urlwithroot = DOL_URL_ROOT;
4384 }
4385
4386 return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
4387 }
4388
4402 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND', $entityfilter = false)
4403 {
4404 global $conf, $user;
4405
4406 $sql = "SELECT t.rowid";
4407 $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
4408
4409 if ($entityfilter) {
4410 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4411 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
4412 $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
4413 } else {
4414 $sql .= " WHERE t.entity = 0 OR EXISTS (";
4415 $sql .= " SELECT ug.rowid FROM " . $this->db->prefix() . "usergroup_user as ug";
4416 $sql .= " WHERE ug.fk_user = t.rowid AND ug.entity IN (" . getEntity('usergroup') . "))";
4417 }
4418 } else {
4419 $sql .= " WHERE t.entity IN (".getEntity('user').")";
4420 }
4421 } else {
4422 $sql .= " WHERE 1 = 1";
4423 }
4424
4425 // Manage filter
4426 $errormessage = '';
4427 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
4428 if ($errormessage) {
4429 $this->errors[] = $errormessage;
4430 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
4431 return -1;
4432 }
4433
4434 $sql .= $this->db->order($sortfield, $sortorder);
4435 if ($limit) {
4436 $sql .= $this->db->plimit($limit + 1, $offset);
4437 }
4438
4439 dol_syslog(__METHOD__, LOG_DEBUG);
4440
4441 $resql = $this->db->query($sql);
4442 if ($resql) {
4443 $this->users = array();
4444 $num = $this->db->num_rows($resql);
4445 if ($num) {
4446 while ($obj = $this->db->fetch_object($resql)) {
4447 $line = new self($this->db);
4448 $result = $line->fetch($obj->rowid);
4449 if ($result > 0 && !empty($line->id)) {
4450 $this->users[$obj->rowid] = clone $line;
4451 }
4452 }
4453 $this->db->free($resql);
4454 }
4455 return $num;
4456 } else {
4457 $this->errors[] = $this->db->lasterror();
4458 return -1;
4459 }
4460 }
4461
4469 private $findUserIdByEmailCache;
4470
4481 public function findUserIdByEmail($email)
4482 {
4483 if (isset($this->findUserIdByEmailCache[$email])) {
4484 return $this->findUserIdByEmailCache[$email];
4485 }
4486
4487 $this->findUserIdByEmailCache[$email] = -1;
4488
4489 $sql = 'SELECT rowid';
4490 $sql .= ' FROM '.$this->db->prefix().'user';
4491 if (getDolGlobalString('AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR')) {
4492 $sql .= " WHERE email LIKE '%".$this->db->escape($this->db->escapeforlike($email))."%'";
4493 } else {
4494 $sql .= " WHERE email = '".$this->db->escape($email)."'";
4495 }
4496 $sql .= ' LIMIT 1';
4497
4498 $resql = $this->db->query($sql);
4499 if (!$resql) {
4500 return -1;
4501 }
4502
4503 $obj = $this->db->fetch_object($resql);
4504 if (!$obj) {
4505 return -1;
4506 }
4507
4508 $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4509
4510 return $this->findUserIdByEmailCache[$email];
4511 }
4512
4519 public function cloneRights($fromId, $toId)
4520 {
4521 if (empty($fromId) || empty($toId)) {
4522 return -1;
4523 }
4524
4525 $this->db->begin();
4526
4527 // delete default rights for UserTo
4528 $sqlDelete = "DELETE FROM ".$this->db->prefix()."user_rights";
4529 $sqlDelete .= " WHERE fk_user = ".((int) $toId);
4530
4531 dol_syslog(get_class($this)."::clone_rights (delete default permissions)", LOG_DEBUG);
4532
4533 if (!$this->db->query($sqlDelete)) {
4534 $this->db->rollback();
4535 return -1;
4536 }
4537
4538 // Construction of the insertion request
4539 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id)";
4540 $sql .= " SELECT entity, ".((int) $toId).", fk_id";
4541 $sql .= " FROM ".$this->db->prefix()."user_rights src";
4542 $sql .= " WHERE fk_user = ".((int) $fromId);
4543 $sql .= " AND NOT EXISTS (";
4544 $sql .= " SELECT 1";
4545 $sql .= " FROM ".$this->db->prefix()."user_rights dest";
4546 $sql .= " WHERE dest.entity = src.entity";
4547 $sql .= " AND dest.fk_user = ".((int) $toId);
4548 $sql .= " AND dest.fk_id = src.fk_id";
4549 $sql .= " )";
4550
4551 dol_syslog(get_class($this)."::clone_rights", LOG_DEBUG);
4552
4553 // Execute request
4554 if (!$this->db->query($sql)) {
4555 $this->db->rollback();
4556 return -1;
4557 }
4558
4559 $this->db->commit();
4560 return 1;
4561 }
4562
4571 public function cloneCategories($fromId, $toId, $type = 'user')
4572 {
4573 $this->db->begin();
4574
4575 if (empty($type)) {
4576 $type = $this->table_element;
4577 }
4578
4579 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4580 $categorystatic = new Categorie($this->db);
4581
4582 $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_user)";
4583 $sql .= " SELECT fk_categorie, ".((int) $toId)." FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
4584 $sql .= " WHERE fk_user = ".((int) $fromId);
4585
4586 if (!$this->db->query($sql)) {
4587 $this->error = $this->db->lasterror();
4588 $this->db->rollback();
4589 return -1;
4590 }
4591
4592 $this->db->commit();
4593 return 1;
4594 }
4595}
global $dolibarr_main_url_root
$c
Definition line.php:334
$object ref
Definition info.php:90
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.
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, $usesharelinkifavailable=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, ...)
setForcePasswordChange($user, $value)
Set force password change flag.
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()
Returns the last functional error when manipulating the object.
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.
isExternalUser()
Return if a user is an external user It replaces old syntax: if ($user->socid)
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.
_load_ldap_dn($info, $mode=0)
Returns the complete DN (Distinguished Name) string in the LDAP directory for the object.
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.
isAdmin()
Return if a user is an admin user It replaces old syntax: if ($user->admin)
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.
loadPersonalConf($entity=-1)
Load const values from database table user_param and set it into user->conf->XXX.
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:169
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
global $mysoc
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:680
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:666
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").
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
dol_now($mode='gmt')
Return date for now.
getDolGlobalLoginBadCharUnauthorized()
Return the list of unauthorized characters in user logins.
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.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
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.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getUserRemoteIP($trusted=0)
Return the real IP of remote user.
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.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
div refaddress div address
conf($dolibarr_main_document_root, $realpathconf=null)
Load conf file (file must exists)
Definition inc.php:429
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dolGetLdapPasswordHash($password, $type='md5')
Returns a specific ldap hash of a password.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.
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='', $obfuscationmode='dolcrypt')
Encode a string with a symmetric encryption.