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