dolibarr 25.0.0-alpha
user.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (c) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
4 * Copyright (c) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
7 * Copyright (C) 2005-2024 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2005 Lionel Cousteix <etm_ltd@tiscali.co.uk>
9 * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
10 * Copyright (C) 2013-2019 Philippe Grand <philippe.grand@atoo-net.com>
11 * Copyright (C) 2013-2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
12 * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
13 * Copyright (C) 2018 charlene Benke <charlie@patas-monkey.com>
14 * Copyright (C) 2018-2021 Nicolas ZABOURI <info@inovea-conseil.com>
15 * Copyright (C) 2019-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 * Copyright (C) 2026 Anthony Berton <anthony.berton@bb2a.fr>
20 *
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 3 of the License, or
24 * (at your option) any later version.
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <https://www.gnu.org/licenses/>.
33 */
34
41require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
42require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
43require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
44require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
45
46
50class User extends CommonObject
51{
52 use CommonPeople;
53
57 public $element = 'user';
58
62 public $table_element = 'user';
63
67 public $fk_element = 'fk_user';
68
72 public $picto = 'user';
73
77 public $id = 0;
78
84 public $statut;
85
89 public $status;
90
94 public $openid;
95
99 public $ldap_sid;
103 public $search_sid;
107 public $employee;
111 public $civility_code;
112
116 public $fullname;
117
121 public $gender;
122
126 public $birth;
127
131 public $email;
132
136 public $email_oauth2;
137
141 public $personal_email;
142
146 public $socialnetworks;
147
151 public $job;
152
156 public $signature;
157
161 public $office_phone;
162
166 public $office_fax;
167
171 public $user_mobile;
172
176 public $personal_mobile;
177
181 public $admin;
182
186 public $login;
187
191 public $api_key;
192
196 public $pass;
197
201 public $pass_crypted;
202
206 public $pass_indatabase;
207
211 public $pass_indatabase_crypted;
212
216 public $pass_temp;
217
221 public $force_pass_change = 0;
222
228 public $datec;
229
235 public $datem;
236
240 public $socid;
241
245 public $contact_id;
246
250 public $fk_member;
251
255 public $fk_user;
256
260 public $fk_user_expense_validator;
261
265 public $fk_user_holiday_validator;
266
270 public $clicktodial_url;
271
275 public $clicktodial_login;
276
280 public $clicktodial_password;
281
285 public $clicktodial_poste;
286
290 public $clicktodial_loaded;
291
292
296 public $datelastpassvalidation;
300 public $datelastlogin;
304 public $datepreviouslogin;
308 public $flagdelsessionsbefore;
312 public $iplastlogin;
316 public $ippreviouslogin;
320 public $datestartvalidity;
324 public $dateendvalidity;
325
329 public $photo;
330
334 public $lang;
335
339 public $rights;
340
344 public $all_permissions_are_loaded;
345
349 public $nb_rights;
350
354 public $user_group_list;
355
359 public $usergroup_entity;
360
364 private $_tab_loaded = array();
365
369 public $conf;
370
374 public $default_values; // To store default values for user. Loaded by loadDefaultValues().
375
379 public $lastsearch_values_tmp; // To store current search criteria for user
383 public $lastsearch_values; // To store last saved search criteria for user
384
388 public $users = array();
392 public $parentof; // To store an array of all parents for all ids.
396 private $cache_childids; // Cache array of already loaded children
397
402 public $accountancy_code_user_general; // Accountancy code in prevision of the complete accountancy module
403
407 public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
408
412 public $thm; // Average cost of employee - Used for valuation of time spent
416 public $tjm; // Average cost of employee
417
421 public $salary; // Monthly salary - Denormalized value from llx_user_employment
425 public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment
429 public $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment
430
434 public $color;
435
439 public $dateemployment; // Define date of employment by company
443 public $dateemploymentend; // Define date of employment end by company
444
448 public $default_c_exp_tax_cat;
449
453 public $ref_employee;
454
458 public $national_registration_number;
459
463 public $default_range;
464
469 public $fk_warehouse;
470
474 public $fk_establishment;
475
479 public $label_establishment;
480
485 public $fields = array(
486 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
487 'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 20, 'searchall' => 1),
488 'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1),
489 'fk_warehouse' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php', 'label' => 'Warehouse', 'enabled' => "isModEnabled('stock')", 'visible' => 1, 'notnull' => 0, 'showoncombobox' => 1, 'index' => 1, 'position' => 50, 'searchall' => 1, 'bi' => 0),
490 'ref_employee' => array('type' => 'varchar(50)', 'label' => 'RefEmployee', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 30, 'searchall' => 1),
491 'national_registration_number' => array('type' => 'varchar(50)', 'label' => 'NationalRegistrationNumber', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 40, 'searchall' => 1)
492 );
493
494 const STATUS_DISABLED = 0;
495 const STATUS_ENABLED = 1;
496
502 public function __construct($db)
503 {
504 $this->db = $db;
505
506 $this->ismultientitymanaged = 1;
507 $this->isextrafieldmanaged = 1;
508 // User preference
509 $this->clicktodial_loaded = 0;
510
511 // For cache usage
512 $this->all_permissions_are_loaded = 0;
513 $this->nb_rights = 0;
514
515 // Force some default values
516 $this->admin = 0;
517 $this->employee = 1;
518
519 $this->conf = new stdClass();
520 $this->rights = new stdClass();
521 $this->rights->user = new stdClass();
522 $this->rights->user->user = new stdClass();
523 $this->rights->user->self = new stdClass();
524 $this->rights->user->user_advance = new stdClass();
525 $this->rights->user->self_advance = new stdClass();
526 $this->rights->user->group_advance = new stdClass();
527 }
528
543 public function fetch($id = 0, $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1, $email = '', $fk_socpeople = 0, $use_email_oauth2 = 0)
544 {
545 global $conf, $user;
546
547 // Clean parameters
548 $login = trim($login);
549
550 // Get user
551 $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.civility as civility_code, u.birth, u.job,";
552 $sql .= " u.email, u.email_oauth2, u.personal_email,";
553 $sql .= " u.socialnetworks,";
554 $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile, u.personal_mobile,";
555 $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
556 $sql .= " u.admin, u.login, u.note_private, u.note_public,";
557 $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.force_pass_change, u.api_key,";
558 $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,";
559 $sql .= " fk_user_creat as user_creation_id, fk_user_modif as user_modification_id,";
560 $sql .= " u.statut as status, u.lang, u.entity,";
561 $sql .= " u.datec as datec,";
562 $sql .= " GREATEST(u.tms, COALESCE(uef.tms, u.tms)) as datem,";
563 $sql .= " u.datelastlogin as datel,";
564 $sql .= " u.datepreviouslogin as datep,";
565 $sql .= " u.flagdelsessionsbefore,";
566 $sql .= " u.iplastlogin,";
567 $sql .= " u.ippreviouslogin,";
568 $sql .= " u.datelastpassvalidation,";
569 $sql .= " u.datestartvalidity,";
570 $sql .= " u.dateendvalidity,";
571 $sql .= " u.photo as photo,";
572 $sql .= " u.openid as openid,";
573 $sql .= " u.accountancy_code_user_general,";
574 $sql .= " u.accountancy_code,";
575 $sql .= " u.thm,";
576 $sql .= " u.tjm,";
577 $sql .= " u.salary,";
578 $sql .= " u.salaryextra,";
579 $sql .= " u.weeklyhours,";
580 $sql .= " u.color,";
581 $sql .= " u.dateemployment, u.dateemploymentend,";
582 $sql .= " u.fk_warehouse,";
583 $sql .= " u.ref_ext,";
584 $sql .= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode
585 $sql .= " u.national_registration_number,";
586 $sql .= " u.ref_employee,";
587 $sql .= " c.code as country_code, c.label as country,";
588 $sql .= " d.code_departement as state_code, d.nom as state,";
589 $sql .= " s.label as label_establishment, u.fk_establishment";
590 $sql .= " FROM ".$this->db->prefix()."user as u";
591 $sql .= " LEFT JOIN ".$this->db->prefix()."user_extrafields as uef ON uef.fk_object = u.rowid";
592 $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as c ON u.fk_country = c.rowid";
593 $sql .= " LEFT JOIN ".$this->db->prefix()."c_departements as d ON u.fk_state = d.rowid";
594 $sql .= " LEFT JOIN ".$this->db->prefix()."establishment as s ON u.fk_establishment = s.rowid";
595
596 if ($id > 0) {
597 $sql .= " WHERE u.rowid = ".((int) $id);
598 } else {
599 if ($entity < 0) {
600 if ((! isModEnabled('multicompany') || ! getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) && (! empty($user->entity))) {
601 $sql .= " WHERE u.entity IN (0, " . ((int) $conf->entity) . ")";
602 } else {
603 $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
604 }
605 } else {
606 // The fetch was forced on an entity
607 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
608 $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
609 } else {
610 if ($entity != '' && $entity == 0) { // If $entity = 0
611 $sql .= " WHERE u.entity = 0";
612 } else { // if $entity is -1 or > 0
613 $sql .= " WHERE u.entity IN (0, " . ((int) ($entity > 0 ? ((int) $entity) : ((int) $conf->entity))) . ")";
614 }
615 }
616 }
617 }
618
619 if ($sid) {
620 // allows searching for the user by their ActiveDirectory or Samba SID
621 $sql .= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."')";
622 } elseif ($login) {
623 $sql .= " AND u.login = '".$this->db->escape($login)."'";
624 } elseif ($email) {
625 $sql .= " AND (u.email = '".$this->db->escape($email)."'";
626 if ($use_email_oauth2) {
627 $sql .= " OR u.email_oauth2 = '".$this->db->escape($email)."'";
628 }
629 $sql .= ")";
630 } elseif ($fk_socpeople > 0) {
631 $sql .= " AND u.fk_socpeople = ".((int) $fk_socpeople);
632 }
633
634 $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
635
636 if ($sid) {
637 // allows searching for the user by their ActiveDirectory or Samba SID
638 $sql .= ' '.$this->db->plimit(1);
639 }
640
641 $resql = $this->db->query($sql);
642 if ($resql) {
643 $num = $this->db->num_rows($resql);
644 if ($num > 1) {
645 $this->error = "USERDUPLICATEFOUND";
646 dol_syslog(get_class($this)."::fetch more than 1 user found", LOG_WARNING);
647
648 $this->db->free($resql);
649 return 0;
650 }
651
652 $obj = $this->db->fetch_object($resql);
653 if ($obj) {
654 $this->id = $obj->rowid;
655 $this->ref = $obj->rowid;
656
657 $this->ref_ext = $obj->ref_ext;
658
659 $this->ldap_sid = $obj->ldap_sid;
660 $this->civility_code = $obj->civility_code;
661 $this->lastname = $obj->lastname;
662 $this->firstname = $obj->firstname;
663 $this->ref_employee = $obj->ref_employee;
664 $this->national_registration_number = $obj->national_registration_number;
665
666 $this->employee = $obj->employee;
667
668 $this->login = $obj->login;
669 $this->gender = $obj->gender;
670 $this->birth = $this->db->jdate($obj->birth);
671 $this->pass_indatabase = $obj->pass;
672 $this->pass_indatabase_crypted = $obj->pass_crypted;
673 $this->pass = $obj->pass;
674 $this->pass_temp = $obj->pass_temp;
675
676 $this->force_pass_change = $obj->force_pass_change;
677 $this->datelastpassvalidation = $this->db->jdate($obj->datelastpassvalidation);
678
679 $this->api_key = dolDecrypt($obj->api_key);
680
681 $this->address = $obj->address;
682 $this->zip = $obj->zip;
683 $this->town = $obj->town;
684
685 $this->country_id = $obj->country_id;
686 $this->country_code = $obj->country_id ? $obj->country_code : '';
687 //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
688
689 $this->state_id = $obj->state_id;
690 $this->state_code = $obj->state_code;
691 $this->state = ($obj->state != '-' ? $obj->state : '');
692
693 $this->office_phone = $obj->office_phone;
694 $this->office_fax = $obj->office_fax;
695 $this->user_mobile = $obj->user_mobile;
696 $this->personal_mobile = $obj->personal_mobile;
697 $this->email = $obj->email;
698 $this->email_oauth2 = $obj->email_oauth2;
699 $this->personal_email = $obj->personal_email;
700 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
701 $this->user_creation_id = $obj->user_creation_id;
702 $this->user_modification_id = $obj->user_modification_id;
703
704 $this->job = $obj->job;
705 $this->signature = $obj->signature;
706 $this->admin = $obj->admin;
707 $this->note_public = $obj->note_public;
708 $this->note_private = $obj->note_private;
709
710 $this->statut = $obj->status; // deprecated
711 $this->status = $obj->status;
712
713 $this->photo = $obj->photo;
714 $this->openid = $obj->openid;
715 $this->lang = $obj->lang;
716 $this->entity = $obj->entity;
717
718 $this->accountancy_code_user_general = $obj->accountancy_code_user_general;
719 $this->accountancy_code = $obj->accountancy_code;
720
721 $this->thm = $obj->thm;
722 $this->tjm = $obj->tjm;
723 $this->salary = $obj->salary;
724 $this->salaryextra = $obj->salaryextra;
725 $this->weeklyhours = $obj->weeklyhours;
726 $this->color = $obj->color;
727 $this->dateemployment = $this->db->jdate($obj->dateemployment);
728 $this->dateemploymentend = $this->db->jdate($obj->dateemploymentend);
729
730 $this->datec = $this->db->jdate($obj->datec);
731 $this->datem = $this->db->jdate($obj->datem);
732 $this->datelastlogin = $this->db->jdate($obj->datel);
733 $this->datepreviouslogin = $this->db->jdate($obj->datep);
734 $this->flagdelsessionsbefore = $this->db->jdate($obj->flagdelsessionsbefore, 'gmt');
735 $this->iplastlogin = $obj->iplastlogin;
736 $this->ippreviouslogin = $obj->ippreviouslogin;
737 $this->datestartvalidity = $this->db->jdate($obj->datestartvalidity);
738 $this->dateendvalidity = $this->db->jdate($obj->dateendvalidity);
739
740 $this->socid = $obj->fk_soc;
741 $this->contact_id = $obj->fk_socpeople;
742 $this->fk_member = $obj->fk_member;
743 $this->fk_user = $obj->fk_user;
744 $this->fk_user_expense_validator = $obj->fk_user_expense_validator;
745 $this->fk_user_holiday_validator = $obj->fk_user_holiday_validator;
746
747 $this->default_range = $obj->default_range;
748 $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
749 $this->fk_warehouse = $obj->fk_warehouse;
750 $this->warehouse_id = $obj->fk_warehouse; // To avoid that some code use $user->warehouse when it is not loaded. It must be loaded with $user->fetch_warehouse() before.
751 $this->warehouse = null; // To avoid that some code use $user->warehouse when it is not loaded. It must be loaded with $user->fetch_warehouse() before.
752 $this->fk_establishment = $obj->fk_establishment;
753 $this->label_establishment = $obj->label_establishment;
754
755 // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
756 // in such case, this admin user must be admin for ALL entities.
757 if (!isModEnabled('multicompany') && $this->admin && $this->entity == 1) {
758 $this->entity = 0;
759 }
760
761 // If user is linked to a warehouse, we load it into memory
762 if (isModEnabled('stock') && getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && (!empty($this->fk_warehouse) || !empty($this->warehouse_id))) {
763 $this->fetchWarehouse();
764 }
765 // Retrieve all extrafield
766 // fetch optionals attributes and labels
767 $this->fetch_optionals();
768
769 $this->db->free($resql);
770 } else {
771 $this->error = "USERNOTFOUND";
772 dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
773
774 $this->db->free($resql);
775 return 0;
776 }
777 } else {
778 $this->error = $this->db->lasterror();
779 return -1;
780 }
781
782 // To get back the global configuration unique to the user
783 if ($loadpersonalconf) {
784 $result = $this->loadPersonalConf($entity);
785
786 $result = $this->loadDefaultValues();
787
788 if ($result < 0) {
789 $this->error = $this->db->lasterror();
790 return -3;
791 }
792 }
793
794 // Add option to allow an admin internal user to make quick debug for internal users. Not yet implemented completely.
795 // This is a special cas that is allowed to have a GETPOST inside a class.
796 if (GETPOSTINT('forceexternaluser') && $this->admin && empty($this->socid)) {
797 $this->socid = GETPOSTINT('forceexternaluser');
798 }
799
800 return 1;
801 }
802
803
810 public function loadPersonalConf($entity = -1)
811 {
812 global $conf;
813
814 // Load user->conf for user
815 $sql = "SELECT param, value FROM ".$this->db->prefix()."user_param";
816 $sql .= " WHERE fk_user = ".((int) $this->id);
817 if ($entity < 0) {
818 $sql .= " AND entity IN (0, ".((int) $conf->entity).")"; // IN (0, x)
819 } else {
820 $sql .= " AND entity = ".((int) $entity); // 0 or x
821 }
822
823 //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
824 $resql = $this->db->query($sql);
825 if ($resql) {
826 $num = $this->db->num_rows($resql);
827 $i = 0;
828 while ($i < $num) {
829 $obj = $this->db->fetch_object($resql);
830 $p = (!empty($obj->param) ? $obj->param : '');
831 if (!empty($p)) {
832 $this->conf->$p = $obj->value;
833 }
834 $i++;
835 }
836 $this->db->free($resql);
837
838 return $num;
839 } else {
840 $this->error = $this->db->lasterror();
841
842 return -2;
843 }
844 }
845
851 public function loadDefaultValues()
852 {
853 global $conf;
854
855 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
856 // Load user->default_values for user. TODO Save this in memcached ?
857 require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php';
858
859 $defaultValues = new DefaultValues($this->db);
860 $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)
861 //$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)
862
863 if (!is_array($result) && $result < 0) {
864 $this->error = $defaultValues->error;
865 $this->errors = $defaultValues->errors;
866 dol_print_error($this->db);
867 return -1;
868 } elseif (count($result) > 0) {
869 foreach ($result as $defval) {
870 if (!empty($defval->page) && !empty($defval->type) && !empty($defval->param)) {
871 $pagewithoutquerystring = $defval->page;
872 $pagequeries = '';
873 $reg = array();
874 if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
875 $pagewithoutquerystring = $reg[1];
876 $pagequeries = $reg[2];
877 }
878 $this->default_values[$pagewithoutquerystring][$defval->type][$pagequeries ? $pagequeries : '_noquery_'][$defval->param] = $defval->value;
879 }
880 }
881 }
882 if (!empty($this->default_values)) {
883 foreach ($this->default_values as $a => $b) {
884 foreach ($b as $c => $d) {
885 krsort($this->default_values[$a][$c]);
886 }
887 }
888 }
889 }
890 return 1;
891 }
892
899 public function isAdmin()
900 {
901 return $this->admin;
902 }
903
910 public function isExternalUser()
911 {
912 return $this->socid;
913 }
914
926 public function hasRight($module, $permlevel1, $permlevel2 = '')
927 {
928 // For compatibility with bad naming permissions on module
929 $moduletomoduletouse = array(
930 'category' => 'categorie',
931 'compta' => 'comptabilite',
932 'contract' => 'contrat',
933 'member' => 'adherent',
934 'mo' => 'mrp',
935 'order' => 'commande',
936 'produit' => 'product',
937 'productlot' => 'product',
938 'project' => 'projet',
939 'propale' => 'propal',
940 'shipping' => 'expedition',
941 'task' => 'task@projet',
942 'fichinter' => 'ficheinter',
943 'intervention' => 'ficheinter',
944 'inventory' => 'stock',
945 'invoice' => 'facture',
946 'invoice_supplier' => 'facture@fournisseur',
947 'order_supplier' => 'fournisseur',
948 'knowledgerecord' => 'knowledgerecord@knowledgemanagement',
949 'skill@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
950 'job@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
951 'position@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
952 'facturerec' => 'facture',
953 'margins' => 'margin',
954 );
955
956 if (!empty($moduletomoduletouse[$module])) {
957 $module = $moduletomoduletouse[$module];
958 }
959
960 // Compatibility layer for the supplier module split transition (MAIN_USE_NEW_SUPPLIERMOD).
961 // Allows both old and new permission syntaxes to work in parallel during migration.
962 // - Old: $user->hasRight('fournisseur', 'commande', 'lire')
963 // - New: $user->hasRight('supplier_order', 'lire')
964 // External modules are also transparently supported without any change on their side.
965 if (getDolGlobalInt('MAIN_USE_NEW_SUPPLIERMOD')) {
966 // New module names introduced by the split, mapped to their legacy equivalent.
967 // Format: 'new_module' => ['legacy_module', 'legacy_permlevel1']
968 $supplierNewToLegacy = array(
969 'supplier_order' => array('fournisseur', 'commande'),
970 'supplier_invoice' => array('fournisseur', 'facture'),
971 );
972
973 if (isset($supplierNewToLegacy[$module])) {
974 // Caller used new syntax: rewrite to legacy so the rights object resolves correctly.
975 // e.g. hasRight('supplier_order', 'lire') -> hasRight('fournisseur', 'commande', 'lire')
976 $permlevel2 = $permlevel1;
977 $permlevel1 = $supplierNewToLegacy[$module][1]; // e.g. 'commande'
978 $module = $supplierNewToLegacy[$module][0]; // e.g. 'fournisseur'
979 }
980 } else {
981 // Legacy mode: translate new module names back to old ones in case some
982 // updated code calls the new syntax while the option is not yet enabled.
983 $supplierLegacyCompat = array(
984 'supplier_order' => 'fournisseur',
985 'supplier_invoice' => 'fournisseur',
986 );
987
988 if (isset($supplierLegacyCompat[$module])) {
989 // e.g. hasRight('supplier_order', 'lire') stays routed through 'fournisseur'
990 $module = $supplierLegacyCompat[$module];
991 }
992 }
993
994 $moduleRightsMapping = array(
995 'product' => 'produit',
996 'margin' => 'margins',
997 'comptabilite' => 'compta'
998 );
999
1000 $rightsPath = $module;
1001 if (!empty($moduleRightsMapping[$rightsPath])) {
1002 $rightsPath = $moduleRightsMapping[$rightsPath];
1003 }
1004
1005 // If module is abc@module, we check permission user->hasRight(module, abc, permlevel1)
1006 $tmp = explode('@', $rightsPath, 2);
1007 if (!empty($tmp[1])) {
1008 if (strpos($module, '@') !== false) {
1009 $module = $tmp[1];
1010 }
1011 if ($tmp[0] != $tmp[1]) {
1012 // If $module = 'myobject@mymodule'
1013 $rightsPath = $tmp[1];
1014 $permlevel2 = $permlevel1;
1015 $permlevel1 = $tmp[0];
1016 } else {
1017 // If $module = 'abc@abc'
1018 $rightsPath = $tmp[1];
1019 }
1020 }
1021
1022 // In $conf->modules, we have 'accounting', 'product', 'facture', ...
1023 // In $user->rights, we have 'accounting', 'produit', 'facture', ...
1024
1025 if (!isModEnabled($module)) {
1026 return 0;
1027 }
1028
1029 // Special case for external user
1030 if (!empty($this->socid)) {
1031 if ($module == 'societe' && ($permlevel1 == 'creer' || $permlevel1 == 'write')) {
1032 return 0; // An external user never has the permission ->societe->write to see all thirdparties (always restricted to himself)
1033 }
1034 if ($module == 'societe' && $permlevel1 == 'client' && $permlevel2 == 'voir') {
1035 return 0; // An external user never has the permission ->societe->client->voir to see all thirdparties (always restricted to himself)
1036 }
1037 if ($module == 'societe' && $permlevel1 == 'export') {
1038 return 0; // An external user never has the permission ->societe->export to see all thirdparties (always restricted to himself)
1039 }
1040 if ($module == 'societe' && ($permlevel1 == 'supprimer' || $permlevel1 == 'delete')) {
1041 return 0; // An external user never has the permission ->societe->delete to see all thirdparties (always restricted to himself)
1042 }
1043 }
1044
1045 // For compatibility with bad naming permissions on permlevel1
1046 if ($permlevel1 == 'propale') {
1047 $permlevel1 = 'propal';
1048 }
1049 if ($permlevel1 == 'member') {
1050 $permlevel1 = 'adherent';
1051 }
1052 if ($permlevel1 == 'recruitmentcandidature') {
1053 $permlevel1 = 'recruitmentjobposition';
1054 }
1055
1056 if (empty($rightsPath) || empty($this->rights) || empty($this->rights->$rightsPath) || empty($permlevel1)) {
1057 return 0;
1058 }
1059
1060 if ($permlevel2) {
1061 if (!empty($this->rights->$rightsPath->$permlevel1)) {
1062 if (!empty($this->rights->$rightsPath->$permlevel1->$permlevel2)) {
1063 return $this->rights->$rightsPath->$permlevel1->$permlevel2;
1064 }
1065 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
1066 // instead of "read", "write", "delete"
1067 if ($permlevel2 == 'read' && !empty($this->rights->$rightsPath->$permlevel1->lire)) {
1068 return $this->rights->$rightsPath->$permlevel1->lire;
1069 }
1070 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->creer)) {
1071 return $this->rights->$rightsPath->$permlevel1->creer;
1072 }
1073 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->create)) {
1074 return $this->rights->$rightsPath->$permlevel1->create;
1075 }
1076 if ($permlevel2 == 'delete' && !empty($this->rights->$rightsPath->$permlevel1->supprimer)) {
1077 return $this->rights->$rightsPath->$permlevel1->supprimer;
1078 }
1079 }
1080 } else {
1081 if (!empty($this->rights->$rightsPath->$permlevel1)) {
1082 return $this->rights->$rightsPath->$permlevel1;
1083 }
1084 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
1085 // instead of "read", "write", "delete"
1086 if ($permlevel1 == 'read' && !empty($this->rights->$rightsPath->lire)) {
1087 return $this->rights->$rightsPath->lire;
1088 }
1089 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->creer)) {
1090 return $this->rights->$rightsPath->creer;
1091 }
1092 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->create)) {
1093 return $this->rights->$rightsPath->create;
1094 }
1095 if ($permlevel1 == 'delete' && !empty($this->rights->$rightsPath->supprimer)) {
1096 return $this->rights->$rightsPath->supprimer;
1097 }
1098 }
1099
1100 return 0;
1101 }
1102
1114 public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1115 {
1116 global $conf, $user, $langs;
1117
1118 $entity = (empty($entity) ? $conf->entity : $entity);
1119
1120 dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity, $notrigger for user id=".$this->id);
1121
1122 if (empty($this->id)) {
1123 $this->error = 'Try to call addrights on an object user with an empty id';
1124 return -1;
1125 }
1126
1127 $error = 0;
1128 $whereforadd = '';
1129
1130 $this->db->begin();
1131
1132 if (!empty($rid)) {
1133 $module = $perms = $subperms = '';
1134
1135 // If we ask to add a given permission, we first load properties of this permission (module, perms and subperms).
1136 $sql = "SELECT module, perms, subperms";
1137 $sql .= " FROM ".$this->db->prefix()."rights_def";
1138 $sql .= " WHERE id = ".((int) $rid);
1139 $sql .= " AND entity = ".((int) $entity);
1140
1141 $result = $this->db->query($sql);
1142 if ($result) {
1143 $obj = $this->db->fetch_object($result);
1144
1145 if ($obj) {
1146 $module = $obj->module;
1147 $perms = $obj->perms;
1148 $subperms = $obj->subperms;
1149 }
1150 } else {
1151 $error++;
1152 dol_print_error($this->db);
1153 }
1154
1155 // Define the where for the permission to add
1156 $whereforadd = "id=".((int) $rid);
1157 // Add also inherited permissions
1158 if (!empty($subperms)) {
1159 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))";
1160 } elseif (!empty($perms)) {
1161 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND (subperms IS NULL or subperms = ''))";
1162 }
1163 } else {
1164 // A list of permission was requested (not a single specific permission)
1165 // based on the name of a module of permissions
1166 // Used in the where clause to determine the list of permissions to add.
1167 if (!empty($allmodule)) {
1168 if ($allmodule == 'allmodules') {
1169 $whereforadd = 'allmodules';
1170 } else {
1171 $whereforadd = "module='".$this->db->escape($allmodule)."'";
1172 if (!empty($allperms)) {
1173 $whereforadd .= " AND perms='".$this->db->escape($allperms)."'";
1174 }
1175 }
1176 }
1177 }
1178
1179 // Add automatically other permission using the criteria whereforadd
1180 // $whereforadd can be a SQL filter or the string 'allmodules'
1181 if (!empty($whereforadd)) {
1182 //print "$module-$perms-$subperms";
1183 $sql = "SELECT id";
1184 $sql .= " FROM ".$this->db->prefix()."rights_def";
1185 $sql .= " WHERE entity = ".((int) $entity);
1186 if (!empty($whereforadd) && $whereforadd != 'allmodules') {
1187 $sql .= " AND (".$whereforadd.")"; // Note: parenthesis are important because whereforadd can contains OR. Also note that $whereforadd is already sanitized
1188 }
1189
1190 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1191 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1192 $sqldelete .= $sql;
1193 $sqldelete .= ") AND entity = ".((int) $entity);
1194 if (!$this->db->query($sqldelete)) {
1195 $error++;
1196 }
1197
1198 if (!$error) {
1199 $resql = $this->db->query($sql);
1200 if ($resql) {
1201 $num = $this->db->num_rows($resql);
1202 $i = 0;
1203 while ($i < $num) {
1204 $obj = $this->db->fetch_object($resql);
1205
1206 if ($obj) {
1207 $nid = $obj->id;
1208
1209 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id) VALUES (".((int) $entity).", ".((int) $this->id).", ".((int) $nid).")";
1210 if (!$this->db->query($sql)) {
1211 $error++;
1212 }
1213 }
1214
1215 $i++;
1216 }
1217 } else {
1218 $error++;
1219 dol_print_error($this->db);
1220 }
1221 }
1222 }
1223
1224 if (!$error && !$notrigger) {
1225 $langs->load("other");
1226 $this->context = array('audit' => $langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : ''));
1227
1228 // Call trigger
1229 $result = $this->call_trigger('USER_MODIFY', $user);
1230 if ($result < 0) {
1231 $error++;
1232 }
1233 // End call triggers
1234 }
1235
1236 if ($error) {
1237 $this->db->rollback();
1238 return -$error;
1239 } else {
1240 $this->db->commit();
1241 return 1;
1242 }
1243 }
1244
1245
1257 public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1258 {
1259 global $conf, $user, $langs;
1260
1261 $error = 0;
1262 $wherefordel = '';
1263 $entity = (!empty($entity) ? $entity : $conf->entity);
1264
1265 $this->db->begin();
1266
1267 if (!empty($rid)) {
1268 $module = $perms = $subperms = '';
1269
1270 // When the request is to delete a specific permissions, this gets the
1271 // characteristics for the module, permissions and sub-permission of this permission.
1272 $sql = "SELECT module, perms, subperms";
1273 $sql .= " FROM ".$this->db->prefix()."rights_def";
1274 $sql .= " WHERE id = ".((int) $rid);
1275 $sql .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1276
1277 $result = $this->db->query($sql);
1278 if ($result) {
1279 $obj = $this->db->fetch_object($result);
1280
1281 if ($obj) {
1282 $module = $obj->module;
1283 $perms = $obj->perms;
1284 $subperms = $obj->subperms;
1285 }
1286 } else {
1287 $error++;
1288 dol_print_error($this->db);
1289 }
1290
1291 // Where clause for the list of permissions to delete
1292 $wherefordel = "id=".((int) $rid);
1293 // Removal of induced rights
1294 if ($subperms == 'lire' || $subperms == 'read') {
1295 $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)";
1296 }
1297 if ($perms == 'lire' || $perms == 'read') {
1298 $wherefordel .= " OR (module='".$this->db->escape($module)."')";
1299 }
1300 } else {
1301 // The deletion of the permissions concerns the name of a module or
1302 // list of permissions.
1303 // Used in the Where clause to determine the list of permission to delete
1304 if (!empty($allmodule)) {
1305 if ($allmodule == 'allmodules') {
1306 $wherefordel = 'allmodules';
1307 } else {
1308 $wherefordel = "module='".$this->db->escape($allmodule)."'";
1309 if (!empty($allperms)) {
1310 $wherefordel .= " AND perms='".$this->db->escape($allperms)."'";
1311 }
1312 }
1313 }
1314 }
1315
1316 // Delete permission according to a criteria set into $wherefordel
1317 if (!empty($wherefordel)) {
1318 //print "$module-$perms-$subperms";
1319 $sql = "SELECT id";
1320 $sql .= " FROM ".$this->db->prefix()."rights_def";
1321 $sql .= " WHERE entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1322 if (!empty($wherefordel) && $wherefordel != 'allmodules') {
1323 $sql .= " AND (".$wherefordel.")"; // Note: parenthesis are important because wherefordel can contains OR. Also note that $wherefordel is already sanitized
1324 }
1325
1326 // avoid admin to remove his own important rights
1327 if ($this->admin == 1) {
1328 $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
1329 $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
1330 $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
1331 $sql .= " AND id NOT IN (358)"; // user export
1332 }
1333
1334 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1335 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1336 $sqldelete .= $sql;
1337 $sqldelete .= ")";
1338 $sqldelete .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1339
1340 $resql = $this->db->query($sqldelete);
1341 if (!$resql) {
1342 $error++;
1343 dol_print_error($this->db);
1344 }
1345 }
1346
1347 if (!$error && !$notrigger) {
1348 $langs->load("other");
1349 $this->context = array('audit' => $langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : ''));
1350
1351 // Call trigger
1352 $result = $this->call_trigger('USER_MODIFY', $user);
1353 if ($result < 0) {
1354 $error++;
1355 }
1356 // End call triggers
1357 }
1358
1359 if ($error) {
1360 $this->db->rollback();
1361 return -$error;
1362 } else {
1363 $this->db->commit();
1364 return 1;
1365 }
1366 }
1367
1368
1375 public function clearrights()
1376 {
1377 dol_syslog(get_class($this)."::clearrights reset user->rights");
1378 $this->rights = new stdClass();
1379 $this->nb_rights = 0;
1380 $this->all_permissions_are_loaded = 0;
1381 $this->_tab_loaded = array();
1382 }
1383
1384
1393 public function loadRights($moduletag = '', $forcereload = 0)
1394 {
1395 global $conf;
1396
1397 $alreadyloaded = false;
1398
1399 if (empty($forcereload)) {
1400 if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
1401 // Rights for this module are already loaded, so we leave
1402 $alreadyloaded = true;
1403 }
1404
1405 if (!empty($this->all_permissions_are_loaded)) {
1406 // We already loaded all rights for this user, so we leave
1407 $alreadyloaded = true;
1408 }
1409 }
1410
1411 // More init to avoid warnings/errors
1412 if (!isset($this->rights) || !is_object($this->rights)) {
1413 $this->rights = new stdClass();
1414 }
1415 if (!isset($this->rights->user) || !is_object($this->rights->user)) {
1416 $this->rights->user = new stdClass();
1417 }
1418
1419 // Get permission of users + Get permissions of groups
1420
1421 if (!$alreadyloaded) {
1422 // First user permissions
1423 $sql = "SELECT DISTINCT r.module, r.module_origin, r.perms, r.subperms";
1424 $sql .= " FROM ".$this->db->prefix()."user_rights as ur,";
1425 $sql .= " ".$this->db->prefix()."rights_def as r";
1426 $sql .= " WHERE r.id = ur.fk_id";
1427 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1428 // On old version, we used entity defined into table r only
1429 // @FIXME Test on MULTICOMPANY_BACKWARD_COMPATIBILITY is a very strange business rules because the select should be always the
1430 // same than into user->loadRights() in user/perms.php and user/group/perms.php
1431 // We should never use and remove this case.
1432 $sql .= " AND r.entity IN (0,".(isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') ? "1," : "").((int) $conf->entity).")";
1433 } else {
1434 // On table r=rights_def, the unique key is (id, entity) because id is hard coded into module descriptor and inserted during module activation.
1435 // So we must include the filter on entity on both table r. and ur.
1436 $sql .= " AND r.entity = ".((int) $conf->entity)." AND ur.entity = ".((int) $conf->entity);
1437 }
1438 $sql .= " AND ur.fk_user = ".((int) $this->id);
1439 $sql .= " AND r.perms IS NOT NULL";
1440 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1441 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1442 }
1443 if ($moduletag) {
1444 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1445 }
1446
1447 $resql = $this->db->query($sql);
1448 if ($resql) {
1449 $num = $this->db->num_rows($resql);
1450 $i = 0;
1451 while ($i < $num) {
1452 $obj = $this->db->fetch_object($resql);
1453
1454 if ($obj) {
1455 // module_origin (set only when the right was declared by another module
1456 // via KEY_MODULE, to be filed into a foreign module's section of the
1457 // permission grid) is the namespace actually used to check the right with
1458 // hasRight(), so the declaring module keeps control of it regardless of
1459 // which module's section it is grouped under for display.
1460 $module = (!empty($obj->module_origin) ? $obj->module_origin : $obj->module);
1461 $perms = $obj->perms;
1462 $subperms = $obj->subperms;
1463
1464 if (!empty($perms)) {
1465 if (!empty($module)) {
1466 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1467 $this->rights->$module = new stdClass();
1468 }
1469 if (!empty($subperms)) {
1470 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1471 $this->rights->$module->$perms = new stdClass();
1472 }
1473 if (empty($this->rights->$module->$perms->$subperms)) { // if not already counted
1474 $this->nb_rights++;
1475 }
1476 $this->rights->$module->$perms->$subperms = 1;
1477 } else {
1478 if (empty($this->rights->$module->$perms)) { // if not already counted
1479 $this->nb_rights++;
1480 }
1481 $this->rights->$module->$perms = 1;
1482 }
1483 }
1484 }
1485 }
1486 $i++;
1487 }
1488 $this->db->free($resql);
1489 }
1490
1491 // Now permissions of groups
1492 $sql = "SELECT DISTINCT r.module, r.module_origin, r.perms, r.subperms, r.entity";
1493 $sql .= " FROM ".$this->db->prefix()."usergroup_rights as gr,";
1494 $sql .= " ".$this->db->prefix()."usergroup_user as gu,";
1495 $sql .= " ".$this->db->prefix()."rights_def as r";
1496 $sql .= " WHERE r.id = gr.fk_id";
1497 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1498 // @FIXME Test on MULTICOMPANY_BACKWARD_COMPATIBILITY is a very strange business rules because the select should be always the
1499 // same than into user->loadRights() in user/perms.php and user/group/perms.php
1500 // We should never use and remove this case.
1501 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1502 $sql .= " AND gu.entity IN (0,".((int) $conf->entity).")";
1503 } else {
1504 $sql .= " AND r.entity = ".((int) $conf->entity);
1505 }
1506 } else {
1507 $sql .= " AND gr.entity = ".((int) $conf->entity); // Only groups created in current entity
1508 // The entity on the table gu=usergroup_user should be useless and should never be used because it is already into gr and r.
1509 // but when using MULTICOMPANY_TRANSVERSE_MODE, we may have inserted record that make rubbish result here due to the duplicate record of
1510 // other entities, so we are forced to add a filter on gu here
1511 $sql .= " AND gu.entity IN (0,".((int) $conf->entity).")";
1512 $sql .= " AND r.entity = ".((int) $conf->entity); // Only permission of modules enabled in current entity
1513 }
1514 // End of strange business rule
1515 $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
1516 $sql .= " AND gu.fk_user = ".((int) $this->id);
1517 $sql .= " AND r.perms IS NOT NULL";
1518 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1519 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1520 }
1521 if ($moduletag) {
1522 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1523 }
1524
1525 $resql = $this->db->query($sql);
1526 if ($resql) {
1527 $num = $this->db->num_rows($resql);
1528 $i = 0;
1529 while ($i < $num) {
1530 $obj = $this->db->fetch_object($resql);
1531
1532 if ($obj) {
1533 // module_origin (set only when the right was declared by another module
1534 // via KEY_MODULE, to be filed into a foreign module's section of the
1535 // permission grid) is the namespace actually used to check the right with
1536 // hasRight(), so the declaring module keeps control of it regardless of
1537 // which module's section it is grouped under for display.
1538 $module = (!empty($obj->module_origin) ? $obj->module_origin : $obj->module);
1539 $perms = $obj->perms;
1540 $subperms = $obj->subperms;
1541
1542 if (!empty($perms)) {
1543 if (!empty($module)) {
1544 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1545 $this->rights->$module = new stdClass();
1546 }
1547 if (!empty($subperms)) {
1548 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1549 $this->rights->$module->$perms = new stdClass();
1550 }
1551 if (empty($this->rights->$module->$perms->$subperms)) { // if not already counted
1552 $this->nb_rights++;
1553 }
1554 $this->rights->$module->$perms->$subperms = 1;
1555 } else {
1556 // 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
1557 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1558 if (empty($this->rights->$module->$perms)) { // if not already counted
1559 $this->nb_rights++;
1560 }
1561 $this->rights->$module->$perms = 1;
1562 }
1563 }
1564 }
1565 }
1566 }
1567 $i++;
1568 }
1569 $this->db->free($resql);
1570 }
1571
1572 // Force permission on user for admin
1573 if (!empty($this->admin)) {
1574 if (empty($this->rights->user->user)) {
1575 $this->rights->user->user = new stdClass();
1576 }
1577 $listofpermtotest = array('lire', 'creer', 'password', 'supprimer', 'export');
1578 foreach ($listofpermtotest as $permtotest) {
1579 if (empty($this->rights->user->user->$permtotest)) {
1580 $this->rights->user->user->$permtotest = 1;
1581 $this->nb_rights++;
1582 }
1583 }
1584 if (empty($this->rights->user->self)) {
1585 $this->rights->user->self = new stdClass();
1586 }
1587 $listofpermtotest = array('creer', 'password');
1588 foreach ($listofpermtotest as $permtotest) {
1589 if (empty($this->rights->user->self->$permtotest)) {
1590 $this->rights->user->self->$permtotest = 1;
1591 $this->nb_rights++;
1592 }
1593 }
1594 // Add test on advanced permissions
1595 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1596 if (empty($this->rights->user->user_advance)) {
1597 $this->rights->user->user_advance = new stdClass();
1598 }
1599 $listofpermtotest = array('readperms', 'write');
1600 foreach ($listofpermtotest as $permtotest) {
1601 if (empty($this->rights->user->user_advance->$permtotest)) {
1602 $this->rights->user->user_advance->$permtotest = 1;
1603 $this->nb_rights++;
1604 }
1605 }
1606 if (empty($this->rights->user->self_advance)) {
1607 $this->rights->user->self_advance = new stdClass();
1608 }
1609 $listofpermtotest = array('readperms', 'writeperms');
1610 foreach ($listofpermtotest as $permtotest) {
1611 if (empty($this->rights->user->self_advance->$permtotest)) {
1612 $this->rights->user->self_advance->$permtotest = 1;
1613 $this->nb_rights++;
1614 }
1615 }
1616 if (empty($this->rights->user->group_advance)) {
1617 $this->rights->user->group_advance = new stdClass();
1618 }
1619 $listofpermtotest = array('read', 'readperms', 'write', 'delete');
1620 foreach ($listofpermtotest as $permtotest) {
1621 if (empty($this->rights->user) || empty($this->rights->user->group_advance->$permtotest)) {
1622 $this->rights->user->group_advance->$permtotest = 1;
1623 $this->nb_rights++;
1624 }
1625 }
1626 }
1627 }
1628
1629 // For backward compatibility
1630 if (isset($this->rights->propale) && !isset($this->rights->propal)) {
1631 $this->rights->propal = $this->rights->propale;
1632 }
1633 if (isset($this->rights->propal) && !isset($this->rights->propale)) {
1634 $this->rights->propale = $this->rights->propal;
1635 }
1636
1637 if (!$moduletag) {
1638 // If the module was not define, then everything is loaded.
1639 // Therefore, we can consider that the permissions are cached
1640 // because they were all loaded for this user instance.
1641 $this->all_permissions_are_loaded = 1;
1642 } else {
1643 // If the module is defined, we flag it as loaded into cache
1644 $this->_tab_loaded[$moduletag] = 1;
1645 }
1646 }
1647 }
1648
1661 public function getrights($moduletag = '', $forcereload = 0)
1662 {
1663 $this->loadRights($moduletag, $forcereload);
1664 }
1665
1672 public function setstatus($status)
1673 {
1674 global $conf, $langs, $user;
1675
1676 $error = 0;
1677
1678 // Check parameters
1679 if (isset($this->status)) {
1680 if ($this->status == $status) {
1681 return 0;
1682 }
1683 } elseif (isset($this->statut) && $this->statut == $status) { // $this->statut is deprecated
1684 return 0;
1685 }
1686
1687 $this->db->begin();
1688
1689 // Save in database
1690 $sql = "UPDATE ".$this->db->prefix()."user";
1691 $sql .= " SET statut = ".((int) $status);
1692 $sql .= " WHERE rowid = ".((int) $this->id);
1693 $result = $this->db->query($sql);
1694
1695 dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1696 if ($result) {
1697 if ($status == 0) {
1698 $this->context['actionmsg'] = 'User '.$this->login.' disabled';
1699 } else {
1700 $this->context['actionmsg'] = 'User '.$this->login.' enabled';
1701 }
1702 // Call trigger
1703 $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
1704 if ($result < 0) {
1705 $error++;
1706 }
1707 // End call triggers
1708 }
1709
1710 if ($error) {
1711 $this->db->rollback();
1712 return -$error;
1713 } else {
1714 $this->status = $status;
1715 $this->statut = $status;
1716 $this->db->commit();
1717 return 1;
1718 }
1719 }
1720
1728 public function setForcePasswordChange($user, $value)
1729 {
1730 $error = 0;
1731
1732 $value = (int) $value;
1733
1734 // Check parameters : no change short line
1735 if ($this->force_pass_change == $value) {
1736 return 0;
1737 }
1738
1739 $this->db->begin();
1740
1741 // Save in database
1742 $sql = "UPDATE ".$this->db->prefix()."user";
1743 $sql .= " SET force_pass_change = ".((int) $value);
1744 $sql .= " WHERE rowid = ".((int) $this->id);
1745 $result = $this->db->query($sql);
1746
1747 dol_syslog(get_class($this)."::setForcePasswordChange", LOG_DEBUG);
1748 if ($result) {
1749 $this->force_pass_change = $value;
1750 // Call trigger
1751 $result = $this->call_trigger('USER_MODIFY', $user);
1752 if ($result < 0) {
1753 $error++;
1754 }
1755 // End call triggers
1756 } else {
1757 $error++;
1758 $this->error = $this->db->lasterror();
1759 }
1760
1761 if ($error) {
1762 $this->db->rollback();
1763 return -$error;
1764 } else {
1765 $this->db->commit();
1766 return 1;
1767 }
1768 }
1769
1780 public function setCategories($categories)
1781 {
1782 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1783 return parent::setCategoriesCommon($categories, Categorie::TYPE_USER);
1784 }
1785
1792 public function delete(User $user)
1793 {
1794 $error = 0;
1795
1796 $this->db->begin();
1797
1798 $this->fetch($this->id);
1799
1800 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1801
1802 // A user that still has HRM data (competency assessments, job positions, skills) must not be deleted
1803 if (isModEnabled('hrm')) {
1804 global $langs;
1805
1806 $hrmtables = array(
1807 'hrm_evaluation' => array('label' => 'EvaluationCard', 'filter' => "fk_user = ".((int) $this->id)),
1808 'hrm_job_user' => array('label' => 'EmployeePosition', 'filter' => "fk_user = ".((int) $this->id)),
1809 'hrm_skillrank' => array('label' => 'Skill', 'filter' => "objecttype = 'user' AND fk_object = ".((int) $this->id)),
1810 );
1811 foreach ($hrmtables as $hrmtable => $sanitizedhrminfo) {
1812 $sanitizedfilter = $sanitizedhrminfo['filter']; // Built above from the id of the user only
1813 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->db->sanitize($hrmtable)." WHERE ".$sanitizedfilter;
1814 $resql = $this->db->query($sql);
1815 if ($resql) {
1816 $obj = $this->db->fetch_object($resql);
1817 if ($obj && $obj->nb > 0) {
1818 $langs->loadLangs(array('errors', 'hrm'));
1819 $this->error = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $this->login, $langs->transnoentitiesnoconv($sanitizedhrminfo['label']));
1820 $this->errors[] = $this->error;
1821 $this->db->rollback();
1822 return -1;
1823 }
1824 }
1825 }
1826 }
1827
1828 // Remove rights
1829 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1830
1831 if (!$error && !$this->db->query($sql)) {
1832 $error++;
1833 $this->error = $this->db->lasterror();
1834 }
1835
1836 // Remove group
1837 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1838 if (!$error && !$this->db->query($sql)) {
1839 $error++;
1840 $this->error = $this->db->lasterror();
1841 }
1842
1843 // Remove params
1844 $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1845 if (!$error && !$this->db->query($sql)) {
1846 $error++;
1847 $this->error = $this->db->lasterror();
1848 }
1849
1850 // Remove the private bookmarks of the user (the public ones have no owner and are kept)
1851 $sql = "DELETE FROM ".$this->db->prefix()."bookmark WHERE fk_user = ".((int) $this->id);
1852 if (!$error && !$this->db->query($sql)) {
1853 $error++;
1854 $this->error = $this->db->lasterror();
1855 }
1856
1857 // If contact, remove link
1858 if ($this->contact_id > 0) {
1859 $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1860 if (!$error && !$this->db->query($sql)) {
1861 $error++;
1862 $this->error = $this->db->lasterror();
1863 }
1864 }
1865
1866 // Remove extrafields
1867 if (!$error) {
1868 $result = $this->deleteExtraFields();
1869 if ($result < 0) {
1870 $error++;
1871 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1872 }
1873 }
1874
1875 // Remove user
1876 if (!$error) {
1877 $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1878 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1879 if (!$this->db->query($sql)) {
1880 $error++;
1881 $this->error = $this->db->lasterror();
1882 }
1883 }
1884
1885 if (!$error) {
1886 // Call trigger
1887 $result = $this->call_trigger('USER_DELETE', $user);
1888 if ($result < 0) {
1889 $error++;
1890 $this->db->rollback();
1891 return -1;
1892 }
1893 // End call triggers
1894
1895 $this->db->commit();
1896 return 1;
1897 } else {
1898 $this->db->rollback();
1899 return -1;
1900 }
1901 }
1902
1910 public function create($user, $notrigger = 0)
1911 {
1912 global $conf, $langs;
1913 global $mysoc;
1914
1915 // Clean parameters
1916 $this->setUpperOrLowerCase();
1917
1918 $this->civility_code = trim((string) $this->civility_code);
1919 $this->login = trim((string) $this->login);
1920 $this->user_creation_id = (int) $user->id;
1921 if (!isset($this->entity)) {
1922 $this->entity = $conf->entity; // If not defined, we use default value
1923 }
1924 dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1925
1926 $badCharUnauthorizedIntoLoginName = getDolGlobalLoginBadCharUnauthorized();
1927
1928 // Check parameters
1929 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
1930 $langs->load("errors");
1931 $this->error = $langs->trans("ErrorBadEMail", $this->email);
1932 return -1;
1933 }
1934 if (empty($this->login)) {
1935 $langs->load("errors");
1936 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1937 return -1;
1938 } elseif ($badCharUnauthorizedIntoLoginName !== '' && preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1939 $langs->load("errors");
1940 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1941 return -1;
1942 }
1943
1944 $this->datec = dol_now();
1945
1946 $error = 0;
1947 $this->db->begin();
1948
1949 // Check if login already exists in same entity or into entity 0.
1950 if ($this->login) {
1951 $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)."'";
1952 $resqltochecklogin = $this->db->query($sqltochecklogin);
1953 if ($resqltochecklogin) {
1954 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1955 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1956 $langs->load("errors");
1957 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1958 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1959 $this->db->rollback();
1960 return -6;
1961 }
1962 $this->db->free($resqltochecklogin);
1963 }
1964 }
1965 if (!empty($this->email)) {
1966 $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)."'";
1967 $resqltochecklogin = $this->db->query($sqltochecklogin);
1968 if ($resqltochecklogin) {
1969 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1970 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1971 $langs->load("errors");
1972 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1973 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1974 $this->db->rollback();
1975 return -6;
1976 }
1977 $this->db->free($resqltochecklogin);
1978 }
1979 }
1980
1981 // Insert into database
1982 $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, fk_user_creat, entity)";
1983 $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).")";
1984 $result = $this->db->query($sql);
1985
1986 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1987 if ($result) {
1988 $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1989
1990 // Set default rights
1991 if ($this->set_default_rights() < 0) {
1992 $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1993 $this->db->rollback();
1994 return -5;
1995 }
1996
1997 if (getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && getDolGlobalString('STOCK_USERSTOCK_AUTOCREATE')) {
1998 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1999 $langs->load("stocks");
2000
2001 $entrepot = new Entrepot($this->db);
2002 $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
2003 $entrepot->libelle = $entrepot->label; // For backward compatibility
2004 $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
2005 $entrepot->statut = 1;
2006 $entrepot->country_id = $mysoc->country_id;
2007
2008 $warehouseid = $entrepot->create($user);
2009
2010 $this->fk_warehouse = $warehouseid;
2011 }
2012
2013 // Update minor fields
2014 $result = $this->update($user, 1, 1);
2015 if ($result < 0) {
2016 $this->db->rollback();
2017 return -4;
2018 }
2019
2020 if (!$notrigger) {
2021 // Call trigger
2022 $result = $this->call_trigger('USER_CREATE', $user);
2023 if ($result < 0) {
2024 $error++;
2025 }
2026 // End call triggers
2027 }
2028
2029 if (!$error) {
2030 $this->db->commit();
2031 return $this->id;
2032 } else {
2033 //$this->error=$interface->error;
2034 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
2035 $this->db->rollback();
2036 return -3;
2037 }
2038 } else {
2039 $this->error = $this->db->lasterror();
2040 $this->db->rollback();
2041 return -2;
2042 }
2043 }
2044
2045
2046 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2055 public function create_from_contact($contact, $login = '', $password = '')
2056 {
2057 // phpcs:enable
2058 global $user;
2059
2060 $error = 0;
2061
2062 // Define parameters
2063 $this->admin = 0;
2064 $this->civility_code = $contact->civility_code;
2065 $this->lastname = $contact->lastname;
2066 $this->firstname = $contact->firstname;
2067 //$this->gender = $contact->gender; // contact has no gender
2068 $this->email = $contact->email;
2069 $this->socialnetworks = $contact->socialnetworks;
2070 $this->office_phone = $contact->phone_pro;
2071 $this->office_fax = $contact->fax;
2072 $this->user_mobile = $contact->phone_mobile;
2073 $this->address = $contact->address;
2074 $this->zip = $contact->zip;
2075 $this->town = $contact->town;
2076 $this->setUpperOrLowerCase();
2077 $this->state_id = $contact->state_id;
2078 $this->country_id = $contact->country_id;
2079 $this->employee = 0;
2080
2081 if (empty($login)) {
2082 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2083 $login = dol_buildlogin($contact->lastname, $contact->firstname);
2084 }
2085 $this->login = $login;
2086
2087 $this->db->begin();
2088
2089 // Create user and set $this->id. Trigger is disabled because executed later.
2090 $result = $this->create($user, 1);
2091 if ($result > 0) {
2092 $sql = "UPDATE ".$this->db->prefix()."user";
2093 $sql .= " SET fk_socpeople=".((int) $contact->id);
2094 $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
2095 if ($contact->socid > 0) {
2096 $sql .= ", fk_soc=".((int) $contact->socid);
2097 }
2098 $sql .= " WHERE rowid=".((int) $this->id);
2099
2100 $resql = $this->db->query($sql);
2101
2102 dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
2103 if ($resql) {
2104 $this->context['createfromcontact'] = 'createfromcontact';
2105
2106 // Call trigger
2107 $result = $this->call_trigger('USER_CREATE', $user);
2108 if ($result < 0) {
2109 $error++;
2110 $this->db->rollback();
2111 return -1;
2112 }
2113 // End call triggers
2114
2115 $this->db->commit();
2116 return $this->id;
2117 } else {
2118 $this->error = $this->db->error();
2119
2120 $this->db->rollback();
2121 return -1;
2122 }
2123 } else {
2124 // $this->error already set
2125 dol_syslog(get_class($this)."::create_from_contact - 0");
2126
2127 $this->db->rollback();
2128 return $result;
2129 }
2130 }
2131
2132 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2141 public function create_from_member($member, $login = '')
2142 {
2143 // phpcs:enable
2144 global $user;
2145
2146 // Set properties on new user
2147 $this->admin = 0;
2148 $this->civility_code = $member->civility_code;
2149 // A corporation member has no lastname/firstname (the name is in the company field), so use it as
2150 // the user lastname, otherwise the created user would have an empty name and login (#33642).
2151 if ($member->morphy == 'mor' && empty($member->lastname) && !empty($member->company)) {
2152 $this->lastname = $member->company;
2153 $this->firstname = '';
2154 } else {
2155 $this->lastname = $member->lastname;
2156 $this->firstname = $member->firstname;
2157 }
2158 $this->gender = $member->gender;
2159 $this->email = $member->email;
2160 $this->fk_member = $member->id;
2161 $this->address = $member->address;
2162 $this->zip = $member->zip;
2163 $this->town = $member->town;
2164 $this->setUpperOrLowerCase();
2165 $this->state_id = $member->state_id;
2166 $this->country_id = $member->country_id;
2167 $this->socialnetworks = $member->socialnetworks;
2168
2169 $this->pass = $member->pass;
2170 $this->pass_crypted = $member->pass_indatabase_crypted;
2171
2172 if (empty($login)) {
2173 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2174 // Use the resolved name so a corporation member (name in company field) still gets a login.
2175 $login = dol_buildlogin($this->lastname, $this->firstname);
2176 }
2177 $this->login = $login;
2178
2179 $this->db->begin();
2180
2181 // Create and set $this->id
2182 $result = $this->create($user);
2183 if ($result > 0) {
2184 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
2185 $newpass = $this->setPassword($user, $this->pass);
2186 if (is_int($newpass) && $newpass < 0) {
2187 $result = -2;
2188 }
2189 } 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.
2190 $sql = "UPDATE ".$this->db->prefix()."user";
2191 $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
2192 $sql .= " WHERE rowid=".((int) $this->id);
2193
2194 $resql = $this->db->query($sql);
2195 if (!$resql) {
2196 $result = -1;
2197 }
2198 }
2199
2200 if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
2201 $sql = "UPDATE ".$this->db->prefix()."user";
2202 $sql .= " SET fk_soc=".((int) $member->socid);
2203 $sql .= " WHERE rowid=".((int) $this->id);
2204
2205 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
2206 $resql = $this->db->query($sql);
2207 if ($resql) {
2208 $this->db->commit();
2209 return $this->id;
2210 } else {
2211 $this->error = $this->db->lasterror();
2212
2213 $this->db->rollback();
2214 return -1;
2215 }
2216 }
2217 }
2218
2219 if ($result > 0) {
2220 $this->db->commit();
2221 return $this->id;
2222 } else {
2223 // $this->error was already set
2224 $this->db->rollback();
2225 return -2;
2226 }
2227 }
2228
2229 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2235 public function set_default_rights()
2236 {
2237 // phpcs:enable
2238 global $conf;
2239
2240 $rd = array();
2241 $num = 0;
2242 $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
2243 $sql .= " WHERE bydefault = 1";
2244 $sql .= " AND entity = ".((int) $conf->entity);
2245
2246 $resql = $this->db->query($sql);
2247 if ($resql) {
2248 $num = $this->db->num_rows($resql);
2249 $i = 0;
2250 while ($i < $num) {
2251 $row = $this->db->fetch_row($resql);
2252 $rd[$i] = $row[0];
2253 $i++;
2254 }
2255 $this->db->free($resql);
2256 }
2257 $i = 0;
2258 while ($i < $num) {
2259 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id)." AND fk_id=".((int) $rd[$i]);
2260 $result = $this->db->query($sql);
2261
2262 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES (".((int) $this->id).", ".((int) $rd[$i]).")";
2263 $result = $this->db->query($sql);
2264 if (!$result) {
2265 return -1;
2266 }
2267 $i++;
2268 }
2269
2270 return $i;
2271 }
2272
2283 public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
2284 {
2285 global $langs;
2286
2287 if (empty($this->country_id) && !empty($this->country_code)) {
2288 $country_id = getCountry($this->country_code, '3');
2289 $this->country_id = is_int($country_id) ? $country_id : 0;
2290 }
2291
2292 $nbrowsaffected = 0;
2293 $error = 0;
2294
2295 dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
2296
2297 // Clean parameters
2298 $this->civility_code = trim((string) $this->civility_code);
2299 $this->lastname = trim((string) $this->lastname);
2300 $this->firstname = trim((string) $this->firstname);
2301 $this->ref_employee = trim((string) $this->ref_employee);
2302 $this->national_registration_number = trim((string) $this->national_registration_number);
2303 $this->employee = ($this->employee > 0 ? $this->employee : 0);
2304 $this->login = trim((string) $this->login);
2305 $this->gender = trim((string) $this->gender);
2306
2307 $this->pass = trim((string) $this->pass);
2308 $this->api_key = trim((string) $this->api_key);
2309 $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
2310 $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
2311
2312 $this->address = trim((string) $this->address);
2313 $this->zip = trim((string) $this->zip);
2314 $this->town = trim((string) $this->town);
2315
2316 $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
2317 $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
2318 $this->office_phone = trim((string) $this->office_phone);
2319 $this->office_fax = trim((string) $this->office_fax);
2320 $this->user_mobile = trim((string) $this->user_mobile);
2321 $this->personal_mobile = trim((string) $this->personal_mobile);
2322 $this->email = trim((string) $this->email);
2323 $this->personal_email = trim((string) $this->personal_email);
2324
2325 $this->job = trim((string) $this->job);
2326 $this->signature = trim((string) $this->signature);
2327 $this->note_public = trim((string) $this->note_public);
2328 $this->note_private = trim((string) $this->note_private);
2329 $this->openid = trim((string) $this->openid);
2330 $this->admin = ($this->admin > 0 ? $this->admin : 0);
2331 $this->user_modification_id = $user->id;
2332
2333 $this->accountancy_code_user_general = trim((string) $this->accountancy_code_user_general);
2334 $this->accountancy_code = trim((string) $this->accountancy_code);
2335 $this->color = trim(str_replace('#', '', (string) $this->color));
2336 $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
2337 $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
2338
2339 $this->birth = empty($this->birth) ? '' : $this->birth;
2340 $this->fk_warehouse = (int) $this->fk_warehouse;
2341 $this->fk_establishment = (int) $this->fk_establishment;
2342
2343 $this->setUpperOrLowerCase();
2344
2345 // Check parameters
2346 $badCharUnauthorizedIntoLoginName = getDolGlobalLoginBadCharUnauthorized();
2347
2348 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
2349 $langs->load("errors");
2350 $this->error = $langs->trans("ErrorBadEMail", $this->email);
2351 return -1;
2352 }
2353 if (empty($this->login)) {
2354 $langs->load("errors");
2355 $this->error = $langs->trans("ErrorFieldRequired", 'Login');
2356 return -1;
2357 } elseif ($badCharUnauthorizedIntoLoginName !== '' && preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
2358 $langs->load("errors");
2359 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
2360 return -1;
2361 }
2362
2363 $this->db->begin();
2364
2365 // Check if login already exists in same entity or into entity 0.
2366 if (is_object($this->oldcopy) && !empty($this->oldcopy->id) && $this->oldcopy->login != $this->login) {
2367 $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)."'";
2368 $resqltochecklogin = $this->db->query($sqltochecklogin);
2369 if ($resqltochecklogin) {
2370 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2371 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2372 $langs->load("errors");
2373 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
2374 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2375 $this->db->rollback();
2376 return -1;
2377 }
2378 }
2379 }
2380 if (is_object($this->oldcopy) && !empty($this->oldcopy->id) && !empty($this->email) && $this->oldcopy->email != $this->email) {
2381 $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)."'";
2382 $resqltochecklogin = $this->db->query($sqltochecklogin);
2383 if ($resqltochecklogin) {
2384 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2385 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2386 $langs->load("errors");
2387 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
2388 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2389 $this->db->rollback();
2390 return -1;
2391 }
2392 }
2393 }
2394
2395 // Update data
2396 $sql = "UPDATE ".$this->db->prefix()."user SET";
2397 $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
2398 $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
2399 $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
2400 $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
2401 $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
2402 $sql .= ", employee = ".(int) $this->employee;
2403 $sql .= ", login = '".$this->db->escape($this->login)."'";
2404 $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
2405 $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' or 'other'
2406 $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
2407 if (!empty($user->admin)) {
2408 $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
2409 }
2410 $sql .= ", address = '".$this->db->escape($this->address)."'";
2411 $sql .= ", zip = '".$this->db->escape($this->zip)."'";
2412 $sql .= ", town = '".$this->db->escape($this->town)."'";
2413 $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : "null");
2414 $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : "null");
2415 $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
2416 $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
2417 $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
2418 $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
2419 $sql .= ", email = '".$this->db->escape($this->email)."'";
2420 $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
2421 $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
2422 $sql .= ", job = '".$this->db->escape($this->job)."'";
2423 $sql .= ", signature = '".$this->db->escape($this->signature)."'";
2424 $sql .= ", accountancy_code_user_general = '".$this->db->escape($this->accountancy_code_user_general)."'";
2425 $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
2426 $sql .= ", color = '".$this->db->escape($this->color)."'";
2427 $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
2428 $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
2429 $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2430 $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2431 $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2432 $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2433 $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2434 $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2435 $sql .= ", fk_user = ".($this->fk_user > 0 ? ((int) $this->fk_user) : "null");
2436 $sql .= ", fk_user_modif = ".($this->user_modification_id > 0 ? ((int) $this->user_modification_id) : "null");
2437 $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? ((int) $this->fk_user_expense_validator) : "null");
2438 $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? ((int) $this->fk_user_holiday_validator) : "null");
2439 if (isset($this->thm) || $this->thm != '') {
2440 $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2441 }
2442 if (isset($this->tjm) || $this->tjm != '') {
2443 $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2444 }
2445 if (isset($this->salary) || $this->salary != '') {
2446 $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2447 }
2448 if (isset($this->salaryextra) || $this->salaryextra != '') {
2449 $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2450 }
2451 $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2452 if (isModEnabled('multicompany') && !empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2453 // entity flag can be set/unset only by another superadmin user, and only when multicompany is enabled.
2454 // Without multicompany, entity must never be written here: fetch() forces an admin's entity to 0 in memory
2455 // (an admin is a global admin without multicompany), and persisting that would wrongly turn the user into
2456 // a "whole database" (entity 0) admin.
2457 $sql .= ", entity = ".((int) $this->entity);
2458 }
2459
2460 $sql .= ", default_range = ".($this->default_range > 0 ? ((int) $this->default_range) : 'null');
2461 $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? ((int) $this->default_c_exp_tax_cat) : 'null');
2462 $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? ((int) $this->fk_warehouse) : "null");
2463 $sql .= ", fk_establishment = ".($this->fk_establishment > 0 ? ((int) $this->fk_establishment) : "null");
2464 $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2465 $sql .= ", force_pass_change = ".($this->force_pass_change ? ((int) $this->force_pass_change) : "0");
2466 $sql .= " WHERE rowid = ".((int) $this->id);
2467
2468 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2469 $resql = $this->db->query($sql);
2470 if ($resql) {
2471 $nbrowsaffected += $this->db->affected_rows($resql);
2472
2473 // Update password
2474 if (!empty($this->pass)) {
2475 if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2476 // If a new value for password is set and different than the one encrypted into database
2477 $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2478 if (is_int($result) && $result < 0) {
2479 return -5;
2480 }
2481 }
2482 }
2483
2484 // If user is linked to a member, remove old link to this member
2485 if ($this->fk_member > 0) {
2486 dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2487 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2488 $resql = $this->db->query($sql);
2489 if (!$resql) {
2490 $this->error = $this->db->error();
2491 $this->db->rollback();
2492 return -5;
2493 }
2494 }
2495 // Set link to user
2496 dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2497 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2498 $resql = $this->db->query($sql);
2499 if (!$resql) {
2500 $this->error = $this->db->error();
2501 $this->db->rollback();
2502 return -5;
2503 }
2504
2505 if ($nbrowsaffected) { // If something has changed in data
2506 if ($this->fk_member > 0 && !$nosyncmember) {
2507 dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2508
2509 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2510
2511 // This user is linked with a member, so we also update member information
2512 // if this is an update.
2513 $adh = new Adherent($this->db);
2514 $result = $adh->fetch($this->fk_member);
2515
2516 if ($result > 0) {
2517 $adh->civility_code = $this->civility_code;
2518 $adh->firstname = $this->firstname;
2519 $adh->lastname = $this->lastname;
2520 $adh->login = $this->login;
2521 $adh->gender = $this->gender;
2522 $adh->birth = $this->birth;
2523
2524 $adh->pass = $this->pass;
2525
2526 $adh->address = $this->address;
2527 $adh->town = $this->town;
2528 $adh->zip = $this->zip;
2529 $adh->state_id = $this->state_id;
2530 $adh->country_id = $this->country_id;
2531
2532 $adh->email = $this->email;
2533
2534 $adh->socialnetworks = $this->socialnetworks;
2535
2536 $adh->phone = $this->office_phone;
2537 $adh->phone_mobile = $this->user_mobile;
2538
2539 $adh->default_lang = $this->lang;
2540
2541 $adh->user_id = $this->id;
2542 $adh->user_login = $this->login;
2543
2544 $result = $adh->update($user, 0, 1, 0);
2545 if ($result < 0) {
2546 $this->error = $adh->error;
2547 $this->errors = $adh->errors;
2548 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2549 $error++;
2550 }
2551 } elseif ($result < 0) {
2552 $this->error = $adh->error;
2553 $this->errors = $adh->errors;
2554 $error++;
2555 }
2556 }
2557
2558 if ($this->contact_id > 0 && !$nosynccontact) {
2559 dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2560
2561 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2562
2563 // This user is linked with a contact, so we also update contact information if this is an update.
2564 $tmpobj = new Contact($this->db);
2565 $result = $tmpobj->fetch($this->contact_id);
2566
2567 if ($result > 0) {
2568 $tmpobj->civility_code = $this->civility_code;
2569 $tmpobj->firstname = $this->firstname;
2570 $tmpobj->lastname = $this->lastname;
2571 $tmpobj->login = $this->login;
2572 $tmpobj->gender = $this->gender;
2573 $tmpobj->birth = $this->birth;
2574
2575 //$tmpobj->pass=$this->pass;
2576
2577 $tmpobj->email = $this->email;
2578
2579 $tmpobj->socialnetworks = $this->socialnetworks;
2580
2581 $tmpobj->phone_pro = $this->office_phone;
2582 $tmpobj->phone_mobile = $this->user_mobile;
2583 $tmpobj->fax = $this->office_fax;
2584
2585 $tmpobj->default_lang = $this->lang;
2586
2587 $tmpobj->address = $this->address;
2588 $tmpobj->town = $this->town;
2589 $tmpobj->zip = $this->zip;
2590 $tmpobj->state_id = $this->state_id;
2591 $tmpobj->country_id = $this->country_id;
2592
2593 $tmpobj->user_id = $this->id;
2594 $tmpobj->user_login = $this->login;
2595
2596 $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2597 if ($result < 0) {
2598 $this->error = $tmpobj->error;
2599 $this->errors = $tmpobj->errors;
2600 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2601 $error++;
2602 }
2603 } else {
2604 $this->error = $tmpobj->error;
2605 $this->errors = $tmpobj->errors;
2606 $error++;
2607 }
2608 }
2609 }
2610
2611 $action = 'update';
2612
2613 // Actions on extra fields
2614 if (!$error) {
2615 $result = $this->insertExtraFields();
2616 if ($result < 0) {
2617 $error++;
2618 }
2619 }
2620
2621 if (!$error && !$notrigger) {
2622 // Call trigger
2623 $result = $this->call_trigger('USER_MODIFY', $user);
2624 if ($result < 0) {
2625 $error++;
2626 }
2627 // End call triggers
2628 }
2629
2630 if (!$error) {
2631 $this->db->commit();
2632 return $nbrowsaffected;
2633 } else {
2634 dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2635 $this->db->rollback();
2636 return -1;
2637 }
2638 } else {
2639 $this->error = $this->db->lasterror();
2640 $this->db->rollback();
2641 return -2;
2642 }
2643 }
2644
2645 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2652 public function update_last_login_date()
2653 {
2654 // phpcs:enable
2655 $now = dol_now();
2656
2657 $userremoteip = getUserRemoteIP();
2658
2659 $sql = "UPDATE ".$this->db->prefix()."user SET";
2660 $sql .= " datepreviouslogin = datelastlogin,";
2661 $sql .= " ippreviouslogin = iplastlogin,";
2662 $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2663 $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2664 $sql .= " tms = tms"; // The last update date must change because the last login date is updated
2665 $sql .= " WHERE rowid = ".((int) $this->id);
2666
2667 dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2668 $resql = $this->db->query($sql);
2669 if ($resql) {
2670 $this->datepreviouslogin = $this->datelastlogin;
2671 $this->datelastlogin = $now;
2672 $this->ippreviouslogin = $this->iplastlogin;
2673 $this->iplastlogin = $userremoteip;
2674 return 1;
2675 } else {
2676 $this->error = $this->db->lasterror().' sql='.$sql;
2677 return -1;
2678 }
2679 }
2680
2681
2694 public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2695 {
2696 global $conf, $langs;
2697 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2698
2699 $error = 0;
2700
2701 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2702
2703 // If new password not provided, we generate one
2704 if (!$password) {
2705 $password = getRandomPassword(false);
2706 $passwordalreadycrypted = 0; // Just generated, so not crypted
2707 }
2708
2709 // Check and encrypt the password
2710 if (!empty($passwordalreadycrypted)) {
2711 $password_crypted = $password; // Reuse crypted password
2712 } else {
2713 if (getDolGlobalString('USER_PASSWORD_GENERATED')) {
2714 // Add a check on rules for password syntax using the setup of the password generator
2715 require_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/modules_genpassword.php';
2716 $modGeneratePass = ModeleGenPassword::loadAndInstantiate(getDolGlobalString('USER_PASSWORD_GENERATED'), $this->db, $conf, $langs, $user);
2717 if ($modGeneratePass) {
2718 '@phan-var-force ModeleGenPassword $modGeneratePass';
2719
2720 // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2721 $modGeneratePass->WithoutAmbi = 0;
2722
2723 // Call to validatePassword($password) to check pass match rules
2724 $testpassword = $modGeneratePass->validatePassword($password);
2725 if (!$testpassword) {
2726 $this->error = $modGeneratePass->error;
2727 return -1;
2728 }
2729 }
2730 }
2731
2732
2733 // Now, we encrypt the new password
2734 $password_crypted = (string) dol_hash($password);
2735 }
2736
2737 // Update password
2738 if (!$changelater) {
2739 if (!is_object($this->oldcopy)) {
2740 $this->oldcopy = clone $this;
2741 }
2742
2743 $now = dol_now();
2744
2745 $this->db->begin();
2746
2747 $sql = "UPDATE ".$this->db->prefix()."user";
2748 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2749 $sql .= " datelastpassvalidation = '".$this->db->idate(dol_now())."',";
2750 $sql .= " pass_temp = null,";
2751 $sql .= " force_pass_change = 0";
2752 if (!empty($flagdelsessionsbefore)) {
2753 $sql .= ", flagdelsessionsbefore = '".$this->db->idate($now - 5, 'gmt')."'";
2754 }
2755 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
2756 $sql .= ", pass = null";
2757 } else {
2758 $sql .= ", pass = '".$this->db->escape($password)."'";
2759 }
2760 $sql .= " WHERE rowid = ".((int) $this->id);
2761
2762 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2763
2764 $result = $this->db->query($sql);
2765 if ($result) {
2766 if ($this->db->affected_rows($result)) {
2767 $this->pass = $password;
2768 $this->pass_indatabase = $password;
2769 $this->pass_indatabase_crypted = (string) $password_crypted;
2770 $this->force_pass_change = 0;
2771
2772 if ($this->fk_member && !$nosyncmember) {
2773 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2774
2775 // This user is linked with a member, so we also update members information
2776 // if this is an update.
2777 $adh = new Adherent($this->db);
2778 $result = $adh->fetch($this->fk_member);
2779
2780 if ($result >= 0) {
2781 $result = $adh->setPassword($user, $this->pass, (!getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 0 : 1), 1); // The encryption is not managed in the 'adherent' module
2782 if (is_int($result) && $result < 0) {
2783 $this->error = $adh->error;
2784 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2785 $error++;
2786 }
2787 } else {
2788 $this->error = $adh->error;
2789 $error++;
2790 }
2791 }
2792
2793 dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2794
2795 // Call trigger for the "security events" log
2796 $user->context['audit'] = 'login='.$user->login;
2797 if (!empty($flagdelsessionsbefore)) {
2798 $user->context['audit'] .= " - flagdelsessionsbefore set to '".$this->db->idate($now - 5, 'gmt')."'";
2799 }
2800
2801 if (!$error && !$notrigger) {
2802 // Call trigger
2803 $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2804 if ($result < 0) {
2805 $error++;
2806 $this->db->rollback();
2807 return -1;
2808 }
2809 // End call triggers
2810 }
2811
2812 $this->db->commit();
2813 return $this->pass;
2814 } else {
2815 $this->db->rollback();
2816 return 0;
2817 }
2818 } else {
2819 $this->db->rollback();
2820 dol_print_error($this->db);
2821 return -1;
2822 }
2823 } else {
2824 // We store password in password temporary field.
2825 // After receiving confirmation link, we will erase and store it in pass_crypted
2826 $sql = "UPDATE ".$this->db->prefix()."user";
2827 $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2828 $sql .= " WHERE rowid = ".((int) $this->id);
2829
2830 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2831 $result = $this->db->query($sql);
2832 if ($result) {
2833 return $password;
2834 } else {
2835 dol_print_error($this->db);
2836 return -3;
2837 }
2838 }
2839 }
2840
2841 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2850 public function send_password($user, $password = '', $changelater = 0)
2851 {
2852 // phpcs:enable
2853 global $conf, $langs;
2855
2856 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2857
2858 $msgishtml = 0;
2859
2860 // Define $msg
2861 $mesg = '';
2862
2863 $outputlangs = new Translate("", $conf);
2864
2865 if (getDolGlobalString('MAIN_LANG_DEFAULT')) {
2866 $outputlangs->setDefaultLang(getDolGlobalString('MAIN_LANG_DEFAULT'));
2867 } else { // If user has not defined its own language, we used current language
2868 $outputlangs = $langs;
2869 }
2870
2871 // Load translation files required by the page
2872 $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2873
2874 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', constant('DOL_APPLICATION_TITLE'));
2875
2876 $subject = '['.$appli.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2877
2878 // Define $urlwithroot
2879 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2880 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2881
2882 if (!$changelater) {
2883 $url = $urlwithroot.'/';
2884 if (getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD')) {
2885 $url = getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD');
2886 }
2887
2888 dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2889
2890 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."\n";
2891 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2892 $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2893 $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2894 $mesg .= "\n";
2895
2896 $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2897 $mesg .= "--\n";
2898 $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2899 } else {
2900 //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2901 $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2902 $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2903 if (isModEnabled('multicompany')) {
2904 $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2905 }
2906
2907 dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2908
2909 $msgishtml = 1;
2910
2911 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2912 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2913 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2914 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2915 $mesg .= "<br>\n";
2916 $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2917 $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2918 $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2919 }
2920
2921 $trackid = 'use'.$this->id;
2922 $sendcontext = 'passwordreset';
2923
2924 $mailfile = new CMailFile(
2925 $subject,
2926 $this->email,
2927 getDolGlobalString("MAIN_MAIL_EMAIL_FROM_PASSWORDRESET", getDolGlobalString("MAIN_MAIL_EMAIL_FROM")),
2928 $mesg,
2929 array(),
2930 array(),
2931 array(),
2932 '',
2933 '',
2934 0,
2935 $msgishtml,
2936 '',
2937 '',
2938 $trackid,
2939 '',
2940 $sendcontext
2941 );
2942
2943 if ($mailfile->sendfile()) {
2944 return 1;
2945 } else {
2946 $langs->load("errors");
2947 $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2948 return -1;
2949 }
2950 }
2951
2957 public function error()
2958 {
2959 return $this->error;
2960 }
2961
2962
2963 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2969 public function fetch_clicktodial()
2970 {
2971 // phpcs:enable
2972 $sql = "SELECT url, login, pass, poste ";
2973 $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2974 $sql .= " WHERE u.fk_user = ".((int) $this->id);
2975
2976 $resql = $this->db->query($sql);
2977 if ($resql) {
2978 if ($this->db->num_rows($resql)) {
2979 $obj = $this->db->fetch_object($resql);
2980
2981 $this->clicktodial_url = $obj->url;
2982 $this->clicktodial_login = $obj->login;
2983 $this->clicktodial_password = $obj->pass;
2984 $this->clicktodial_poste = $obj->poste;
2985 }
2986
2987 $this->clicktodial_loaded = 1; // Data loaded (found or not)
2988
2989 $this->db->free($resql);
2990 return 1;
2991 } else {
2992 $this->error = $this->db->error();
2993 return -1;
2994 }
2995 }
2996
2997 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3003 public function update_clicktodial()
3004 {
3005 // phpcs:enable
3006 $this->db->begin();
3007
3008 $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
3009 $sql .= " WHERE fk_user = ".((int) $this->id);
3010
3011 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
3012
3013 $result = $this->db->query($sql);
3014
3015 $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
3016 $sql .= " (fk_user,url,login,pass,poste)";
3017 $sql .= " VALUES (".((int) $this->id);
3018 $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
3019 $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
3020 $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
3021 $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
3022
3023 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
3024
3025 $result = $this->db->query($sql);
3026 if ($result) {
3027 $this->db->commit();
3028 return 1;
3029 } else {
3030 $this->db->rollback();
3031 $this->error = $this->db->lasterror();
3032 return -1;
3033 }
3034 }
3035
3036
3045 public function setInGroup($group, $entity, $notrigger = 0)
3046 {
3047 global $langs, $user;
3048
3049 $error = 0;
3050
3051 $this->db->begin();
3052
3053 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
3054 $sql .= " WHERE fk_user = ".((int) $this->id);
3055 $sql .= " AND fk_usergroup = ".((int) $group);
3056 $sql .= " AND entity = ".((int) $entity);
3057
3058 $result = $this->db->query($sql);
3059
3060 $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
3061 $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
3062
3063 $result = $this->db->query($sql);
3064 if ($result) {
3065 if (!$error && !$notrigger) {
3066 $this->context = array('audit' => $langs->trans("UserSetInGroup"), 'newgroupid' => $group);
3067
3068 // Call trigger
3069 $result = $this->call_trigger('USER_MODIFY', $user);
3070 if ($result < 0) {
3071 $error++;
3072 }
3073 // End call triggers
3074 }
3075
3076 if (!$error) {
3077 $this->db->commit();
3078 return 1;
3079 } else {
3080 dol_syslog(get_class($this)."::setInGroup ".$this->error, LOG_ERR);
3081 $this->db->rollback();
3082 return -2;
3083 }
3084 } else {
3085 $this->error = $this->db->lasterror();
3086 $this->db->rollback();
3087 return -1;
3088 }
3089 }
3090
3099 public function removeFromGroup($group, $entity, $notrigger = 0)
3100 {
3101 global $langs, $user;
3102
3103 $error = 0;
3104
3105 $this->db->begin();
3106
3107 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
3108 $sql .= " WHERE fk_user = ".((int) $this->id);
3109 $sql .= " AND fk_usergroup = ".((int) $group);
3110 if (empty($entity)) {
3111 $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
3112 } else {
3113 $sql .= " AND entity = ".((int) $entity);
3114 }
3115
3116 $result = $this->db->query($sql);
3117 if ($result) {
3118 if (!$error && !$notrigger) {
3119 $this->context = array('audit' => $langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
3120
3121 // Call trigger
3122 $result = $this->call_trigger('USER_MODIFY', $user);
3123 if ($result < 0) {
3124 $error++;
3125 }
3126 // End call triggers
3127 }
3128
3129 if (!$error) {
3130 $this->db->commit();
3131 return 1;
3132 } else {
3133 dol_syslog(get_class($this)."::removeFromGroup ".$this->error, LOG_ERR);
3134 $this->db->rollback();
3135 return -2;
3136 }
3137 } else {
3138 $this->error = $this->db->lasterror();
3139 $this->db->rollback();
3140 return -1;
3141 }
3142 }
3143
3144
3152 {
3153 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3154
3155 $now = dol_now();
3156
3157 //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
3158
3159 // Check date start validity
3160 if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
3161 return 1;
3162 }
3163 // Check date end validity
3164 if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
3165 return 1;
3166 }
3167
3168 return 0;
3169 }
3170
3171
3183 public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
3184 {
3185 $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3186 $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
3187 $result .= '</a>';
3188
3189 return $result;
3190 }
3191
3198 public function getTooltipContentArray($params)
3199 {
3200 global $conf, $langs, $menumanager;
3201 global $dolibarr_main_demo;
3202
3203 $infologin = $params['infologin'] ?? 0;
3204 $option = $params['option'] ?? '';
3205
3206 $data = [];
3207 if (!empty($this->photo)) {
3208 $photo = '<div class="photointooltip floatright">';
3209 $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
3210 $photo .= '</div>';
3211 $data['photo'] = $photo;
3212 //$label .= '<div style="clear: both;"></div>';
3213 }
3214
3215 // Info Login
3216 $data['opendiv'] = '<div class="centpercent divtooltip">';
3217 $data['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
3218 $data['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs));
3219 if (!empty($this->login)) {
3220 $data['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
3221 }
3222 if (!empty($this->job)) {
3223 $data['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
3224 }
3225 $data['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
3226 if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
3227 $phonelist = array();
3228 if ($this->office_phone) {
3229 $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3230 }
3231 if ($this->office_fax) {
3232 $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3233 }
3234 if ($this->user_mobile) {
3235 $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3236 }
3237 $data['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
3238 }
3239 if (!empty($this->admin)) {
3240 $data['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
3241 }
3242 if (!empty($this->accountancy_code) || $option == 'accountancy') {
3243 $langs->load("companies");
3244 $data['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
3245 }
3246 $company = '';
3247 if (!empty($this->socid)) { // Add thirdparty for external users
3248 $thirdpartystatic = new Societe($this->db);
3249 $thirdpartystatic->fetch($this->socid);
3250 $companyimg = '';
3251 if (empty($params['hidethirdpartylogo'])) {
3252 $companyimg = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3253 }
3254 $company = ' ('.$langs->trans("Company").': '.($companyimg ? $companyimg : img_picto('', 'company')).' '.dol_string_nohtmltag($thirdpartystatic->name).')';
3255 }
3256 $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
3257 $data['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
3258 $data['closediv'] = '</div>';
3259
3260 if ($infologin > 0) {
3261 $data['newlinelogin'] = '<br>';
3262 $data['session'] = '<br><u>'.$langs->trans("Session").'</u>';
3263 $data['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
3264 if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
3265 $data['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
3266 }
3267 $data['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
3268 $data['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
3269 $data['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
3270 $data['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
3271 // @phan-suppress-next-line PhanRedefinedClassReference
3272 $data['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
3273 $s = picto_from_langcode($langs->getDefaultLang());
3274 $data['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
3275 $data['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.($_SERVER['HTTP_USER_AGENT'] ?? '').')');
3276 $data['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
3277 $data['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
3278 if ($conf->browser->layout == 'phone') {
3279 $data['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
3280 }
3281 if (!empty($_SESSION["disablemodules"])) {
3282 $data['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(implode(', ', explode(',', $_SESSION["disablemodules"])));
3283 }
3284 }
3285
3286 return $data;
3287 }
3288
3304 public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
3305 {
3306 global $langs, $hookmanager, $user;
3307
3308 if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
3309 $option = 'nolink';
3310 }
3311
3312 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
3313 $withpictoimg = 0;
3314 }
3315
3316 $result = '';
3317 $params = [
3318 'id' => $this->id,
3319 'objecttype' => $this->element,
3320 'infologin' => $infologin,
3321 'option' => $option,
3322 'hidethirdpartylogo' => $hidethirdpartylogo,
3323 ];
3324 $classfortooltip = 'classfortooltip';
3325 $dataparams = '';
3326 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3327 $classfortooltip = 'classforajaxtooltip';
3328 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3329 $label = '';
3330 } else {
3331 $label = implode($this->getTooltipContentArray($params));
3332 }
3333
3334 $companylink = '';
3335 if (!empty($this->socid)) { // Add thirdparty for external users
3336 $thirdpartystatic = new Societe($this->db);
3337 $thirdpartystatic->fetch($this->socid);
3338 if (empty($hidethirdpartylogo)) {
3339 $companylink = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3340 }
3341 }
3342
3343 if ($infologin < 0) {
3344 $label = '';
3345 }
3346
3347 $baseurl = DOL_URL_ROOT . '/user/card.php';
3348 if ($option == 'leave') {
3349 $baseurl = DOL_URL_ROOT . '/holiday/list.php';
3350 }
3351 $query = ['id' => $this->id];
3352 if ($option != 'nolink') {
3353 // Add param to save lastsearch_values or not
3354 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3355 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3356 $add_save_lastsearch_values = 1;
3357 }
3358 if ($add_save_lastsearch_values) {
3359 $query = array_merge($query, ['save_lastsearch_values' => 1]);
3360 }
3361 }
3362 $url = dolBuildUrl($baseurl, $query);
3363
3364 $linkstart = '<a href="'.$url.'"';
3365 $linkclose = "";
3366 if (empty($notooltip)) {
3367 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3368 $langs->load("users");
3369 $label = $langs->trans("ShowUser");
3370 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3371 }
3372 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3373 $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
3374 } else {
3375 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
3376 }
3377
3378 $linkstart .= $linkclose.'>';
3379 $linkend = '</a>';
3380
3381 //if ($withpictoimg == -1) $result.='<div class="nowrap">';
3382 $result .= (($option == 'nolink') ? '' : $linkstart);
3383 if ($withpictoimg) {
3384 $paddafterimage = '';
3385 if (abs((int) $withpictoimg) == 1 || abs((int) $withpictoimg) == 4) {
3386 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3387 }
3388 // Only picto
3389 if ($withpictoimg > 0) {
3390 $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>';
3391 } else {
3392 // Picto must be a photo
3393 $picto = '<!-- picto photo user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'"'.($paddafterimage ? ' '.$paddafterimage : '').'>';
3394 $picto .= Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto'.(($withpictoimg == -3 || $withpictoimg == -4) ? 'small' : ''), 'mini', 0, 1);
3395 $picto .= '</span>';
3396 }
3397 $result .= $picto;
3398 }
3399
3400 if ($withpictoimg == -4 || ($withpictoimg > -2 && $withpictoimg != 2)) {
3401 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3402 $result .= '<span class="nopadding usertext'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
3403 }
3404 if ($mode == 'login') {
3405 $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
3406 } else {
3407 $result .= dol_string_nohtmltag($this->getFullName($langs, 0, ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
3408 }
3409 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3410 $result .= '</span>';
3411 }
3412 }
3413 $result .= (($option == 'nolink') ? '' : $linkend);
3414 //if ($withpictoimg == -1) $result.='</div>';
3415
3416 $result .= $companylink;
3417
3418 global $action;
3419 $hookmanager->initHooks(array('userdao'));
3420 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
3421 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3422 if ($reshook > 0) {
3423 $result = $hookmanager->resPrint;
3424 } else {
3425 $result .= $hookmanager->resPrint;
3426 }
3427
3428 return $result;
3429 }
3430
3440 public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
3441 {
3442 global $langs, $user;
3443
3444 $result = '';
3445
3446 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3447 $linkend = '</a>';
3448
3449 //Check user's rights to see an other user
3450 if ((!$user->hasRight('user', 'user', 'lire') && $this->id != $user->id)) {
3451 $option = 'nolink';
3452 }
3453
3454 if ($option == 'xxx') {
3455 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3456 $linkend = '</a>';
3457 }
3458
3459 if ($option == 'nolink') {
3460 $linkstart = '';
3461 $linkend = '';
3462 }
3463
3464 $result .= $linkstart;
3465 if ($withpictoimg) {
3466 $paddafterimage = '';
3467 if (abs($withpictoimg) == 1) {
3468 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3469 }
3470 // Only picto
3471 if ($withpictoimg > 0) {
3472 $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3473 } else {
3474 // Picto must be a photo
3475 $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>';
3476 }
3477 $result .= $picto;
3478 }
3479 $result .= $this->login;
3480 $result .= $linkend;
3481
3482 return $result;
3483 }
3484
3491 public function getLibStatut($mode = 0)
3492 {
3493 return $this->LibStatut(isset($this->status) ? (int) $this->status : (int) $this->statut, $mode); // $this->statut is deprecated
3494 }
3495
3496 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3504 public function LibStatut($status, $mode = 0)
3505 {
3506 // phpcs:enable
3507 global $langs;
3508
3509 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3510 global $langs;
3511 //$langs->load("mymodule");
3512 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3513 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3514 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3515 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3516 }
3517
3518 $statusType = 'status5';
3519 if ($status == self::STATUS_ENABLED) {
3520 $statusType = 'status4';
3521 }
3522
3523 $label = $this->labelStatus[$status];
3524 $labelshort = $this->labelStatusShort[$status];
3525
3526 $now = dol_now();
3527 if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3528 $statusType = 'status3';
3529 $label .= ' ('.$langs->trans("UserNotYetValid").')';
3530 }
3531 if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3532 $statusType = 'status2';
3533 $label .= ' ('.$langs->trans("UserExpired").')';
3534 }
3535
3536 return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3537 }
3538
3539
3547 public function getKanbanView($option = '', $arraydata = null)
3548 {
3549 global $langs;
3550
3551 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3552
3553 $return = '<div class="box-flex-item box-flex-grow-zero">';
3554 $return .= '<div class="info-box info-box-sm">';
3555 $return .= '<span class="info-box-icon bg-infobox-action">';
3556
3557 $label = '';
3558 if (!empty($this->photo)) {
3559 //$label .= '<div class="photointooltip floatright">';
3560 $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
3561 //$label .= '</div>';
3562 //$label .= '<div style="clear: both;"></div>';
3563 $return .= $label;
3564 } else {
3565 $return .= img_picto('', $this->picto);
3566 }
3567
3568 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3569 $return .= '</span>';
3570 $return .= '<div class="info-box-content">';
3571 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3572 if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3573 $return .= img_picto($langs->trans("SuperAdministratorDesc"), 'superadmin', 'class="valignmiddle paddingright paddingleft"');
3574 } elseif ($this->admin) {
3575 $return .= img_picto($langs->trans("AdministratorDesc"), 'admin', 'class="valignmiddle paddingright paddingleft"');
3576 }
3577 $return .= '</span>';
3578 if ($selected >= 0) {
3579 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3580 }
3581 if ($this->email) {
3582 $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3583 }
3584 if (method_exists($this, 'getLibStatut')) {
3585 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3586 }
3587 $return .= '</div>';
3588 $return .= '</div>';
3589 $return .= '</div>';
3590
3591 return $return;
3592 }
3593
3594
3595 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3596 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3606 public function _load_ldap_dn($info, $mode = 0)
3607 {
3608 // phpcs:enable
3609 global $conf;
3610 $dn = '';
3611 if ($mode == 0) {
3612 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')]."," . getDolGlobalString('LDAP_USER_DN');
3613 } elseif ($mode == 1) {
3614 $dn = getDolGlobalString('LDAP_USER_DN');
3615 } elseif ($mode == 2) {
3616 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')];
3617 }
3618 return $dn;
3619 }
3620
3621 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3622 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3628 public function _load_ldap_info()
3629 {
3630 // phpcs:enable
3631 global $conf, $langs;
3632
3633 $info = array();
3634
3635 $socialnetworks = getArrayOfSocialNetworks();
3636
3637 $keymodified = false;
3638
3639 // Object classes
3640 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_USER_OBJECT_CLASS'));
3641
3642 $this->fullname = $this->getFullName($langs);
3643
3644 // Possible LDAP KEY (constname => varname)
3645 $ldapkey = array(
3646 'LDAP_FIELD_FULLNAME' => 'fullname',
3647 'LDAP_FIELD_NAME' => 'lastname',
3648 'LDAP_FIELD_FIRSTNAME' => 'firstname',
3649 'LDAP_FIELD_LOGIN' => 'login',
3650 'LDAP_FIELD_LOGIN_SAMBA' => 'login',
3651 'LDAP_FIELD_PHONE' => 'office_phone',
3652 'LDAP_FIELD_MOBILE' => 'user_mobile',
3653 'LDAP_FIELD_FAX' => 'office_fax',
3654 'LDAP_FIELD_MAIL' => 'email',
3655 'LDAP_FIELD_SID' => 'ldap_sid',
3656 );
3657
3658 // Champs
3659 foreach ($ldapkey as $constname => $varname) {
3660 if (!empty($this->$varname) && getDolGlobalString($constname)) {
3661 $info[getDolGlobalString($constname)] = $this->$varname;
3662
3663 // Check if it is the LDAP key and if its value has been changed
3664 if (getDolGlobalString('LDAP_KEY_USERS') && getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString($constname)) {
3665 if (is_object($this->oldcopy) && !empty($this->oldcopy->id) && $this->$varname != $this->oldcopy->$varname) {
3666 $keymodified = true; // For check if LDAP key has been modified
3667 }
3668 }
3669 }
3670 }
3671 foreach ($socialnetworks as $key => $value) {
3672 if (!empty($this->socialnetworks[$value['label']]) && getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))) {
3673 $info[getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3674 }
3675 }
3676 if ($this->address && getDolGlobalString('LDAP_FIELD_ADDRESS')) {
3677 $info[getDolGlobalString('LDAP_FIELD_ADDRESS')] = $this->address;
3678 }
3679 if ($this->zip && getDolGlobalString('LDAP_FIELD_ZIP')) {
3680 $info[getDolGlobalString('LDAP_FIELD_ZIP')] = $this->zip;
3681 }
3682 if ($this->town && getDolGlobalString('LDAP_FIELD_TOWN')) {
3683 $info[getDolGlobalString('LDAP_FIELD_TOWN')] = $this->town;
3684 }
3685 if ($this->note_public && getDolGlobalString('LDAP_FIELD_DESCRIPTION')) {
3686 $info[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_public, 2);
3687 }
3688 if ($this->socid > 0 && getDolGlobalString('LDAP_FIELD_COMPANY')) {
3689 $soc = new Societe($this->db);
3690 $soc->fetch($this->socid);
3691
3692 $info[getDolGlobalString('LDAP_FIELD_COMPANY')] = $soc->name;
3693 if ($soc->client == 1) {
3694 $info["businessCategory"] = "Customers";
3695 }
3696 if ($soc->client == 2) {
3697 $info["businessCategory"] = "Prospects";
3698 }
3699 if ($soc->fournisseur == 1) {
3700 $info["businessCategory"] = "Suppliers";
3701 }
3702 }
3703
3704 // When password is modified
3705 if (!empty($this->pass)) {
3706 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3707 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass; // this->pass = unencrypted password
3708 }
3709 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3710 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3711 }
3712 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3713 // Set LDAP password if possible
3714 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3715 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
3716 // Just for the default MD5 !
3717 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) {
3718 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3719 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3720 }
3721 }
3722 } elseif (!empty($this->pass_indatabase)) {
3723 // Use $this->pass_indatabase value if exists
3724 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3725 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = unencrypted password
3726 }
3727 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3728 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3729 }
3730 }
3731 }
3732
3733 if (getDolGlobalString('LDAP_SERVER_TYPE') == 'egroupware') {
3734 $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3735
3736 $info['uidnumber'] = $this->id;
3737
3738 $info['phpgwTz'] = 0;
3739 $info['phpgwMailType'] = 'INTERNET';
3740 $info['phpgwMailHomeType'] = 'INTERNET';
3741
3742 $info["phpgwContactTypeId"] = 'n';
3743 $info["phpgwContactCatId"] = 0;
3744 $info["phpgwContactAccess"] = "public";
3745
3746 $info["phpgwContactOwner"] = 1;
3747
3748 if ($this->email) {
3749 $info["rfc822Mailbox"] = $this->email;
3750 }
3751 if ($this->user_mobile) {
3752 $info["phpgwCellTelephoneNumber"] = $this->user_mobile;
3753 }
3754 }
3755
3756 if (getDolGlobalString('LDAP_FIELD_USERID')) {
3757 $info[getDolGlobalString('LDAP_FIELD_USERID')] = $this->id;
3758 }
3759 if (getDolGlobalString('LDAP_FIELD_GROUPID')) {
3760 $usergroup = new UserGroup($this->db);
3761 $groupslist = $usergroup->listGroupsForUser($this->id);
3762 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = '65534';
3763 if (!empty($groupslist)) {
3764 foreach ($groupslist as $groupforuser) {
3765 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = $groupforuser->id; //Select first group in list
3766 break;
3767 }
3768 }
3769 }
3770 if (getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY') && getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')) {
3771 $info[getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY')] = getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')."/".$this->login;
3772 }
3773
3774 return $info;
3775 }
3776
3777
3785 public function initAsSpecimen()
3786 {
3787 global $user;
3788
3789 $now = dol_now();
3790
3791 // Initialise parameters
3792 $this->id = 0;
3793 $this->ref = 'SPECIMEN';
3794 $this->specimen = 1;
3795 $this->user_creation_id = $user->id;
3796
3797 $this->lastname = 'DOLIBARR';
3798 $this->firstname = 'SPECIMEN';
3799 $this->gender = 'man';
3800 $this->note_public = 'This is a note public';
3801 $this->note_private = 'This is a note private';
3802 $this->email = 'email@specimen.com';
3803 $this->personal_email = 'personalemail@specimen.com';
3804 $this->socialnetworks = array(
3805 'skype' => 'skypepseudo',
3806 'twitter' => 'twitterpseudo',
3807 'facebook' => 'facebookpseudo',
3808 'linkedin' => 'linkedinpseudo',
3809 );
3810 $this->office_phone = '0999999999';
3811 $this->office_fax = '0999999998';
3812 $this->user_mobile = '0999999997';
3813 $this->personal_mobile = '0999999996';
3814 $this->admin = 0;
3815 $this->login = 'dolibspec';
3816 $this->pass = 'dolibSpec+@123';
3817 //$this->pass_indatabase='dolibspec'; Set after a fetch
3818 //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3819 $this->datec = $now;
3820 $this->datem = $now;
3821
3822 $this->datelastlogin = $now;
3823 $this->iplastlogin = '127.0.0.1';
3824 $this->datepreviouslogin = $now;
3825 $this->ippreviouslogin = '127.0.0.1';
3826 $this->status = 1;
3827
3828 $this->entity = 1;
3829
3830 return 1;
3831 }
3832
3839 public function info($id)
3840 {
3841 $sql = "SELECT u.rowid, u.login as ref, u.datec, fk_user_creat as user_creation_id, fk_user_modif as user_modification_id,";
3842 $sql .= " GREATEST(u.tms, COALESCE(uef.tms, u.tms)) as date_modification, u.entity";
3843 $sql .= " FROM ".$this->db->prefix()."user as u";
3844 $sql .= " LEFT JOIN ".$this->db->prefix()."user_extrafields as uef ON uef.fk_object = u.rowid";
3845 $sql .= " WHERE u.rowid = ".((int) $id);
3846
3847 $result = $this->db->query($sql);
3848 if ($result) {
3849 if ($this->db->num_rows($result)) {
3850 $obj = $this->db->fetch_object($result);
3851
3852 $this->id = $obj->rowid;
3853
3854 $this->user_creation_id = $obj->user_creation_id;
3855 $this->user_modification_id = $obj->user_modification_id;
3856
3857 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3858 $this->date_creation = $this->db->jdate($obj->datec);
3859 $this->date_modification = $this->db->jdate($obj->date_modification);
3860 $this->entity = $obj->entity;
3861 }
3862
3863 $this->db->free($result);
3864 } else {
3865 dol_print_error($this->db);
3866 }
3867 }
3868
3869
3875 public function getNbOfEMailings()
3876 {
3877 $sql = "SELECT count(mc.email) as nb";
3878 $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3879 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3880 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
3881
3882 $resql = $this->db->query($sql);
3883 if ($resql) {
3884 $obj = $this->db->fetch_object($resql);
3885 $nb = (int) $obj->nb;
3886
3887 $this->db->free($resql);
3888 return $nb;
3889 } else {
3890 $this->error = $this->db->error();
3891 return -1;
3892 }
3893 }
3894
3903 public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3904 {
3905 $sql = "SELECT count(rowid) as nb";
3906 $sql .= " FROM ".$this->db->prefix()."user";
3907 if ($option == 'superadmin') {
3908 $sql .= " WHERE entity = 0";
3909 } else {
3910 $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3911 if ($limitTo == 'active') {
3912 $sql .= " AND statut = 1";
3913 }
3914 }
3915 if ($admin >= 0) {
3916 $sql .= " AND admin = ".(int) $admin;
3917 }
3918
3919 $resql = $this->db->query($sql);
3920 if ($resql) {
3921 $obj = $this->db->fetch_object($resql);
3922 $nb = (int) $obj->nb;
3923
3924 $this->db->free($resql);
3925 return $nb;
3926 } else {
3927 $this->error = $this->db->lasterror();
3928 return -1;
3929 }
3930 }
3931
3932 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3939 public function update_ldap2dolibarr(&$ldapuser)
3940 {
3941 // phpcs:enable
3942 // TODO: See why the update sets all values to empty (does global $user overwrite?)
3943 global $user;
3944
3945 $socialnetworks = getArrayOfSocialNetworks();
3946
3947 $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3948 $this->firstname = $ldapuser->$tmpvar;
3949 $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3950 $this->lastname = $ldapuser->$tmpvar;
3951 $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3952 $this->login = $ldapuser->$tmpvar;
3953 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3954 $this->pass = $ldapuser->$tmpvar;
3955 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3956 $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3957
3958 $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3959 $this->office_phone = $ldapuser->$tmpvar;
3960 $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3961 $this->user_mobile = $ldapuser->$tmpvar;
3962 $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3963 $this->office_fax = $ldapuser->$tmpvar;
3964 $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3965 $this->email = $ldapuser->$tmpvar;
3966 foreach ($socialnetworks as $key => $value) {
3967 $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3968 $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3969 }
3970 $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3971 $this->ldap_sid = $ldapuser->$tmpvar;
3972
3973 $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3974 $this->job = $ldapuser->$tmpvar;
3975 $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3976 $this->note_public = $ldapuser->$tmpvar;
3977
3978 $result = $this->update($user);
3979
3980 dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3981
3982 return $result;
3983 }
3984
3985
3986 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3993 public function get_children()
3994 {
3995 // phpcs:enable
3996 $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3997 $sql .= " WHERE fk_user = ".((int) $this->id);
3998
3999 dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
4000 $res = $this->db->query($sql);
4001 if ($res) {
4002 $users = array();
4003 while ($rec = $this->db->fetch_array($res)) {
4004 $user = new User($this->db);
4005 $user->fetch($rec['rowid']);
4006 $users[] = $user;
4007 }
4008 return $users;
4009 } else {
4010 dol_print_error($this->db);
4011 return -1;
4012 }
4013 }
4014
4015
4021 private function loadParentOf()
4022 {
4023 $this->parentof = array();
4024
4025 // Load array[child]=parent
4026 $sql = "SELECT fk_user as id_parent, rowid as id_son";
4027 $sql .= " FROM ".$this->db->prefix()."user";
4028 $sql .= " WHERE fk_user <> 0";
4029 $sql .= " AND entity IN (".getEntity('user').")";
4030
4031 dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
4032 $resql = $this->db->query($sql);
4033 if ($resql) {
4034 while ($obj = $this->db->fetch_object($resql)) {
4035 $this->parentof[$obj->id_son] = $obj->id_parent;
4036 }
4037 return 1;
4038 } else {
4039 dol_print_error($this->db);
4040 return -1;
4041 }
4042 }
4043
4044 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4058 public function get_full_tree($deleteafterid = 0, $filter = '')
4059 {
4060 // phpcs:enable
4061 global $hookmanager;
4062
4063 // Actions hooked (by external module)
4064 $hookmanager->initHooks(array('userdao'));
4065
4066 $this->users = array();
4067
4068 // Init this->parentof that is array(id_son=>id_parent, ...)
4069 $this->loadParentOf();
4070
4071 // Init $this->users array
4072 $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
4073 $sql .= " FROM ".$this->db->prefix()."user as u";
4074 // Add fields from hooks
4075 $parameters = array();
4076 $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
4077 if ($reshook > 0) {
4078 $sql .= $hookmanager->resPrint;
4079 } else {
4080 $sql .= " WHERE u.entity IN (".getEntity('user').")";
4081 }
4082 if ($filter) {
4083 $sql .= forgeSQLFromUniversalSearchCriteria($filter);
4084 }
4085
4086 dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
4087 $resql = $this->db->query($sql);
4088 if ($resql) {
4089 $i = 0;
4090 while ($obj = $this->db->fetch_object($resql)) {
4091 $this->users[(int) $obj->rowid]
4092 = array(
4093 'rowid' => (int) $obj->rowid,
4094 'id' => (int) $obj->rowid,
4095 'fk_user' => (int) $obj->fk_user,
4096 'fk_soc' => (int) $obj->fk_soc,
4097 'firstname' => (string) $obj->firstname,
4098 'lastname' => (string) $obj->lastname,
4099 'login' => (string) $obj->login,
4100 'statut' => (int) $obj->statut,
4101 'entity' => (int) $obj->entity,
4102 'email' => (string) $obj->email,
4103 'gender' => (string) $obj->gender,
4104 'admin' => (int) $obj->admin,
4105 'photo' => (string) $obj->photo,
4106 // fields are filled with build_path_from_id_user
4107 'fullpath' => '',
4108 'fullname' => '',
4109 'level' => 0,
4110 );
4111 $i++;
4112 }
4113 } else {
4114 dol_print_error($this->db);
4115 return -1;
4116 }
4117
4118 // We add the fullpath property to each element of the first level (no parent exists)
4119 dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
4120 foreach ($this->users as $key => $val) {
4121 $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
4122 if ($result < 0) {
4123 $this->error = 'ErrorLoopInHierarchy';
4124 return -1;
4125 }
4126 }
4127
4128 // Exclude leaf including $deleteafterid from tree
4129 if ($deleteafterid) {
4130 //print "Look to discard user ".$deleteafterid."\n";
4131 $keyfilter1 = '^'.$deleteafterid.'$';
4132 $keyfilter2 = '_'.$deleteafterid.'$';
4133 $keyfilter3 = '^'.$deleteafterid.'_';
4134 $keyfilter4 = '_'.$deleteafterid.'_';
4135 foreach (array_keys($this->users) as $key) {
4136 $fullpath = (string) $this->users[$key]['fullpath'];
4137 if (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
4138 || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath)) {
4139 unset($this->users[$key]);
4140 }
4141 }
4142 }
4143
4144 dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
4145 $this->users = dol_sort_array($this->users, 'fullname', 'asc', 1, 0, 1);
4146
4147 return $this->users;
4148 }
4149
4158 public function getAllChildIds($addcurrentuser = 0)
4159 {
4160 $childids = array();
4161
4162 if (isset($this->cache_childids[$this->id])) {
4163 $childids = $this->cache_childids[$this->id];
4164 } else {
4165 // Init this->users
4166 $treeresult = $this->get_full_tree();
4167
4168 $idtoscan = $this->id;
4169
4170 dol_syslog("Build childid for id = ".$idtoscan);
4171 foreach ($this->users as $id => $val) {
4172 if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
4173 $childids[$val['id']] = $val['id'];
4174 }
4175 }
4176
4177 // A loop anywhere in the hierarchy aborts get_full_tree(), leaving the branches it had not
4178 // walked yet with an empty fullpath, so they silently drop out of the list above. Do not
4179 // cache such a truncated result, it would be reused for the whole request.
4180 if ($treeresult < 0) {
4181 dol_syslog(get_class($this)."::getAllChildIds got a truncated tree: ".$this->error, LOG_WARNING);
4182 return $addcurrentuser ? array($this->id => $this->id) : $childids;
4183 }
4184 }
4185 $this->cache_childids[$this->id] = $childids;
4186
4187 if ($addcurrentuser) {
4188 $childids[$this->id] = $this->id;
4189 }
4190
4191 return $childids;
4192 }
4193
4194 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4203 public function build_path_from_id_user($id_user, $protection = 0)
4204 {
4205 // phpcs:enable
4206 //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
4207
4208 if (!empty($this->users[$id_user]['fullpath'])) {
4209 // Already defined
4210 dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
4211 return 0;
4212 }
4213
4214 // Define fullpath and fullname
4215 $this->users[$id_user]['fullpath'] = '_'.$id_user;
4216 $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
4217 $i = 0;
4218 $cursor_user = $id_user;
4219
4220 $useridfound = array($id_user);
4221 while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) { // @phan-suppress-current-line PhanTypeMismatchProperty
4222 if (in_array($this->parentof[$cursor_user], $useridfound)) {
4223 dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
4224 return -1; // Should not happen. Protection against looping hierarchy
4225 }
4226 $useridfound[] = $this->parentof[$cursor_user];
4227 $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
4228 $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
4229 $i++;
4230 $cursor_user = $this->parentof[$cursor_user];
4231 }
4232
4233 // We count number of _ to have level
4234 $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
4235
4236 return 1;
4237 }
4238
4247 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4248 {
4249 $tables = array(
4250 'user',
4251 );
4252
4253 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4254 }
4255
4266 public static function replaceContact(DoliDB $dbs, $origin_id, $dest_id)
4267 {
4268 if (!CommonObject::commonReplaceContact($dbs, $origin_id, $dest_id, array('user'))) {
4269 return false;
4270 }
4271
4272 return CommonObject::commonReplaceContact($dbs, $origin_id, $dest_id, array('user_alert'), 'fk_contact');
4273 }
4274
4275
4281 public function loadStateBoard()
4282 {
4283 $this->nb = array();
4284
4285 $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
4286 $sql .= " FROM ".$this->db->prefix()."user as u";
4287 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4288 $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
4289 $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
4290 $sql .= " AND ug.fk_user = u.rowid";
4291 } else {
4292 $sql .= " WHERE u.entity IN (".getEntity('user').")";
4293 }
4294 $sql .= " AND u.statut > 0";
4295 //$sql.= " AND employee != 0";
4296
4297 $resql = $this->db->query($sql);
4298 if ($resql) {
4299 while ($obj = $this->db->fetch_object($resql)) {
4300 $this->nb["users"] = $obj->nb;
4301 }
4302 $this->db->free($resql);
4303 return 1;
4304 } else {
4305 dol_print_error($this->db);
4306 $this->error = $this->db->error();
4307 return -1;
4308 }
4309 }
4310
4322 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4323 {
4324 global $langs;
4325
4326 $langs->load("user");
4327
4328 // Set the '$modele' to the name of the document template (model) to use
4329 if (!dol_strlen($modele)) {
4330 if (getDolGlobalString('USER_ADDON_PDF')) {
4331 $modele = getDolGlobalString('USER_ADDON_PDF');
4332 } else {
4333 $modele = 'bluesky';
4334 }
4335 }
4336
4337 $modelpath = "core/modules/user/doc/";
4338
4339 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4340 }
4341
4342 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4350 public function user_get_property($rowid, $mode)
4351 {
4352 // phpcs:enable
4353 $user_property = '';
4354
4355 if (empty($rowid)) {
4356 return '';
4357 }
4358
4359 $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
4360 $sql .= " FROM ".$this->db->prefix()."user";
4361 $sql .= " WHERE rowid = ".((int) $rowid);
4362
4363 $resql = $this->db->query($sql);
4364 if ($resql) {
4365 $nump = $this->db->num_rows($resql);
4366
4367 if ($nump) {
4368 $obj = $this->db->fetch_object($resql);
4369
4370 if ($mode == 'email') {
4371 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
4372 } elseif ($mode == 'mobile') {
4373 $user_property = $obj->user_mobile;
4374 } elseif ($mode == 'name') {
4375 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname);
4376 }
4377 }
4378 return $user_property;
4379 } else {
4380 dol_print_error($this->db);
4381 }
4382
4383 return '';
4384 }
4385
4393 public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
4394 {
4396 global $conf;
4397
4398 $instanceuniqueid = empty($conf->file->instance_unique_id) ? '' : $conf->file->instance_unique_id;
4399 $encodedsecurekey = dol_hash($instanceuniqueid.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
4400 if (isModEnabled('multicompany')) {
4401 $entity_qr = '&entity='.((int) $conf->entity);
4402 } else {
4403 $entity_qr = '';
4404 }
4405 // Define $urlwithroot
4406 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
4407 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
4408 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
4409
4410 if ($typeofurl == 'internal') {
4411 $urlwithroot = DOL_URL_ROOT;
4412 }
4413
4414 return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
4415 }
4416
4430 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND', $entityfilter = false)
4431 {
4432 global $conf, $user;
4433
4434 $sql = "SELECT t.rowid";
4435 $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
4436
4437 if ($entityfilter) {
4438 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4439 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
4440 $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
4441 } else {
4442 $sql .= " WHERE t.entity = 0 OR EXISTS (";
4443 $sql .= " SELECT ug.rowid FROM " . $this->db->prefix() . "usergroup_user as ug";
4444 $sql .= " WHERE ug.fk_user = t.rowid AND ug.entity IN (" . getEntity('usergroup') . "))";
4445 }
4446 } else {
4447 $sql .= " WHERE t.entity IN (".getEntity('user').")";
4448 }
4449 } else {
4450 $sql .= " WHERE 1 = 1";
4451 }
4452
4453 // Manage filter
4454 $errormessage = '';
4455 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
4456 if ($errormessage) {
4457 $this->errors[] = $errormessage;
4458 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
4459 return -1;
4460 }
4461
4462 $sql .= $this->db->order($sortfield, $sortorder);
4463 if ($limit) {
4464 $sql .= $this->db->plimit($limit + 1, $offset);
4465 }
4466
4467 dol_syslog(__METHOD__, LOG_DEBUG);
4468
4469 $resql = $this->db->query($sql);
4470 if ($resql) {
4471 $this->users = array();
4472 $num = $this->db->num_rows($resql);
4473 if ($num) {
4474 while ($obj = $this->db->fetch_object($resql)) {
4475 $line = new self($this->db);
4476 $result = $line->fetch($obj->rowid);
4477 if ($result > 0 && !empty($line->id)) {
4478 $this->users[$obj->rowid] = clone $line;
4479 }
4480 }
4481 $this->db->free($resql);
4482 }
4483 return $num;
4484 } else {
4485 $this->errors[] = $this->db->lasterror();
4486 return -1;
4487 }
4488 }
4489
4497 private $findUserIdByEmailCache;
4498
4509 public function findUserIdByEmail($email)
4510 {
4511 if (isset($this->findUserIdByEmailCache[$email])) {
4512 return $this->findUserIdByEmailCache[$email];
4513 }
4514
4515 $this->findUserIdByEmailCache[$email] = -1;
4516
4517 $sql = 'SELECT rowid';
4518 $sql .= ' FROM '.$this->db->prefix().'user';
4519 if (getDolGlobalString('AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR')) {
4520 $sql .= " WHERE email LIKE '%".$this->db->escape($this->db->escapeforlike($email))."%'";
4521 } else {
4522 $sql .= " WHERE email = '".$this->db->escape($email)."'";
4523 }
4524 $sql .= ' LIMIT 1';
4525
4526 $resql = $this->db->query($sql);
4527 if (!$resql) {
4528 return -1;
4529 }
4530
4531 $obj = $this->db->fetch_object($resql);
4532 if (!$obj) {
4533 return -1;
4534 }
4535
4536 $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4537
4538 return $this->findUserIdByEmailCache[$email];
4539 }
4540
4547 public function cloneRights($fromId, $toId)
4548 {
4549 if (empty($fromId) || empty($toId)) {
4550 return -1;
4551 }
4552
4553 $this->db->begin();
4554
4555 // delete default rights for UserTo
4556 $sqlDelete = "DELETE FROM ".$this->db->prefix()."user_rights";
4557 $sqlDelete .= " WHERE fk_user = ".((int) $toId);
4558
4559 dol_syslog(get_class($this)."::clone_rights (delete default permissions)", LOG_DEBUG);
4560
4561 if (!$this->db->query($sqlDelete)) {
4562 $this->db->rollback();
4563 return -1;
4564 }
4565
4566 // Construction of the insertion request
4567 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id)";
4568 $sql .= " SELECT entity, ".((int) $toId).", fk_id";
4569 $sql .= " FROM ".$this->db->prefix()."user_rights src";
4570 $sql .= " WHERE fk_user = ".((int) $fromId);
4571 $sql .= " AND NOT EXISTS (";
4572 $sql .= " SELECT 1";
4573 $sql .= " FROM ".$this->db->prefix()."user_rights dest";
4574 $sql .= " WHERE dest.entity = src.entity";
4575 $sql .= " AND dest.fk_user = ".((int) $toId);
4576 $sql .= " AND dest.fk_id = src.fk_id";
4577 $sql .= " )";
4578
4579 dol_syslog(get_class($this)."::clone_rights", LOG_DEBUG);
4580
4581 // Execute request
4582 if (!$this->db->query($sql)) {
4583 $this->db->rollback();
4584 return -1;
4585 }
4586
4587 $this->db->commit();
4588 return 1;
4589 }
4590
4599 public function cloneCategories($fromId, $toId, $type = 'user')
4600 {
4601 $this->db->begin();
4602
4603 if (empty($type)) {
4604 $type = $this->table_element;
4605 }
4606
4607 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4608 $categorystatic = new Categorie($this->db);
4609
4610 $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_user)";
4611 $sql .= " SELECT fk_categorie, ".((int) $toId)." FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
4612 $sql .= " WHERE fk_user = ".((int) $fromId);
4613
4614 if (!$this->db->query($sql)) {
4615 $this->error = $this->db->lasterror();
4616 $this->db->rollback();
4617 return -1;
4618 }
4619
4620 $this->db->commit();
4621 return 1;
4622 }
4623}
global $dolibarr_main_url_root
$c
Definition line.php:353
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage members of a foundation.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage categories.
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...
fetchWarehouse($force_warehouse_id=0)
Load the warehouse of object, from id $this->warehouse_id or $this->fk_warehouse, into this->warehous...
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.
static commonReplaceContact(DoliDB $dbs, $origin_id, $dest_id, array $tables, $fieldname='fk_socpeople', $ignoreerrors=0)
Function used to replace a contact id with another one.
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.
static loadAndInstantiate($id, $db, $conf, $langs, $user)
Locate, load and instantiate a password generator/validator model by its id (the value stored in USER...
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).
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.
isNotIntoValidityDateRange()
Return a link with photo Use this->id,this->photo.
getNbOfUsers($limitTo, $option='', $admin=-1)
Return number of existing users.
removeFromGroup($group, $entity, $notrigger=0)
Remove a user from a group.
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)
$fields
Array with all fields and their property.
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.
setInGroup($group, $entity, $notrigger=0)
Add user into a group.
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
static replaceContact(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a contact id with another one when merging two contacts.
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
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
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:686
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:672
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
dol_now($mode='gmt')
Return date for now.
getDolGlobalLoginBadCharUnauthorized()
Return the list of unauthorized characters in user logins.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
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.
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
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_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.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
conf($dolibarr_main_document_root, $realpathconf=null)
Load conf file (file must exists)
Definition inc.php:431
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.
div refaddress div address