dolibarr 22.0.5
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-2025 Frédéric France <frederic.france@free.fr>
16 * Copyright (C) 2019 Abbes Bahfir <dolipar@dolipar.org>
17 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
18 * Copyright (C) 2024 Lenin Rivas <lenin.rivas777@gmail.com>
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 3 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <https://www.gnu.org/licenses/>.
32 */
33
40require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
41require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
42require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
43require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
44
45
49class User extends CommonObject
50{
51 use CommonPeople;
52
56 public $element = 'user';
57
61 public $table_element = 'user';
62
66 public $fk_element = 'fk_user';
67
71 public $picto = 'user';
72
76 public $id = 0;
77
83 public $statut;
84
88 public $status;
89
93 public $openid;
94
98 public $ldap_sid;
102 public $search_sid;
106 public $employee;
110 public $civility_code;
111
115 public $fullname;
116
120 public $gender;
121
125 public $birth;
126
130 public $email;
131
135 public $email_oauth2;
136
140 public $personal_email;
141
145 public $socialnetworks;
146
150 public $job;
151
155 public $signature;
156
160 public $office_phone;
161
165 public $office_fax;
166
170 public $user_mobile;
171
175 public $personal_mobile;
176
180 public $admin;
181
185 public $login;
186
190 public $api_key;
191
195 public $entity;
196
200 public $pass;
201
205 public $pass_crypted;
206
210 public $pass_indatabase;
211
215 public $pass_indatabase_crypted;
216
220 public $pass_temp;
221
227 public $datec;
228
234 public $datem;
235
239 public $socid;
240
244 public $contact_id;
245
249 public $fk_member;
250
254 public $fk_user;
255
259 public $fk_user_expense_validator;
260
264 public $fk_user_holiday_validator;
265
269 public $clicktodial_url;
270
274 public $clicktodial_login;
275
279 public $clicktodial_password;
280
284 public $clicktodial_poste;
285
289 public $clicktodial_loaded;
290
291
295 public $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
477 //private $egroupware_id;
478
483 public $usergroup_entity;
484
485 public $fields = array(
486 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
487 'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 20, 'searchall' => 1),
488 'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1),
489 'ref_employee' => array('type' => 'varchar(50)', 'label' => 'RefEmployee', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 30, 'searchall' => 1),
490 'national_registration_number' => array('type' => 'varchar(50)', 'label' => 'NationalRegistrationNumber', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 40, 'searchall' => 1)
491 );
492
493 const STATUS_DISABLED = 0;
494 const STATUS_ENABLED = 1;
495
501 public function __construct($db)
502 {
503 $this->db = $db;
504
505 $this->ismultientitymanaged = 1;
506 $this->isextrafieldmanaged = 1;
507 // User preference
508 $this->clicktodial_loaded = 0;
509
510 // For cache usage
511 $this->all_permissions_are_loaded = 0;
512 $this->nb_rights = 0;
513
514 // Force some default values
515 $this->admin = 0;
516 $this->employee = 1;
517
518 $this->conf = new stdClass();
519 $this->rights = new stdClass();
520 $this->rights->user = new stdClass();
521 $this->rights->user->user = new stdClass();
522 $this->rights->user->self = new stdClass();
523 $this->rights->user->user_advance = new stdClass();
524 $this->rights->user->self_advance = new stdClass();
525 $this->rights->user->group_advance = new stdClass();
526 }
527
542 public function fetch($id = 0, $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1, $email = '', $fk_socpeople = 0, $use_email_oauth2 = 0)
543 {
544 global $conf, $user;
545
546 // Clean parameters
547 $login = trim($login);
548
549 // Get user
550 $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.civility as civility_code, u.birth, u.job,";
551 $sql .= " u.email, u.email_oauth2, u.personal_email,";
552 $sql .= " u.socialnetworks,";
553 $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile, u.personal_mobile,";
554 $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
555 $sql .= " u.admin, u.login, u.note_private, u.note_public,";
556 $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.api_key,";
557 $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,";
558 $sql .= " u.statut as status, u.lang, u.entity,";
559 $sql .= " u.datec as datec,";
560 $sql .= " u.tms as datem,";
561 $sql .= " u.datelastlogin as datel,";
562 $sql .= " u.datepreviouslogin as datep,";
563 $sql .= " u.flagdelsessionsbefore,";
564 $sql .= " u.iplastlogin,";
565 $sql .= " u.ippreviouslogin,";
566 $sql .= " u.datelastpassvalidation,";
567 $sql .= " u.datestartvalidity,";
568 $sql .= " u.dateendvalidity,";
569 $sql .= " u.photo as photo,";
570 $sql .= " u.openid as openid,";
571 $sql .= " u.accountancy_code_user_general,";
572 $sql .= " u.accountancy_code,";
573 $sql .= " u.thm,";
574 $sql .= " u.tjm,";
575 $sql .= " u.salary,";
576 $sql .= " u.salaryextra,";
577 $sql .= " u.weeklyhours,";
578 $sql .= " u.color,";
579 $sql .= " u.dateemployment, u.dateemploymentend,";
580 $sql .= " u.fk_warehouse,";
581 $sql .= " u.ref_ext,";
582 $sql .= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode
583 $sql .= " u.national_registration_number,";
584 $sql .= " u.ref_employee,";
585 $sql .= " c.code as country_code, c.label as country,";
586 $sql .= " d.code_departement as state_code, d.nom as state,";
587 $sql .= " s.label as label_establishment, u.fk_establishment";
588 $sql .= " FROM ".$this->db->prefix()."user as u";
589 $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as c ON u.fk_country = c.rowid";
590 $sql .= " LEFT JOIN ".$this->db->prefix()."c_departements as d ON u.fk_state = d.rowid";
591 $sql .= " LEFT JOIN ".$this->db->prefix()."establishment as s ON u.fk_establishment = s.rowid";
592
593 if ($id > 0) {
594 $sql .= " WHERE u.rowid = ".((int) $id);
595 } else {
596 if ($entity < 0) {
597 if ((! isModEnabled('multicompany') || ! getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) && (! empty($user->entity))) {
598 $sql .= " WHERE u.entity IN (0, " . ((int) $conf->entity) . ")";
599 } else {
600 $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
601 }
602 } else {
603 // The fetch was forced on an entity
604 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
605 $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
606 } else {
607 if ($entity != '' && $entity == 0) { // If $entity = 0
608 $sql .= " WHERE u.entity = 0";
609 } else { // if $entity is -1 or > 0
610 $sql .= " WHERE u.entity IN (0, " . ((int) ($entity > 0 ? $entity : $conf->entity)) . ")";
611 }
612 }
613 }
614 }
615
616 if ($sid) {
617 // permet une recherche du user par son SID ActiveDirectory ou Samba
618 $sql .= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."')";
619 } elseif ($login) {
620 $sql .= " AND u.login = '".$this->db->escape($login)."'";
621 } elseif ($email) {
622 $sql .= " AND (u.email = '".$this->db->escape($email)."'";
623 if ($use_email_oauth2) {
624 $sql .= " OR u.email_oauth2 = '".$this->db->escape($email)."'";
625 }
626 $sql .= ")";
627 } elseif ($fk_socpeople > 0) {
628 $sql .= " AND u.fk_socpeople = ".((int) $fk_socpeople);
629 }
630
631 $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
632
633 if ($sid) {
634 // permet une recherche du user par son SID ActiveDirectory ou Samba
635 $sql .= ' '.$this->db->plimit(1);
636 }
637
638 $resql = $this->db->query($sql);
639 if ($resql) {
640 $num = $this->db->num_rows($resql);
641 if ($num > 1) {
642 $this->error = "USERDUPLICATEFOUND";
643 dol_syslog(get_class($this)."::fetch more than 1 user found", LOG_WARNING);
644
645 $this->db->free($resql);
646 return 0;
647 }
648
649 $obj = $this->db->fetch_object($resql);
650 if ($obj) {
651 $this->id = $obj->rowid;
652 $this->ref = $obj->rowid;
653
654 $this->ref_ext = $obj->ref_ext;
655
656 $this->ldap_sid = $obj->ldap_sid;
657 $this->civility_code = $obj->civility_code;
658 $this->lastname = $obj->lastname;
659 $this->firstname = $obj->firstname;
660 $this->ref_employee = $obj->ref_employee;
661 $this->national_registration_number = $obj->national_registration_number;
662
663 $this->employee = $obj->employee;
664
665 $this->login = $obj->login;
666 $this->gender = $obj->gender;
667 $this->birth = $this->db->jdate($obj->birth);
668 $this->pass_indatabase = $obj->pass;
669 $this->pass_indatabase_crypted = $obj->pass_crypted;
670 $this->pass = $obj->pass;
671 $this->pass_temp = $obj->pass_temp;
672 $this->datelastpassvalidation = $obj->datelastpassvalidation;
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
696 $this->job = $obj->job;
697 $this->signature = $obj->signature;
698 $this->admin = $obj->admin;
699 $this->note_public = $obj->note_public;
700 $this->note_private = $obj->note_private;
701
702 $this->statut = $obj->status; // deprecated
703 $this->status = $obj->status;
704
705 $this->photo = $obj->photo;
706 $this->openid = $obj->openid;
707 $this->lang = $obj->lang;
708 $this->entity = $obj->entity;
709
710 $this->accountancy_code_user_general = $obj->accountancy_code_user_general;
711 $this->accountancy_code = $obj->accountancy_code;
712
713 $this->thm = $obj->thm;
714 $this->tjm = $obj->tjm;
715 $this->salary = $obj->salary;
716 $this->salaryextra = $obj->salaryextra;
717 $this->weeklyhours = $obj->weeklyhours;
718 $this->color = $obj->color;
719 $this->dateemployment = $this->db->jdate($obj->dateemployment);
720 $this->dateemploymentend = $this->db->jdate($obj->dateemploymentend);
721
722 $this->datec = $this->db->jdate($obj->datec);
723 $this->datem = $this->db->jdate($obj->datem);
724 $this->datelastlogin = $this->db->jdate($obj->datel);
725 $this->datepreviouslogin = $this->db->jdate($obj->datep);
726 $this->flagdelsessionsbefore = $this->db->jdate($obj->flagdelsessionsbefore, 'gmt');
727 $this->iplastlogin = $obj->iplastlogin;
728 $this->ippreviouslogin = $obj->ippreviouslogin;
729 $this->datestartvalidity = $this->db->jdate($obj->datestartvalidity);
730 $this->dateendvalidity = $this->db->jdate($obj->dateendvalidity);
731
732 $this->socid = $obj->fk_soc;
733 $this->contact_id = $obj->fk_socpeople;
734 $this->fk_member = $obj->fk_member;
735 $this->fk_user = $obj->fk_user;
736 $this->fk_user_expense_validator = $obj->fk_user_expense_validator;
737 $this->fk_user_holiday_validator = $obj->fk_user_holiday_validator;
738
739 $this->default_range = $obj->default_range;
740 $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
741 $this->fk_warehouse = $obj->fk_warehouse;
742 $this->fk_establishment = $obj->fk_establishment;
743 $this->label_establishment = $obj->label_establishment;
744
745 // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
746 // in such case, this admin user must be admin for ALL entities.
747 if (!isModEnabled('multicompany') && $this->admin && $this->entity == 1) {
748 $this->entity = 0;
749 }
750
751 // Retrieve all extrafield
752 // fetch optionals attributes and labels
753 $this->fetch_optionals();
754
755 $this->db->free($resql);
756 } else {
757 $this->error = "USERNOTFOUND";
758 dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
759
760 $this->db->free($resql);
761 return 0;
762 }
763 } else {
764 $this->error = $this->db->lasterror();
765 return -1;
766 }
767
768 // To get back the global configuration unique to the user
769 if ($loadpersonalconf) {
770 $result = $this->loadPersonalConf();
771
772 $result = $this->loadDefaultValues();
773
774 if ($result < 0) {
775 $this->error = $this->db->lasterror();
776 return -3;
777 }
778 }
779
780 // Add option to allow an admin internal user to make quick debug for internal users. Not yet implemented completely.
781 // This is a special cas that is allowed to have a GETPOST inside a class.
782 if (GETPOSTINT('forceexternaluser') && $this->admin && empty($this->socid)) {
783 $this->socid = GETPOSTINT('forceexternaluser');
784 }
785
786 return 1;
787 }
788
789
795 public function loadPersonalConf()
796 {
797 global $conf;
798
799 // Load user->conf for user
800 $sql = "SELECT param, value FROM ".$this->db->prefix()."user_param";
801 $sql .= " WHERE fk_user = ".((int) $this->id);
802 $sql .= " AND entity = ".((int) $conf->entity);
803 //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
804 $resql = $this->db->query($sql);
805 if ($resql) {
806 $num = $this->db->num_rows($resql);
807 $i = 0;
808 while ($i < $num) {
809 $obj = $this->db->fetch_object($resql);
810 $p = (!empty($obj->param) ? $obj->param : '');
811 if (!empty($p)) {
812 $this->conf->$p = $obj->value;
813 }
814 $i++;
815 }
816 $this->db->free($resql);
817
818 return $num;
819 } else {
820 $this->error = $this->db->lasterror();
821
822 return -2;
823 }
824 }
825
831 public function loadDefaultValues()
832 {
833 global $conf;
834
835 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
836 // Load user->default_values for user. TODO Save this in memcached ?
837 require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php';
838
839 $defaultValues = new DefaultValues($this->db);
840 $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)
841 //$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)
842
843 if (!is_array($result) && $result < 0) {
844 setEventMessages($defaultValues->error, $defaultValues->errors, 'errors');
845 dol_print_error($this->db);
846 return -1;
847 } elseif (count($result) > 0) {
848 foreach ($result as $defval) {
849 if (!empty($defval->page) && !empty($defval->type) && !empty($defval->param)) {
850 $pagewithoutquerystring = $defval->page;
851 $pagequeries = '';
852 $reg = array();
853 if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
854 $pagewithoutquerystring = $reg[1];
855 $pagequeries = $reg[2];
856 }
857 $this->default_values[$pagewithoutquerystring][$defval->type][$pagequeries ? $pagequeries : '_noquery_'][$defval->param] = $defval->value;
858 }
859 }
860 }
861 if (!empty($this->default_values)) {
862 foreach ($this->default_values as $a => $b) {
863 foreach ($b as $c => $d) {
864 krsort($this->default_values[$a][$c]);
865 }
866 }
867 }
868 }
869 return 1;
870 }
871
883 public function hasRight($module, $permlevel1, $permlevel2 = '')
884 {
885 // For compatibility with bad naming permissions on module
886 $moduletomoduletouse = array(
887 'category' => 'categorie',
888 'compta' => 'comptabilite',
889 'contract' => 'contrat',
890 'member' => 'adherent',
891 'mo' => 'mrp',
892 'order' => 'commande',
893 'produit' => 'product',
894 'productlot' => 'product',
895 'project' => 'projet',
896 'propale' => 'propal',
897 'shipping' => 'expedition',
898 'task' => 'task@projet',
899 'fichinter' => 'ficheinter',
900 'inventory' => 'stock',
901 'invoice' => 'facture',
902 'invoice_supplier' => 'fournisseur',
903 'order_supplier' => 'fournisseur',
904 'knowledgerecord' => 'knowledgerecord@knowledgemanagement',
905 'skill@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
906 'job@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
907 'position@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
908 'facturerec' => 'facture',
909 'margins' => 'margin',
910 );
911
912 if (!empty($moduletomoduletouse[$module])) {
913 $module = $moduletomoduletouse[$module];
914 }
915
916 $moduleRightsMapping = array(
917 'product' => 'produit',
918 'margin' => 'margins',
919 'comptabilite' => 'compta'
920 );
921
922 $rightsPath = $module;
923 if (!empty($moduleRightsMapping[$rightsPath])) {
924 $rightsPath = $moduleRightsMapping[$rightsPath];
925 }
926
927 // If module is abc@module, we check permission user->hasRight(module, abc, permlevel1)
928 $tmp = explode('@', $rightsPath, 2);
929 if (!empty($tmp[1])) {
930 if (strpos($module, '@') !== false) {
931 $module = $tmp[1];
932 }
933 if ($tmp[0] != $tmp[1]) {
934 // If $module = 'myobject@mymodule'
935 $rightsPath = $tmp[1];
936 $permlevel2 = $permlevel1;
937 $permlevel1 = $tmp[0];
938 } else {
939 // If $module = 'abc@abc'
940 $rightsPath = $tmp[1];
941 }
942 }
943
944 // In $conf->modules, we have 'accounting', 'product', 'facture', ...
945 // In $user->rights, we have 'accounting', 'produit', 'facture', ...
946 //var_dump($this->rights->$rightsPath);
947 //var_dump($conf->modules);
948 //if ($module == 'fournisseur') { var_dump($module.' '.isModEnabled($module).' '.$rightsPath.' '.$permlevel1.' '.$permlevel2); }
949
950 if (!isModEnabled($module)) {
951 return 0;
952 }
953
954 // Special case for external user
955 if (!empty($this->socid)) {
956 if ($module == 'societe' && ($permlevel1 == 'creer' || $permlevel1 == 'write')) {
957 return 0; // An external user never has the permission ->societe->write to see all thirdparties (always restricted to himself)
958 }
959 if ($module == 'societe' && $permlevel1 == 'client' && $permlevel2 == 'voir') {
960 return 0; // An external user never has the permission ->societe->client->voir to see all thirdparties (always restricted to himself)
961 }
962 if ($module == 'societe' && $permlevel1 == 'export') {
963 return 0; // An external user never has the permission ->societe->export to see all thirdparties (always restricted to himself)
964 }
965 if ($module == 'societe' && ($permlevel1 == 'supprimer' || $permlevel1 == 'delete')) {
966 return 0; // An external user never has the permission ->societe->delete to see all thirdparties (always restricted to himself)
967 }
968 }
969
970 // For compatibility with bad naming permissions on permlevel1
971 if ($permlevel1 == 'propale') {
972 $permlevel1 = 'propal';
973 }
974 if ($permlevel1 == 'member') {
975 $permlevel1 = 'adherent';
976 }
977 if ($permlevel1 == 'recruitmentcandidature') {
978 $permlevel1 = 'recruitmentjobposition';
979 }
980
981 //var_dump($this->rights);
982 //var_dump($rightsPath.' '.$permlevel1.' '.$permlevel2);
983 if (empty($rightsPath) || empty($this->rights) || empty($this->rights->$rightsPath) || empty($permlevel1)) {
984 return 0;
985 }
986
987 if ($permlevel2) {
988 if (!empty($this->rights->$rightsPath->$permlevel1)) {
989 if (!empty($this->rights->$rightsPath->$permlevel1->$permlevel2)) {
990 return $this->rights->$rightsPath->$permlevel1->$permlevel2;
991 }
992 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
993 // instead of "read", "write", "delete"
994 if ($permlevel2 == 'read' && !empty($this->rights->$rightsPath->$permlevel1->lire)) {
995 return $this->rights->$rightsPath->$permlevel1->lire;
996 }
997 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->creer)) {
998 return $this->rights->$rightsPath->$permlevel1->creer;
999 }
1000 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->create)) {
1001 return $this->rights->$rightsPath->$permlevel1->create;
1002 }
1003 if ($permlevel2 == 'delete' && !empty($this->rights->$rightsPath->$permlevel1->supprimer)) {
1004 return $this->rights->$rightsPath->$permlevel1->supprimer;
1005 }
1006 }
1007 } else {
1008 if (!empty($this->rights->$rightsPath->$permlevel1)) {
1009 return $this->rights->$rightsPath->$permlevel1;
1010 }
1011 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
1012 // instead of "read", "write", "delete"
1013 if ($permlevel1 == 'read' && !empty($this->rights->$rightsPath->lire)) {
1014 return $this->rights->$rightsPath->lire;
1015 }
1016 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->creer)) {
1017 return $this->rights->$rightsPath->creer;
1018 }
1019 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->create)) {
1020 return $this->rights->$rightsPath->create;
1021 }
1022 if ($permlevel1 == 'delete' && !empty($this->rights->$rightsPath->supprimer)) {
1023 return $this->rights->$rightsPath->supprimer;
1024 }
1025 }
1026
1027 return 0;
1028 }
1029
1041 public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1042 {
1043 global $conf, $user, $langs;
1044
1045 $entity = (empty($entity) ? $conf->entity : $entity);
1046
1047 dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity, $notrigger for user id=".$this->id);
1048
1049 if (empty($this->id)) {
1050 $this->error = 'Try to call addrights on an object user with an empty id';
1051 return -1;
1052 }
1053
1054 $error = 0;
1055 $whereforadd = '';
1056
1057 $this->db->begin();
1058
1059 if (!empty($rid)) {
1060 $module = $perms = $subperms = '';
1061
1062 // If we ask to add a given permission, we first load properties of this permission (module, perms and subperms).
1063 $sql = "SELECT module, perms, subperms";
1064 $sql .= " FROM ".$this->db->prefix()."rights_def";
1065 $sql .= " WHERE id = ".((int) $rid);
1066 $sql .= " AND entity = ".((int) $entity);
1067
1068 $result = $this->db->query($sql);
1069 if ($result) {
1070 $obj = $this->db->fetch_object($result);
1071
1072 if ($obj) {
1073 $module = $obj->module;
1074 $perms = $obj->perms;
1075 $subperms = $obj->subperms;
1076 }
1077 } else {
1078 $error++;
1079 dol_print_error($this->db);
1080 }
1081
1082 // Define the where for the permission to add
1083 $whereforadd = "id=".((int) $rid);
1084 // Add also inherited permissions
1085 if (!empty($subperms)) {
1086 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))";
1087 } elseif (!empty($perms)) {
1088 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND (subperms IS NULL or subperms = ''))";
1089 }
1090 } else {
1091 // A list of permission was requested (not a single specific permission)
1092 // based on the name of a module of permissions
1093 // Used in the where clause to determine the list of permissions to add.
1094 if (!empty($allmodule)) {
1095 if ($allmodule == 'allmodules') {
1096 $whereforadd = 'allmodules';
1097 } else {
1098 $whereforadd = "module='".$this->db->escape($allmodule)."'";
1099 if (!empty($allperms)) {
1100 $whereforadd .= " AND perms='".$this->db->escape($allperms)."'";
1101 }
1102 }
1103 }
1104 }
1105
1106 // Add automatically other permission using the criteria whereforadd
1107 // $whereforadd can be a SQL filter or the string 'allmodules'
1108 if (!empty($whereforadd)) {
1109 //print "$module-$perms-$subperms";
1110 $sql = "SELECT id";
1111 $sql .= " FROM ".$this->db->prefix()."rights_def";
1112 $sql .= " WHERE entity = ".((int) $entity);
1113 if (!empty($whereforadd) && $whereforadd != 'allmodules') {
1114 $sql .= " AND (".$whereforadd.")"; // Note: parenthesis are important because whereforadd can contains OR. Also note that $whereforadd is already sanitized
1115 }
1116
1117 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1118 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1119 $sqldelete .= $sql;
1120 $sqldelete .= ") AND entity = ".((int) $entity);
1121 if (!$this->db->query($sqldelete)) {
1122 $error++;
1123 }
1124
1125 if (!$error) {
1126 $resql = $this->db->query($sql);
1127 if ($resql) {
1128 $num = $this->db->num_rows($resql);
1129 $i = 0;
1130 while ($i < $num) {
1131 $obj = $this->db->fetch_object($resql);
1132
1133 if ($obj) {
1134 $nid = $obj->id;
1135
1136 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id) VALUES (".((int) $entity).", ".((int) $this->id).", ".((int) $nid).")";
1137 if (!$this->db->query($sql)) {
1138 $error++;
1139 }
1140 }
1141
1142 $i++;
1143 }
1144 } else {
1145 $error++;
1146 dol_print_error($this->db);
1147 }
1148 }
1149 }
1150
1151 if (!$error && !$notrigger) {
1152 $langs->load("other");
1153 $this->context = array('audit' => $langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : ''));
1154
1155 // Call trigger
1156 $result = $this->call_trigger('USER_MODIFY', $user);
1157 if ($result < 0) {
1158 $error++;
1159 }
1160 // End call triggers
1161 }
1162
1163 if ($error) {
1164 $this->db->rollback();
1165 return -$error;
1166 } else {
1167 $this->db->commit();
1168 return 1;
1169 }
1170 }
1171
1172
1184 public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1185 {
1186 global $conf, $user, $langs;
1187
1188 $error = 0;
1189 $wherefordel = '';
1190 $entity = (!empty($entity) ? $entity : $conf->entity);
1191
1192 $this->db->begin();
1193
1194 if (!empty($rid)) {
1195 $module = $perms = $subperms = '';
1196
1197 // When the request is to delete a specific permissions, this gets the
1198 // les charactis for the module, permissions and sub-permission of this permission.
1199 $sql = "SELECT module, perms, subperms";
1200 $sql .= " FROM ".$this->db->prefix()."rights_def";
1201 $sql .= " WHERE id = '".((int) $rid)."'";
1202 $sql .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1203
1204 $result = $this->db->query($sql);
1205 if ($result) {
1206 $obj = $this->db->fetch_object($result);
1207
1208 if ($obj) {
1209 $module = $obj->module;
1210 $perms = $obj->perms;
1211 $subperms = $obj->subperms;
1212 }
1213 } else {
1214 $error++;
1215 dol_print_error($this->db);
1216 }
1217
1218 // Where clause for the list of permissions to delete
1219 $wherefordel = "id=".((int) $rid);
1220 // Suppression des droits induits
1221 if ($subperms == 'lire' || $subperms == 'read') {
1222 $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)";
1223 }
1224 if ($perms == 'lire' || $perms == 'read') {
1225 $wherefordel .= " OR (module='".$this->db->escape($module)."')";
1226 }
1227 } else {
1228 // The deletion of the permissions concerns the name of a module or
1229 // list of permissions.
1230 // Used in the Where clause to determine the list of permission to delete
1231 if (!empty($allmodule)) {
1232 if ($allmodule == 'allmodules') {
1233 $wherefordel = 'allmodules';
1234 } else {
1235 $wherefordel = "module='".$this->db->escape($allmodule)."'";
1236 if (!empty($allperms)) {
1237 $wherefordel .= " AND perms='".$this->db->escape($allperms)."'";
1238 }
1239 }
1240 }
1241 }
1242
1243 // Delete permission according to a criteria set into $wherefordel
1244 if (!empty($wherefordel)) {
1245 //print "$module-$perms-$subperms";
1246 $sql = "SELECT id";
1247 $sql .= " FROM ".$this->db->prefix()."rights_def";
1248 $sql .= " WHERE entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1249 if (!empty($wherefordel) && $wherefordel != 'allmodules') {
1250 $sql .= " AND (".$wherefordel.")"; // Note: parenthesis are important because wherefordel can contains OR. Also note that $wherefordel is already sanitized
1251 }
1252
1253 // avoid admin to remove his own important rights
1254 if ($this->admin == 1) {
1255 $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
1256 $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
1257 $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
1258 $sql .= " AND id NOT IN (358)"; // user export
1259 }
1260
1261 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1262 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1263 $sqldelete .= $sql;
1264 $sqldelete .= ")";
1265 $sqldelete .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1266
1267 $resql = $this->db->query($sqldelete);
1268 if (!$resql) {
1269 $error++;
1270 dol_print_error($this->db);
1271 }
1272 }
1273
1274 if (!$error && !$notrigger) {
1275 $langs->load("other");
1276 $this->context = array('audit' => $langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : ''));
1277
1278 // Call trigger
1279 $result = $this->call_trigger('USER_MODIFY', $user);
1280 if ($result < 0) {
1281 $error++;
1282 }
1283 // End call triggers
1284 }
1285
1286 if ($error) {
1287 $this->db->rollback();
1288 return -$error;
1289 } else {
1290 $this->db->commit();
1291 return 1;
1292 }
1293 }
1294
1295
1302 public function clearrights()
1303 {
1304 dol_syslog(get_class($this)."::clearrights reset user->rights");
1305 $this->rights = new stdClass();
1306 $this->nb_rights = 0;
1307 $this->all_permissions_are_loaded = 0;
1308 $this->_tab_loaded = array();
1309 }
1310
1311
1320 public function loadRights($moduletag = '', $forcereload = 0)
1321 {
1322 global $conf;
1323
1324 $alreadyloaded = false;
1325
1326 if (empty($forcereload)) {
1327 if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
1328 // Rights for this module are already loaded, so we leave
1329 $alreadyloaded = true;
1330 }
1331
1332 if (!empty($this->all_permissions_are_loaded)) {
1333 // We already loaded all rights for this user, so we leave
1334 $alreadyloaded = true;
1335 }
1336 }
1337
1338 // More init to avoid warnings/errors
1339 if (!isset($this->rights) || !is_object($this->rights)) {
1340 $this->rights = new stdClass();
1341 }
1342 if (!isset($this->rights->user) || !is_object($this->rights->user)) {
1343 $this->rights->user = new stdClass();
1344 }
1345
1346 // Get permission of users + Get permissions of groups
1347
1348 if (!$alreadyloaded) {
1349 // First user permissions
1350 $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1351 $sql .= " FROM ".$this->db->prefix()."user_rights as ur,";
1352 $sql .= " ".$this->db->prefix()."rights_def as r";
1353 $sql .= " WHERE r.id = ur.fk_id";
1354 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1355 // On old version, we used entity defined into table r only
1356 // @FIXME Test on MULTICOMPANY_BACKWARD_COMPATIBILITY is a very strange business rules because the select should be always the
1357 // same than into user->loadRights() in user/perms.php and user/group/perms.php
1358 // We should never use and remove this case.
1359 $sql .= " AND r.entity IN (0,".(isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') ? "1," : "").$conf->entity.")";
1360 } else {
1361 // On table r=rights_def, the unique key is (id, entity) because id is hard coded into module descriptor and inserted during module activation.
1362 // So we must include the filter on entity on both table r. and ur.
1363 $sql .= " AND r.entity = ".((int) $conf->entity)." AND ur.entity = ".((int) $conf->entity);
1364 }
1365 $sql .= " AND ur.fk_user = ".((int) $this->id);
1366 $sql .= " AND r.perms IS NOT NULL";
1367 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1368 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1369 }
1370 if ($moduletag) {
1371 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1372 }
1373
1374 $resql = $this->db->query($sql);
1375 if ($resql) {
1376 $num = $this->db->num_rows($resql);
1377 $i = 0;
1378 while ($i < $num) {
1379 $obj = $this->db->fetch_object($resql);
1380
1381 if ($obj) {
1382 $module = $obj->module;
1383 $perms = $obj->perms;
1384 $subperms = $obj->subperms;
1385
1386 if (!empty($perms)) {
1387 if (!empty($module)) {
1388 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1389 $this->rights->$module = new stdClass();
1390 }
1391 if (!empty($subperms)) {
1392 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1393 $this->rights->$module->$perms = new stdClass();
1394 }
1395 if (empty($this->rights->$module->$perms->$subperms)) { // if not already counted
1396 $this->nb_rights++;
1397 }
1398 $this->rights->$module->$perms->$subperms = 1;
1399 } else {
1400 if (empty($this->rights->$module->$perms)) { // if not already counted
1401 $this->nb_rights++;
1402 }
1403 $this->rights->$module->$perms = 1;
1404 }
1405 }
1406 }
1407 }
1408 $i++;
1409 }
1410 $this->db->free($resql);
1411 }
1412
1413 // Now permissions of groups
1414 $sql = "SELECT DISTINCT r.module, r.perms, r.subperms, r.entity";
1415 $sql .= " FROM ".$this->db->prefix()."usergroup_rights as gr,";
1416 $sql .= " ".$this->db->prefix()."usergroup_user as gu,";
1417 $sql .= " ".$this->db->prefix()."rights_def as r";
1418 $sql .= " WHERE r.id = gr.fk_id";
1419 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1420 // @FIXME Test on MULTICOMPANY_BACKWARD_COMPATIBILITY is a very strange business rules because the select should be always the
1421 // same than into user->loadRights() in user/perms.php and user/group/perms.php
1422 // We should never use and remove this case.
1423 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1424 $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1425 } else {
1426 $sql .= " AND r.entity = ".((int) $conf->entity);
1427 }
1428 } else {
1429 $sql .= " AND gr.entity = ".((int) $conf->entity); // Only groups created in current entity
1430 // The entity on the table gu=usergroup_user should be useless and should never be used because it is already into gr and r.
1431 // but when using MULTICOMPANY_TRANSVERSE_MODE, we may have inserted record that make rubbish result here due to the duplicate record of
1432 // other entities, so we are forced to add a filter on gu here
1433 $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1434 $sql .= " AND r.entity = ".((int) $conf->entity); // Only permission of modules enabled in current entity
1435 }
1436 // End of strange business rule
1437 $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
1438 $sql .= " AND gu.fk_user = ".((int) $this->id);
1439 $sql .= " AND r.perms IS NOT NULL";
1440 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1441 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1442 }
1443 if ($moduletag) {
1444 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1445 }
1446
1447 $resql = $this->db->query($sql);
1448 if ($resql) {
1449 $num = $this->db->num_rows($resql);
1450 $i = 0;
1451 while ($i < $num) {
1452 $obj = $this->db->fetch_object($resql);
1453
1454 if ($obj) {
1455 $module = $obj->module;
1456 $perms = $obj->perms;
1457 $subperms = $obj->subperms;
1458
1459 if (!empty($perms)) {
1460 if (!empty($module)) {
1461 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1462 $this->rights->$module = new stdClass();
1463 }
1464 if (!empty($subperms)) {
1465 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1466 $this->rights->$module->$perms = new stdClass();
1467 }
1468 if (empty($this->rights->$module->$perms->$subperms)) { // if not already counted
1469 $this->nb_rights++;
1470 }
1471 $this->rights->$module->$perms->$subperms = 1;
1472 } else {
1473 // 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
1474 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1475 if (empty($this->rights->$module->$perms)) { // if not already counted
1476 $this->nb_rights++;
1477 }
1478 $this->rights->$module->$perms = 1;
1479 }
1480 }
1481 }
1482 }
1483 }
1484 $i++;
1485 }
1486 $this->db->free($resql);
1487 }
1488
1489 // Force permission on user for admin
1490 if (!empty($this->admin)) {
1491 if (empty($this->rights->user->user)) {
1492 $this->rights->user->user = new stdClass();
1493 }
1494 $listofpermtotest = array('lire', 'creer', 'password', 'supprimer', 'export');
1495 foreach ($listofpermtotest as $permtotest) {
1496 if (empty($this->rights->user->user->$permtotest)) {
1497 $this->rights->user->user->$permtotest = 1;
1498 $this->nb_rights++;
1499 }
1500 }
1501 if (empty($this->rights->user->self)) {
1502 $this->rights->user->self = new stdClass();
1503 }
1504 $listofpermtotest = array('creer', 'password');
1505 foreach ($listofpermtotest as $permtotest) {
1506 if (empty($this->rights->user->self->$permtotest)) {
1507 $this->rights->user->self->$permtotest = 1;
1508 $this->nb_rights++;
1509 }
1510 }
1511 // Add test on advanced permissions
1512 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1513 if (empty($this->rights->user->user_advance)) {
1514 $this->rights->user->user_advance = new stdClass();
1515 }
1516 $listofpermtotest = array('readperms', 'write');
1517 foreach ($listofpermtotest as $permtotest) {
1518 if (empty($this->rights->user->user_advance->$permtotest)) {
1519 $this->rights->user->user_advance->$permtotest = 1;
1520 $this->nb_rights++;
1521 }
1522 }
1523 if (empty($this->rights->user->self_advance)) {
1524 $this->rights->user->self_advance = new stdClass();
1525 }
1526 $listofpermtotest = array('readperms', 'writeperms');
1527 foreach ($listofpermtotest as $permtotest) {
1528 if (empty($this->rights->user->self_advance->$permtotest)) {
1529 $this->rights->user->self_advance->$permtotest = 1;
1530 $this->nb_rights++;
1531 }
1532 }
1533 if (empty($this->rights->user->group_advance)) {
1534 $this->rights->user->group_advance = new stdClass();
1535 }
1536 $listofpermtotest = array('read', 'readperms', 'write', 'delete');
1537 foreach ($listofpermtotest as $permtotest) {
1538 if (empty($this->rights->user) || empty($this->rights->user->group_advance->$permtotest)) {
1539 $this->rights->user->group_advance->$permtotest = 1;
1540 $this->nb_rights++;
1541 }
1542 }
1543 }
1544 }
1545
1546 // For backward compatibility
1547 if (isset($this->rights->propale) && !isset($this->rights->propal)) {
1548 $this->rights->propal = $this->rights->propale;
1549 }
1550 if (isset($this->rights->propal) && !isset($this->rights->propale)) {
1551 $this->rights->propale = $this->rights->propal;
1552 }
1553
1554 if (!$moduletag) {
1555 // If the module was not define, then everything is loaded.
1556 // Therefore, we can consider that the permissions are cached
1557 // because they were all loaded for this user instance.
1558 $this->all_permissions_are_loaded = 1;
1559 } else {
1560 // If the module is defined, we flag it as loaded into cache
1561 $this->_tab_loaded[$moduletag] = 1;
1562 }
1563 }
1564 }
1565
1578 public function getrights($moduletag = '', $forcereload = 0)
1579 {
1580 $this->loadRights($moduletag, $forcereload);
1581 }
1582
1589 public function setstatus($status)
1590 {
1591 global $conf, $langs, $user;
1592
1593 $error = 0;
1594
1595 // Check parameters
1596 if (isset($this->statut)) {
1597 if ($this->statut == $status) {
1598 return 0;
1599 }
1600 } elseif (isset($this->status) && $this->status == $status) {
1601 return 0;
1602 }
1603
1604 $this->db->begin();
1605
1606 // Save in database
1607 $sql = "UPDATE ".$this->db->prefix()."user";
1608 $sql .= " SET statut = ".((int) $status);
1609 $sql .= " WHERE rowid = ".((int) $this->id);
1610 $result = $this->db->query($sql);
1611
1612 dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1613 if ($result) {
1614 if ($status == 0) {
1615 $this->context['actionmsg'] = 'User '.$this->login.' disabled';
1616 } else {
1617 $this->context['actionmsg'] = 'User '.$this->login.' enabled';
1618 }
1619 // Call trigger
1620 $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
1621 if ($result < 0) {
1622 $error++;
1623 }
1624 // End call triggers
1625 }
1626
1627 if ($error) {
1628 $this->db->rollback();
1629 return -$error;
1630 } else {
1631 $this->status = $status;
1632 $this->statut = $status;
1633 $this->db->commit();
1634 return 1;
1635 }
1636 }
1637
1648 public function setCategories($categories)
1649 {
1650 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1651 return parent::setCategoriesCommon($categories, Categorie::TYPE_USER);
1652 }
1653
1660 public function delete(User $user)
1661 {
1662 global $conf, $langs;
1663
1664 $error = 0;
1665
1666 $this->db->begin();
1667
1668 $this->fetch($this->id);
1669
1670 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1671
1672 // Remove rights
1673 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1674
1675 if (!$error && !$this->db->query($sql)) {
1676 $error++;
1677 $this->error = $this->db->lasterror();
1678 }
1679
1680 // Remove group
1681 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1682 if (!$error && !$this->db->query($sql)) {
1683 $error++;
1684 $this->error = $this->db->lasterror();
1685 }
1686
1687 // Remove params
1688 $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1689 if (!$error && !$this->db->query($sql)) {
1690 $error++;
1691 $this->error = $this->db->lasterror();
1692 }
1693
1694 // If contact, remove link
1695 if ($this->contact_id > 0) {
1696 $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1697 if (!$error && !$this->db->query($sql)) {
1698 $error++;
1699 $this->error = $this->db->lasterror();
1700 }
1701 }
1702
1703 // Remove extrafields
1704 if (!$error) {
1705 $result = $this->deleteExtraFields();
1706 if ($result < 0) {
1707 $error++;
1708 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1709 }
1710 }
1711
1712 // Remove user
1713 if (!$error) {
1714 $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1715 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1716 if (!$this->db->query($sql)) {
1717 $error++;
1718 $this->error = $this->db->lasterror();
1719 }
1720 }
1721
1722 if (!$error) {
1723 // Call trigger
1724 $result = $this->call_trigger('USER_DELETE', $user);
1725 if ($result < 0) {
1726 $error++;
1727 $this->db->rollback();
1728 return -1;
1729 }
1730 // End call triggers
1731
1732 $this->db->commit();
1733 return 1;
1734 } else {
1735 $this->db->rollback();
1736 return -1;
1737 }
1738 }
1739
1747 public function create($user, $notrigger = 0)
1748 {
1749 global $conf, $langs;
1750 global $mysoc;
1751
1752 // Clean parameters
1753 $this->setUpperOrLowerCase();
1754
1755 $this->civility_code = trim((string) $this->civility_code);
1756 $this->login = trim((string) $this->login);
1757 if (!isset($this->entity)) {
1758 $this->entity = $conf->entity; // If not defined, we use default value
1759 }
1760 dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1761
1762 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1763
1764 // Check parameters
1765 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
1766 $langs->load("errors");
1767 $this->error = $langs->trans("ErrorBadEMail", $this->email);
1768 return -1;
1769 }
1770 if (empty($this->login)) {
1771 $langs->load("errors");
1772 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1773 return -1;
1774 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1775 $langs->load("errors");
1776 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1777 return -1;
1778 }
1779
1780 $this->datec = dol_now();
1781
1782 $error = 0;
1783 $this->db->begin();
1784
1785 // Check if login already exists in same entity or into entity 0.
1786 if ($this->login) {
1787 $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)."'";
1788 $resqltochecklogin = $this->db->query($sqltochecklogin);
1789 if ($resqltochecklogin) {
1790 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1791 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1792 $langs->load("errors");
1793 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1794 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1795 $this->db->rollback();
1796 return -6;
1797 }
1798 $this->db->free($resqltochecklogin);
1799 }
1800 }
1801 if (!empty($this->email)) {
1802 $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)."'";
1803 $resqltochecklogin = $this->db->query($sqltochecklogin);
1804 if ($resqltochecklogin) {
1805 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1806 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1807 $langs->load("errors");
1808 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1809 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1810 $this->db->rollback();
1811 return -6;
1812 }
1813 $this->db->free($resqltochecklogin);
1814 }
1815 }
1816
1817 // Insert into database
1818 $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, entity)";
1819 $sql .= " VALUES('".$this->db->idate($this->datec)."', '".$this->db->escape($this->login)."', '".$this->db->escape($this->ldap_sid)."', ".((int) $this->entity).")";
1820 $result = $this->db->query($sql);
1821
1822 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1823 if ($result) {
1824 $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1825
1826 // Set default rights
1827 if ($this->set_default_rights() < 0) {
1828 $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1829 $this->db->rollback();
1830 return -5;
1831 }
1832
1833 if (getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && getDolGlobalString('STOCK_USERSTOCK_AUTOCREATE')) {
1834 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1835 $langs->load("stocks");
1836
1837 $entrepot = new Entrepot($this->db);
1838 $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1839 $entrepot->libelle = $entrepot->label; // For backward compatibility
1840 $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1841 $entrepot->statut = 1;
1842 $entrepot->country_id = $mysoc->country_id;
1843
1844 $warehouseid = $entrepot->create($user);
1845
1846 $this->fk_warehouse = $warehouseid;
1847 }
1848
1849 // Update minor fields
1850 $result = $this->update($user, 1, 1);
1851 if ($result < 0) {
1852 $this->db->rollback();
1853 return -4;
1854 }
1855
1856 if (!$notrigger) {
1857 // Call trigger
1858 $result = $this->call_trigger('USER_CREATE', $user);
1859 if ($result < 0) {
1860 $error++;
1861 }
1862 // End call triggers
1863 }
1864
1865 if (!$error) {
1866 $this->db->commit();
1867 return $this->id;
1868 } else {
1869 //$this->error=$interface->error;
1870 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1871 $this->db->rollback();
1872 return -3;
1873 }
1874 } else {
1875 $this->error = $this->db->lasterror();
1876 $this->db->rollback();
1877 return -2;
1878 }
1879 }
1880
1881
1882 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1891 public function create_from_contact($contact, $login = '', $password = '')
1892 {
1893 // phpcs:enable
1894 global $conf, $user, $langs;
1895
1896 $error = 0;
1897
1898 // Define parameters
1899 $this->admin = 0;
1900 $this->civility_code = $contact->civility_code;
1901 $this->lastname = $contact->lastname;
1902 $this->firstname = $contact->firstname;
1903 //$this->gender = $contact->gender; // contact has no gender
1904 $this->email = $contact->email;
1905 $this->socialnetworks = $contact->socialnetworks;
1906 $this->office_phone = $contact->phone_pro;
1907 $this->office_fax = $contact->fax;
1908 $this->user_mobile = $contact->phone_mobile;
1909 $this->address = $contact->address;
1910 $this->zip = $contact->zip;
1911 $this->town = $contact->town;
1912 $this->setUpperOrLowerCase();
1913 $this->state_id = $contact->state_id;
1914 $this->country_id = $contact->country_id;
1915 $this->employee = 0;
1916
1917 if (empty($login)) {
1918 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1919 $login = dol_buildlogin($contact->lastname, $contact->firstname);
1920 }
1921 $this->login = $login;
1922
1923 $this->db->begin();
1924
1925 // Create user and set $this->id. Trigger is disabled because executed later.
1926 $result = $this->create($user, 1);
1927 if ($result > 0) {
1928 $sql = "UPDATE ".$this->db->prefix()."user";
1929 $sql .= " SET fk_socpeople=".((int) $contact->id);
1930 $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
1931 if ($contact->socid > 0) {
1932 $sql .= ", fk_soc=".((int) $contact->socid);
1933 }
1934 $sql .= " WHERE rowid=".((int) $this->id);
1935
1936 $resql = $this->db->query($sql);
1937
1938 dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1939 if ($resql) {
1940 $this->context['createfromcontact'] = 'createfromcontact';
1941
1942 // Call trigger
1943 $result = $this->call_trigger('USER_CREATE', $user);
1944 if ($result < 0) {
1945 $error++;
1946 $this->db->rollback();
1947 return -1;
1948 }
1949 // End call triggers
1950
1951 $this->db->commit();
1952 return $this->id;
1953 } else {
1954 $this->error = $this->db->error();
1955
1956 $this->db->rollback();
1957 return -1;
1958 }
1959 } else {
1960 // $this->error deja positionne
1961 dol_syslog(get_class($this)."::create_from_contact - 0");
1962
1963 $this->db->rollback();
1964 return $result;
1965 }
1966 }
1967
1968 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1977 public function create_from_member($member, $login = '')
1978 {
1979 // phpcs:enable
1980 global $user;
1981
1982 // Set properties on new user
1983 $this->admin = 0;
1984 $this->civility_code = $member->civility_code;
1985 $this->lastname = $member->lastname;
1986 $this->firstname = $member->firstname;
1987 $this->gender = $member->gender;
1988 $this->email = $member->email;
1989 $this->fk_member = $member->id;
1990 $this->address = $member->address;
1991 $this->zip = $member->zip;
1992 $this->town = $member->town;
1993 $this->setUpperOrLowerCase();
1994 $this->state_id = $member->state_id;
1995 $this->country_id = $member->country_id;
1996 $this->socialnetworks = $member->socialnetworks;
1997
1998 $this->pass = $member->pass;
1999 $this->pass_crypted = $member->pass_indatabase_crypted;
2000
2001 if (empty($login)) {
2002 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2003 $login = dol_buildlogin($member->lastname, $member->firstname);
2004 }
2005 $this->login = $login;
2006
2007 $this->db->begin();
2008
2009 // Create and set $this->id
2010 $result = $this->create($user);
2011 if ($result > 0) {
2012 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
2013 $newpass = $this->setPassword($user, $this->pass);
2014 if (is_int($newpass) && $newpass < 0) {
2015 $result = -2;
2016 }
2017 } 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.
2018 $sql = "UPDATE ".$this->db->prefix()."user";
2019 $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
2020 $sql .= " WHERE rowid=".((int) $this->id);
2021
2022 $resql = $this->db->query($sql);
2023 if (!$resql) {
2024 $result = -1;
2025 }
2026 }
2027
2028 if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
2029 $sql = "UPDATE ".$this->db->prefix()."user";
2030 $sql .= " SET fk_soc=".((int) $member->socid);
2031 $sql .= " WHERE rowid=".((int) $this->id);
2032
2033 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
2034 $resql = $this->db->query($sql);
2035 if ($resql) {
2036 $this->db->commit();
2037 return $this->id;
2038 } else {
2039 $this->error = $this->db->lasterror();
2040
2041 $this->db->rollback();
2042 return -1;
2043 }
2044 }
2045 }
2046
2047 if ($result > 0) {
2048 $this->db->commit();
2049 return $this->id;
2050 } else {
2051 // $this->error was already set
2052 $this->db->rollback();
2053 return -2;
2054 }
2055 }
2056
2057 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2063 public function set_default_rights()
2064 {
2065 // phpcs:enable
2066 global $conf;
2067
2068 $rd = array();
2069 $num = 0;
2070 $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
2071 $sql .= " WHERE bydefault = 1";
2072 $sql .= " AND entity = ".((int) $conf->entity);
2073
2074 $resql = $this->db->query($sql);
2075 if ($resql) {
2076 $num = $this->db->num_rows($resql);
2077 $i = 0;
2078 while ($i < $num) {
2079 $row = $this->db->fetch_row($resql);
2080 $rd[$i] = $row[0];
2081 $i++;
2082 }
2083 $this->db->free($resql);
2084 }
2085 $i = 0;
2086 while ($i < $num) {
2087 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
2088 $result = $this->db->query($sql);
2089
2090 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
2091 $result = $this->db->query($sql);
2092 if (!$result) {
2093 return -1;
2094 }
2095 $i++;
2096 }
2097
2098 return $i;
2099 }
2100
2111 public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
2112 {
2113 global $conf, $langs;
2114
2115 if (empty($this->country_id) && !empty($this->country_code)) {
2116 $country_id = getCountry($this->country_code, '3');
2117 $this->country_id = is_int($country_id) ? $country_id : 0;
2118 }
2119
2120 $nbrowsaffected = 0;
2121 $error = 0;
2122
2123 dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
2124
2125 // Clean parameters
2126 $this->civility_code = trim((string) $this->civility_code);
2127 $this->lastname = trim((string) $this->lastname);
2128 $this->firstname = trim((string) $this->firstname);
2129 $this->ref_employee = trim((string) $this->ref_employee);
2130 $this->national_registration_number = trim((string) $this->national_registration_number);
2131 $this->employee = ($this->employee > 0 ? $this->employee : 0);
2132 $this->login = trim((string) $this->login);
2133 $this->gender = trim((string) $this->gender);
2134
2135 $this->pass = trim((string) $this->pass);
2136 $this->api_key = trim((string) $this->api_key);
2137 $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
2138 $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
2139
2140 $this->address = trim((string) $this->address);
2141 $this->zip = trim((string) $this->zip);
2142 $this->town = trim((string) $this->town);
2143
2144 $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
2145 $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
2146 $this->office_phone = trim((string) $this->office_phone);
2147 $this->office_fax = trim((string) $this->office_fax);
2148 $this->user_mobile = trim((string) $this->user_mobile);
2149 $this->personal_mobile = trim((string) $this->personal_mobile);
2150 $this->email = trim((string) $this->email);
2151 $this->personal_email = trim((string) $this->personal_email);
2152
2153 $this->job = trim((string) $this->job);
2154 $this->signature = trim((string) $this->signature);
2155 $this->note_public = trim((string) $this->note_public);
2156 $this->note_private = trim((string) $this->note_private);
2157 $this->openid = trim((string) $this->openid);
2158 $this->admin = ($this->admin > 0 ? $this->admin : 0);
2159
2160 $this->accountancy_code_user_general = trim((string) $this->accountancy_code_user_general);
2161 $this->accountancy_code = trim((string) $this->accountancy_code);
2162 $this->color = trim(str_replace('#', '', (string) $this->color));
2163 $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
2164 $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
2165
2166 $this->birth = empty($this->birth) ? '' : $this->birth;
2167 $this->fk_warehouse = (int) $this->fk_warehouse;
2168 $this->fk_establishment = (int) $this->fk_establishment;
2169
2170 $this->setUpperOrLowerCase();
2171
2172 // Check parameters
2173 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
2174
2175 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
2176 $langs->load("errors");
2177 $this->error = $langs->trans("ErrorBadEMail", $this->email);
2178 return -1;
2179 }
2180 if (empty($this->login)) {
2181 $langs->load("errors");
2182 $this->error = $langs->trans("ErrorFieldRequired", 'Login');
2183 return -1;
2184 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
2185 $langs->load("errors");
2186 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
2187 return -1;
2188 }
2189
2190 $this->db->begin();
2191
2192 // Check if login already exists in same entity or into entity 0.
2193 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->oldcopy->login != $this->login) {
2194 $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)."'";
2195 $resqltochecklogin = $this->db->query($sqltochecklogin);
2196 if ($resqltochecklogin) {
2197 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2198 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2199 $langs->load("errors");
2200 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
2201 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2202 $this->db->rollback();
2203 return -1;
2204 }
2205 }
2206 }
2207 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && !empty($this->email) && $this->oldcopy->email != $this->email) {
2208 $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)."'";
2209 $resqltochecklogin = $this->db->query($sqltochecklogin);
2210 if ($resqltochecklogin) {
2211 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2212 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2213 $langs->load("errors");
2214 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
2215 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2216 $this->db->rollback();
2217 return -1;
2218 }
2219 }
2220 }
2221
2222 // Update data
2223 $sql = "UPDATE ".$this->db->prefix()."user SET";
2224 $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
2225 $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
2226 $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
2227 $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
2228 $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
2229 $sql .= ", employee = ".(int) $this->employee;
2230 $sql .= ", login = '".$this->db->escape($this->login)."'";
2231 $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
2232 $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' or 'other'
2233 $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
2234 if (!empty($user->admin)) {
2235 $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
2236 }
2237 $sql .= ", address = '".$this->db->escape($this->address)."'";
2238 $sql .= ", zip = '".$this->db->escape($this->zip)."'";
2239 $sql .= ", town = '".$this->db->escape($this->town)."'";
2240 $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".((int) $this->state_id)."'" : "null");
2241 $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".((int) $this->country_id)."'" : "null");
2242 $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
2243 $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
2244 $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
2245 $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
2246 $sql .= ", email = '".$this->db->escape($this->email)."'";
2247 $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
2248 $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
2249 $sql .= ", job = '".$this->db->escape($this->job)."'";
2250 $sql .= ", signature = '".$this->db->escape($this->signature)."'";
2251 $sql .= ", accountancy_code_user_general = '".$this->db->escape($this->accountancy_code_user_general)."'";
2252 $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
2253 $sql .= ", color = '".$this->db->escape($this->color)."'";
2254 $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
2255 $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
2256 $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2257 $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2258 $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2259 $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2260 $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2261 $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2262 $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".((int) $this->fk_user)."'" : "null");
2263 $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".((int) $this->fk_user_expense_validator)."'" : "null");
2264 $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".((int) $this->fk_user_holiday_validator)."'" : "null");
2265 if (isset($this->thm) || $this->thm != '') {
2266 $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2267 }
2268 if (isset($this->tjm) || $this->tjm != '') {
2269 $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2270 }
2271 if (isset($this->salary) || $this->salary != '') {
2272 $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2273 }
2274 if (isset($this->salaryextra) || $this->salaryextra != '') {
2275 $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2276 }
2277 $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2278 if (!empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2279 $sql .= ", entity = ".((int) $this->entity); // entity flag can be set/unset only by an another superadmin user
2280 }
2281 $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
2282 $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
2283 $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
2284 $sql .= ", fk_establishment = ".($this->fk_establishment > 0 ? $this->fk_establishment : "null");
2285 $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2286 $sql .= " WHERE rowid = ".((int) $this->id);
2287
2288 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2289 $resql = $this->db->query($sql);
2290 if ($resql) {
2291 $nbrowsaffected += $this->db->affected_rows($resql);
2292
2293 // Update password
2294 if (!empty($this->pass)) {
2295 if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2296 // If a new value for password is set and different than the one encrypted into database
2297 $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2298 if (is_int($result) && $result < 0) {
2299 return -5;
2300 }
2301 }
2302 }
2303
2304 // If user is linked to a member, remove old link to this member
2305 if ($this->fk_member > 0) {
2306 dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2307 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2308 $resql = $this->db->query($sql);
2309 if (!$resql) {
2310 $this->error = $this->db->error();
2311 $this->db->rollback();
2312 return -5;
2313 }
2314 }
2315 // Set link to user
2316 dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2317 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2318 $resql = $this->db->query($sql);
2319 if (!$resql) {
2320 $this->error = $this->db->error();
2321 $this->db->rollback();
2322 return -5;
2323 }
2324
2325 if ($nbrowsaffected) { // If something has changed in data
2326 if ($this->fk_member > 0 && !$nosyncmember) {
2327 dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2328
2329 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2330
2331 // This user is linked with a member, so we also update member information
2332 // if this is an update.
2333 $adh = new Adherent($this->db);
2334 $result = $adh->fetch($this->fk_member);
2335
2336 if ($result > 0) {
2337 $adh->civility_code = $this->civility_code;
2338 $adh->firstname = $this->firstname;
2339 $adh->lastname = $this->lastname;
2340 $adh->login = $this->login;
2341 $adh->gender = $this->gender;
2342 $adh->birth = $this->birth;
2343
2344 $adh->pass = $this->pass;
2345
2346 $adh->address = $this->address;
2347 $adh->town = $this->town;
2348 $adh->zip = $this->zip;
2349 $adh->state_id = $this->state_id;
2350 $adh->country_id = $this->country_id;
2351
2352 $adh->email = $this->email;
2353
2354 $adh->socialnetworks = $this->socialnetworks;
2355
2356 $adh->phone = $this->office_phone;
2357 $adh->phone_mobile = $this->user_mobile;
2358
2359 $adh->default_lang = $this->lang;
2360
2361 $adh->user_id = $this->id;
2362 $adh->user_login = $this->login;
2363
2364 $result = $adh->update($user, 0, 1, 0);
2365 if ($result < 0) {
2366 $this->error = $adh->error;
2367 $this->errors = $adh->errors;
2368 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2369 $error++;
2370 }
2371 } elseif ($result < 0) {
2372 $this->error = $adh->error;
2373 $this->errors = $adh->errors;
2374 $error++;
2375 }
2376 }
2377
2378 if ($this->contact_id > 0 && !$nosynccontact) {
2379 dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2380
2381 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2382
2383 // This user is linked with a contact, so we also update contact information if this is an update.
2384 $tmpobj = new Contact($this->db);
2385 $result = $tmpobj->fetch($this->contact_id);
2386
2387 if ($result >= 0) {
2388 $tmpobj->civility_code = $this->civility_code;
2389 $tmpobj->firstname = $this->firstname;
2390 $tmpobj->lastname = $this->lastname;
2391 $tmpobj->login = $this->login;
2392 $tmpobj->gender = $this->gender;
2393 $tmpobj->birth = $this->birth;
2394
2395 //$tmpobj->pass=$this->pass;
2396
2397 $tmpobj->email = $this->email;
2398
2399 $tmpobj->socialnetworks = $this->socialnetworks;
2400
2401 $tmpobj->phone_pro = $this->office_phone;
2402 $tmpobj->phone_mobile = $this->user_mobile;
2403 $tmpobj->fax = $this->office_fax;
2404
2405 $tmpobj->default_lang = $this->lang;
2406
2407 $tmpobj->address = $this->address;
2408 $tmpobj->town = $this->town;
2409 $tmpobj->zip = $this->zip;
2410 $tmpobj->state_id = $this->state_id;
2411 $tmpobj->country_id = $this->country_id;
2412
2413 $tmpobj->user_id = $this->id;
2414 $tmpobj->user_login = $this->login;
2415
2416 $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2417 if ($result < 0) {
2418 $this->error = $tmpobj->error;
2419 $this->errors = $tmpobj->errors;
2420 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2421 $error++;
2422 }
2423 } else {
2424 $this->error = $tmpobj->error;
2425 $this->errors = $tmpobj->errors;
2426 $error++;
2427 }
2428 }
2429 }
2430
2431 $action = 'update';
2432
2433 // Actions on extra fields
2434 if (!$error) {
2435 $result = $this->insertExtraFields();
2436 if ($result < 0) {
2437 $error++;
2438 }
2439 }
2440
2441 if (!$error && !$notrigger) {
2442 // Call trigger
2443 $result = $this->call_trigger('USER_MODIFY', $user);
2444 if ($result < 0) {
2445 $error++;
2446 }
2447 // End call triggers
2448 }
2449
2450 if (!$error) {
2451 $this->db->commit();
2452 return $nbrowsaffected;
2453 } else {
2454 dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2455 $this->db->rollback();
2456 return -1;
2457 }
2458 } else {
2459 $this->error = $this->db->lasterror();
2460 $this->db->rollback();
2461 return -2;
2462 }
2463 }
2464
2465 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2472 public function update_last_login_date()
2473 {
2474 // phpcs:enable
2475 $now = dol_now();
2476
2477 $userremoteip = getUserRemoteIP();
2478
2479 $sql = "UPDATE ".$this->db->prefix()."user SET";
2480 $sql .= " datepreviouslogin = datelastlogin,";
2481 $sql .= " ippreviouslogin = iplastlogin,";
2482 $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2483 $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2484 $sql .= " tms = tms"; // The last update date must change because the last login date is updated
2485 $sql .= " WHERE rowid = ".((int) $this->id);
2486
2487 dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2488 $resql = $this->db->query($sql);
2489 if ($resql) {
2490 $this->datepreviouslogin = $this->datelastlogin;
2491 $this->datelastlogin = $now;
2492 $this->ippreviouslogin = $this->iplastlogin;
2493 $this->iplastlogin = $userremoteip;
2494 return 1;
2495 } else {
2496 $this->error = $this->db->lasterror().' sql='.$sql;
2497 return -1;
2498 }
2499 }
2500
2501
2514 public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2515 {
2516 global $conf, $langs;
2517 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2518
2519 $error = 0;
2520
2521 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2522
2523 // If new password not provided, we generate one
2524 if (!$password) {
2525 $password = getRandomPassword(false);
2526 }
2527
2528 $password_crypted = null;
2529 // Check and encrypt the password
2530 if (empty($passwordalreadycrypted)) {
2531 if (getDolGlobalString('USER_PASSWORD_GENERATED')) {
2532 // Add a check on rules for password syntax using the setup of the password generator
2533 $modGeneratePassClass = 'modGeneratePass'.ucfirst($conf->global->USER_PASSWORD_GENERATED);
2534
2535 include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2536 if (class_exists($modGeneratePassClass)) {
2537 $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2538 '@phan-var-force ModeleGenPassword $modGeneratePass';
2539
2540 // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2541 $modGeneratePass->WithoutAmbi = 0;
2542
2543 // Call to validatePassword($password) to check pass match rules
2544 $testpassword = $modGeneratePass->validatePassword($password);
2545 if (!$testpassword) {
2546 $this->error = $modGeneratePass->error;
2547 return -1;
2548 }
2549 }
2550 }
2551
2552
2553 // Now, we encrypt the new password
2554 $password_crypted = dol_hash($password);
2555 }
2556
2557 // Update password
2558 if (!$changelater) {
2559 if (!is_object($this->oldcopy)) {
2560 $this->oldcopy = clone $this;
2561 }
2562
2563 $now = dol_now();
2564
2565 $this->db->begin();
2566
2567 $sql = "UPDATE ".$this->db->prefix()."user";
2568 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2569 $sql .= " datelastpassvalidation = '".$this->db->idate(dol_now())."',";
2570 $sql .= " pass_temp = null";
2571 if (!empty($flagdelsessionsbefore)) {
2572 $sql .= ", flagdelsessionsbefore = '".$this->db->idate($now - 5, 'gmt')."'";
2573 }
2574 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
2575 $sql .= ", pass = null";
2576 } else {
2577 $sql .= ", pass = '".$this->db->escape($password)."'";
2578 }
2579 $sql .= " WHERE rowid = ".((int) $this->id);
2580
2581 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2582
2583 $result = $this->db->query($sql);
2584 if ($result) {
2585 if ($this->db->affected_rows($result)) {
2586 $this->pass = $password;
2587 $this->pass_indatabase = $password;
2588 $this->pass_indatabase_crypted = (string) $password_crypted;
2589
2590 if ($this->fk_member && !$nosyncmember) {
2591 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2592
2593 // This user is linked with a member, so we also update members information
2594 // if this is an update.
2595 $adh = new Adherent($this->db);
2596 $result = $adh->fetch($this->fk_member);
2597
2598 if ($result >= 0) {
2599 $result = $adh->setPassword($user, $this->pass, (!getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 0 : 1), 1); // The encryption is not managed in the 'adherent' module
2600 if (is_int($result) && $result < 0) {
2601 $this->error = $adh->error;
2602 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2603 $error++;
2604 }
2605 } else {
2606 $this->error = $adh->error;
2607 $error++;
2608 }
2609 }
2610
2611 dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2612
2613 // Call trigger for the "security events" log
2614 $user->context['audit'] = 'login='.$user->login;
2615 if (!empty($flagdelsessionsbefore)) {
2616 $user->context['audit'] .= " - flagdelsessionsbefore set to '".$this->db->idate($now - 5, 'gmt')."'";
2617 }
2618
2619 if (!$error && !$notrigger) {
2620 // Call trigger
2621 $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2622 if ($result < 0) {
2623 $error++;
2624 $this->db->rollback();
2625 return -1;
2626 }
2627 // End call triggers
2628 }
2629
2630 $this->db->commit();
2631 return $this->pass;
2632 } else {
2633 $this->db->rollback();
2634 return 0;
2635 }
2636 } else {
2637 $this->db->rollback();
2638 dol_print_error($this->db);
2639 return -1;
2640 }
2641 } else {
2642 // We store password in password temporary field.
2643 // After receiving confirmation link, we will erase and store it in pass_crypted
2644 $sql = "UPDATE ".$this->db->prefix()."user";
2645 $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2646 $sql .= " WHERE rowid = ".((int) $this->id);
2647
2648 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2649 $result = $this->db->query($sql);
2650 if ($result) {
2651 return $password;
2652 } else {
2653 dol_print_error($this->db);
2654 return -3;
2655 }
2656 }
2657 }
2658
2659 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2668 public function send_password($user, $password = '', $changelater = 0)
2669 {
2670 // phpcs:enable
2671 global $conf, $langs;
2673
2674 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2675
2676 $msgishtml = 0;
2677
2678 // Define $msg
2679 $mesg = '';
2680
2681 $outputlangs = new Translate("", $conf);
2682
2683 if (getDolGlobalString('MAIN_LANG_DEFAULT')) {
2684 $outputlangs->setDefaultLang(getDolGlobalString('MAIN_LANG_DEFAULT'));
2685 } else { // If user has not defined its own language, we used current language
2686 $outputlangs = $langs;
2687 }
2688
2689 // Load translation files required by the page
2690 $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2691
2692 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', constant('DOL_APPLICATION_TITLE'));
2693
2694 $subject = '['.$appli.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2695
2696 // Define $urlwithroot
2697 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2698 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2699
2700 if (!$changelater) {
2701 $url = $urlwithroot.'/';
2702 if (getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD')) {
2703 $url = getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD');
2704 }
2705
2706 dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2707
2708 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2709 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2710 $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2711 $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2712 $mesg .= "\n";
2713
2714 $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2715 $mesg .= "--\n";
2716 $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2717 } else {
2718 //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2719 $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2720 $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2721 if (isModEnabled('multicompany')) {
2722 $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2723 }
2724
2725 dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2726
2727 $msgishtml = 1;
2728
2729 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2730 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2731 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2732 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2733 $mesg .= "<br>\n";
2734 $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2735 $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2736 $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2737 }
2738
2739 $trackid = 'use'.$this->id;
2740 $sendcontext = 'passwordreset';
2741
2742 $mailfile = new CMailFile(
2743 $subject,
2744 $this->email,
2745 getDolGlobalString("MAIN_MAIL_EMAIL_FROM_PASSWORDRESET", getDolGlobalString("MAIN_MAIL_EMAIL_FROM")),
2746 $mesg,
2747 array(),
2748 array(),
2749 array(),
2750 '',
2751 '',
2752 0,
2753 $msgishtml,
2754 '',
2755 '',
2756 $trackid,
2757 '',
2758 $sendcontext
2759 );
2760
2761 if ($mailfile->sendfile()) {
2762 return 1;
2763 } else {
2764 $langs->trans("errors");
2765 $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2766 return -1;
2767 }
2768 }
2769
2775 public function error()
2776 {
2777 return $this->error;
2778 }
2779
2780
2781 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2787 public function fetch_clicktodial()
2788 {
2789 // phpcs:enable
2790 $sql = "SELECT url, login, pass, poste ";
2791 $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2792 $sql .= " WHERE u.fk_user = ".((int) $this->id);
2793
2794 $resql = $this->db->query($sql);
2795 if ($resql) {
2796 if ($this->db->num_rows($resql)) {
2797 $obj = $this->db->fetch_object($resql);
2798
2799 $this->clicktodial_url = $obj->url;
2800 $this->clicktodial_login = $obj->login;
2801 $this->clicktodial_password = $obj->pass;
2802 $this->clicktodial_poste = $obj->poste;
2803 }
2804
2805 $this->clicktodial_loaded = 1; // Data loaded (found or not)
2806
2807 $this->db->free($resql);
2808 return 1;
2809 } else {
2810 $this->error = $this->db->error();
2811 return -1;
2812 }
2813 }
2814
2815 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2821 public function update_clicktodial()
2822 {
2823 // phpcs:enable
2824 $this->db->begin();
2825
2826 $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2827 $sql .= " WHERE fk_user = ".((int) $this->id);
2828
2829 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2830
2831 $result = $this->db->query($sql);
2832
2833 $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
2834 $sql .= " (fk_user,url,login,pass,poste)";
2835 $sql .= " VALUES (".$this->id;
2836 $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2837 $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2838 $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2839 $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2840
2841 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2842
2843 $result = $this->db->query($sql);
2844 if ($result) {
2845 $this->db->commit();
2846 return 1;
2847 } else {
2848 $this->db->rollback();
2849 $this->error = $this->db->lasterror();
2850 return -1;
2851 }
2852 }
2853
2854
2855 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2864 public function SetInGroup($group, $entity, $notrigger = 0)
2865 {
2866 // phpcs:enable
2867 global $conf, $langs, $user;
2868
2869 $error = 0;
2870
2871 $this->db->begin();
2872
2873 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2874 $sql .= " WHERE fk_user = ".((int) $this->id);
2875 $sql .= " AND fk_usergroup = ".((int) $group);
2876 $sql .= " AND entity = ".((int) $entity);
2877
2878 $result = $this->db->query($sql);
2879
2880 $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
2881 $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
2882
2883 $result = $this->db->query($sql);
2884 if ($result) {
2885 if (!$error && !$notrigger) {
2886 $this->context = array('audit' => $langs->trans("UserSetInGroup"), 'newgroupid' => $group);
2887
2888 // Call trigger
2889 $result = $this->call_trigger('USER_MODIFY', $user);
2890 if ($result < 0) {
2891 $error++;
2892 }
2893 // End call triggers
2894 }
2895
2896 if (!$error) {
2897 $this->db->commit();
2898 return 1;
2899 } else {
2900 dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2901 $this->db->rollback();
2902 return -2;
2903 }
2904 } else {
2905 $this->error = $this->db->lasterror();
2906 $this->db->rollback();
2907 return -1;
2908 }
2909 }
2910
2911 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2920 public function RemoveFromGroup($group, $entity, $notrigger = 0)
2921 {
2922 // phpcs:enable
2923 global $conf, $langs, $user;
2924
2925 $error = 0;
2926
2927 $this->db->begin();
2928
2929 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2930 $sql .= " WHERE fk_user = ".((int) $this->id);
2931 $sql .= " AND fk_usergroup = ".((int) $group);
2932 if (empty($entity)) {
2933 $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
2934 } else {
2935 $sql .= " AND entity = ".((int) $entity);
2936 }
2937
2938 $result = $this->db->query($sql);
2939 if ($result) {
2940 if (!$error && !$notrigger) {
2941 $this->context = array('audit' => $langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
2942
2943 // Call trigger
2944 $result = $this->call_trigger('USER_MODIFY', $user);
2945 if ($result < 0) {
2946 $error++;
2947 }
2948 // End call triggers
2949 }
2950
2951 if (!$error) {
2952 $this->db->commit();
2953 return 1;
2954 } else {
2955 dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2956 $this->db->rollback();
2957 return -2;
2958 }
2959 } else {
2960 $this->error = $this->db->lasterror();
2961 $this->db->rollback();
2962 return -1;
2963 }
2964 }
2965
2966
2974 {
2975 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2976
2977 $now = dol_now();
2978
2979 //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
2980
2981 // Check date start validity
2982 if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
2983 return 1;
2984 }
2985 // Check date end validity
2986 if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
2987 return 1;
2988 }
2989
2990 return 0;
2991 }
2992
2993
3005 public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
3006 {
3007 $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3008 $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
3009 $result .= '</a>';
3010
3011 return $result;
3012 }
3013
3020 public function getTooltipContentArray($params)
3021 {
3022 global $conf, $langs, $menumanager;
3023 global $dolibarr_main_demo;
3024
3025 $infologin = $params['infologin'] ?? 0;
3026 $option = $params['option'] ?? '';
3027
3028 $data = [];
3029 if (!empty($this->photo)) {
3030 $photo = '<div class="photointooltip floatright">';
3031 $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
3032 $photo .= '</div>';
3033 $data['photo'] = $photo;
3034 //$label .= '<div style="clear: both;"></div>';
3035 }
3036
3037 // Info Login
3038 $data['opendiv'] = '<div class="centpercent divtooltip">';
3039 $data['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
3040 $data['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs));
3041 if (!empty($this->login)) {
3042 $data['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
3043 }
3044 if (!empty($this->job)) {
3045 $data['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
3046 }
3047 $data['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
3048 if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
3049 $phonelist = array();
3050 if ($this->office_phone) {
3051 $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3052 }
3053 if ($this->office_fax) {
3054 $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3055 }
3056 if ($this->user_mobile) {
3057 $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3058 }
3059 $data['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
3060 }
3061 if (!empty($this->admin)) {
3062 $data['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
3063 }
3064 if (!empty($this->accountancy_code) || $option == 'accountancy') {
3065 $langs->load("companies");
3066 $data['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
3067 }
3068 $company = '';
3069 if (!empty($this->socid)) { // Add thirdparty for external users
3070 $thirdpartystatic = new Societe($this->db);
3071 $thirdpartystatic->fetch($this->socid);
3072 $companyimg = '';
3073 if (empty($params['hidethirdpartylogo'])) {
3074 $companyimg = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3075 }
3076 $company = ' ('.$langs->trans("Company").': '.($companyimg ? $companyimg : img_picto('', 'company')).' '.dol_string_nohtmltag($thirdpartystatic->name).')';
3077 }
3078 $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
3079 $data['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
3080 $data['closediv'] = '</div>';
3081
3082 if ($infologin > 0) {
3083 $data['newlinelogin'] = '<br>';
3084 $data['session'] = '<br><u>'.$langs->trans("Session").'</u>';
3085 $data['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
3086 if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
3087 $data['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
3088 }
3089 $data['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
3090 $data['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
3091 $data['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
3092 $data['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
3093 // @phan-suppress-next-line PhanRedefinedClassReference
3094 $data['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
3095 $s = picto_from_langcode($langs->getDefaultLang());
3096 $data['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
3097 $data['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
3098 $data['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
3099 $data['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
3100 if ($conf->browser->layout == 'phone') {
3101 $data['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
3102 }
3103 if (!empty($_SESSION["disablemodules"])) {
3104 $data['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(implode(', ', explode(',', $_SESSION["disablemodules"])));
3105 }
3106 }
3107
3108 return $data;
3109 }
3110
3126 public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = 'valignmiddle', $save_lastsearch_value = -1)
3127 {
3128 global $langs, $hookmanager, $user;
3129
3130 if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
3131 $option = 'nolink';
3132 }
3133
3134 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
3135 $withpictoimg = 0;
3136 }
3137
3138 $result = '';
3139 $params = [
3140 'id' => $this->id,
3141 'objecttype' => $this->element,
3142 'infologin' => $infologin,
3143 'option' => $option,
3144 'hidethirdpartylogo' => $hidethirdpartylogo,
3145 ];
3146 $classfortooltip = 'classfortooltip';
3147 $dataparams = '';
3148 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3149 $classfortooltip = 'classforajaxtooltip';
3150 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3151 $label = '';
3152 } else {
3153 $label = implode($this->getTooltipContentArray($params));
3154 }
3155
3156 $companylink = '';
3157 if (!empty($this->socid)) { // Add thirdparty for external users
3158 $thirdpartystatic = new Societe($this->db);
3159 $thirdpartystatic->fetch($this->socid);
3160 if (empty($hidethirdpartylogo)) {
3161 $companylink = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3162 }
3163 }
3164
3165 if ($infologin < 0) {
3166 $label = '';
3167 }
3168
3169 $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id;
3170 if ($option == 'leave') {
3171 $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id;
3172 }
3173
3174 if ($option != 'nolink') {
3175 // Add param to save lastsearch_values or not
3176 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3177 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3178 $add_save_lastsearch_values = 1;
3179 }
3180 if ($add_save_lastsearch_values) {
3181 $url .= '&save_lastsearch_values=1';
3182 }
3183 }
3184
3185 $linkstart = '<a href="'.$url.'"';
3186 $linkclose = "";
3187 if (empty($notooltip)) {
3188 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3189 $langs->load("users");
3190 $label = $langs->trans("ShowUser");
3191 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3192 }
3193 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3194 $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
3195 } else {
3196 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
3197 }
3198
3199 $linkstart .= $linkclose.'>';
3200 $linkend = '</a>';
3201
3202 //if ($withpictoimg == -1) $result.='<div class="nowrap">';
3203 $result .= (($option == 'nolink') ? '' : $linkstart);
3204 if ($withpictoimg) {
3205 $paddafterimage = '';
3206 if (abs((int) $withpictoimg) == 1) {
3207 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3208 }
3209 // Only picto
3210 if ($withpictoimg > 0) {
3211 $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>';
3212 } else {
3213 // Picto must be a photo
3214 $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>';
3215 }
3216 $result .= $picto;
3217 }
3218 if ($withpictoimg > -2 && $withpictoimg != 2) {
3219 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3220 $result .= '<span class="nopadding usertext'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
3221 }
3222 if ($mode == 'login') {
3223 $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
3224 } else {
3225 $result .= dol_string_nohtmltag($this->getFullName($langs, 0, ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
3226 }
3227 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3228 $result .= '</span>';
3229 }
3230 }
3231 $result .= (($option == 'nolink') ? '' : $linkend);
3232 //if ($withpictoimg == -1) $result.='</div>';
3233
3234 $result .= $companylink;
3235
3236 global $action;
3237 $hookmanager->initHooks(array('userdao'));
3238 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
3239 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3240 if ($reshook > 0) {
3241 $result = $hookmanager->resPrint;
3242 } else {
3243 $result .= $hookmanager->resPrint;
3244 }
3245
3246 return $result;
3247 }
3248
3258 public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
3259 {
3260 global $langs, $user;
3261
3262 $result = '';
3263
3264 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3265 $linkend = '</a>';
3266
3267 //Check user's rights to see an other user
3268 if ((!$user->hasRight('user', 'user', 'lire') && $this->id != $user->id)) {
3269 $option = 'nolink';
3270 }
3271
3272 if ($option == 'xxx') {
3273 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3274 $linkend = '</a>';
3275 }
3276
3277 if ($option == 'nolink') {
3278 $linkstart = '';
3279 $linkend = '';
3280 }
3281
3282 $result .= $linkstart;
3283 if ($withpictoimg) {
3284 $paddafterimage = '';
3285 if (abs($withpictoimg) == 1) {
3286 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3287 }
3288 // Only picto
3289 if ($withpictoimg > 0) {
3290 $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3291 } else {
3292 // Picto must be a photo
3293 $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>';
3294 }
3295 $result .= $picto;
3296 }
3297 $result .= $this->login;
3298 $result .= $linkend;
3299
3300 return $result;
3301 }
3302
3309 public function getLibStatut($mode = 0)
3310 {
3311 return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3312 }
3313
3314 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3322 public function LibStatut($status, $mode = 0)
3323 {
3324 // phpcs:enable
3325 global $langs;
3326
3327 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3328 global $langs;
3329 //$langs->load("mymodule");
3330 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3331 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3332 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3333 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3334 }
3335
3336 $statusType = 'status5';
3337 if ($status == self::STATUS_ENABLED) {
3338 $statusType = 'status4';
3339 }
3340
3341 $label = $this->labelStatus[$status];
3342 $labelshort = $this->labelStatusShort[$status];
3343
3344 $now = dol_now();
3345 if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3346 $statusType = 'status3';
3347 $label .= ' ('.$langs->trans("UserNotYetValid").')';
3348 }
3349 if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3350 $statusType = 'status2';
3351 $label .= ' ('.$langs->trans("UserExpired").')';
3352 }
3353
3354 return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3355 }
3356
3357
3365 public function getKanbanView($option = '', $arraydata = null)
3366 {
3367 global $langs;
3368
3369 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3370
3371 $return = '<div class="box-flex-item box-flex-grow-zero">';
3372 $return .= '<div class="info-box info-box-sm">';
3373 $return .= '<span class="info-box-icon bg-infobox-action">';
3374
3375 $label = '';
3376 if (!empty($this->photo)) {
3377 //$label .= '<div class="photointooltip floatright">';
3378 $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
3379 //$label .= '</div>';
3380 //$label .= '<div style="clear: both;"></div>';
3381 $return .= $label;
3382 } else {
3383 $return .= img_picto('', $this->picto);
3384 }
3385
3386 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3387 $return .= '</span>';
3388 $return .= '<div class="info-box-content">';
3389 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3390 if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3391 $return .= img_picto($langs->trans("SuperAdministratorDesc"), 'redstar', 'class="valignmiddle paddingright paddingleft"');
3392 } elseif ($this->admin) {
3393 $return .= img_picto($langs->trans("AdministratorDesc"), 'star', 'class="valignmiddle paddingright paddingleft"');
3394 }
3395 $return .= '</span>';
3396 if ($selected >= 0) {
3397 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3398 }
3399 if (property_exists($this, 'label')) {
3400 $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3401 }
3402 if ($this->email) {
3403 $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3404 }
3405 if (method_exists($this, 'getLibStatut')) {
3406 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3407 }
3408 $return .= '</div>';
3409 $return .= '</div>';
3410 $return .= '</div>';
3411
3412 return $return;
3413 }
3414
3415
3416 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3417 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3427 public function _load_ldap_dn($info, $mode = 0)
3428 {
3429 // phpcs:enable
3430 global $conf;
3431 $dn = '';
3432 if ($mode == 0) {
3433 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')]."," . getDolGlobalString('LDAP_USER_DN');
3434 } elseif ($mode == 1) {
3435 $dn = getDolGlobalString('LDAP_USER_DN');
3436 } elseif ($mode == 2) {
3437 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')];
3438 }
3439 return $dn;
3440 }
3441
3442 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3443 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3449 public function _load_ldap_info()
3450 {
3451 // phpcs:enable
3452 global $conf, $langs;
3453
3454 $info = array();
3455
3456 $socialnetworks = getArrayOfSocialNetworks();
3457
3458 $keymodified = false;
3459
3460 // Object classes
3461 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_USER_OBJECT_CLASS'));
3462
3463 $this->fullname = $this->getFullName($langs);
3464
3465 // Possible LDAP KEY (constname => varname)
3466 $ldapkey = array(
3467 'LDAP_FIELD_FULLNAME' => 'fullname',
3468 'LDAP_FIELD_NAME' => 'lastname',
3469 'LDAP_FIELD_FIRSTNAME' => 'firstname',
3470 'LDAP_FIELD_LOGIN' => 'login',
3471 'LDAP_FIELD_LOGIN_SAMBA' => 'login',
3472 'LDAP_FIELD_PHONE' => 'office_phone',
3473 'LDAP_FIELD_MOBILE' => 'user_mobile',
3474 'LDAP_FIELD_FAX' => 'office_fax',
3475 'LDAP_FIELD_MAIL' => 'email',
3476 'LDAP_FIELD_SID' => 'ldap_sid',
3477 );
3478
3479 // Champs
3480 foreach ($ldapkey as $constname => $varname) {
3481 if (!empty($this->$varname) && getDolGlobalString($constname)) {
3482 $info[getDolGlobalString($constname)] = $this->$varname;
3483
3484 // Check if it is the LDAP key and if its value has been changed
3485 if (getDolGlobalString('LDAP_KEY_USERS') && $conf->global->LDAP_KEY_USERS == getDolGlobalString($constname)) {
3486 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->$varname != $this->oldcopy->$varname) {
3487 $keymodified = true; // For check if LDAP key has been modified
3488 }
3489 }
3490 }
3491 }
3492 foreach ($socialnetworks as $key => $value) {
3493 if (!empty($this->socialnetworks[$value['label']]) && getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))) {
3494 $info[getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3495 }
3496 }
3497 if ($this->address && getDolGlobalString('LDAP_FIELD_ADDRESS')) {
3498 $info[getDolGlobalString('LDAP_FIELD_ADDRESS')] = $this->address;
3499 }
3500 if ($this->zip && getDolGlobalString('LDAP_FIELD_ZIP')) {
3501 $info[getDolGlobalString('LDAP_FIELD_ZIP')] = $this->zip;
3502 }
3503 if ($this->town && getDolGlobalString('LDAP_FIELD_TOWN')) {
3504 $info[getDolGlobalString('LDAP_FIELD_TOWN')] = $this->town;
3505 }
3506 if ($this->note_public && getDolGlobalString('LDAP_FIELD_DESCRIPTION')) {
3507 $info[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_public, 2);
3508 }
3509 if ($this->socid > 0 && getDolGlobalString('LDAP_FIELD_COMPANY')) {
3510 $soc = new Societe($this->db);
3511 $soc->fetch($this->socid);
3512
3513 $info[getDolGlobalString('LDAP_FIELD_COMPANY')] = $soc->name;
3514 if ($soc->client == 1) {
3515 $info["businessCategory"] = "Customers";
3516 }
3517 if ($soc->client == 2) {
3518 $info["businessCategory"] = "Prospects";
3519 }
3520 if ($soc->fournisseur == 1) {
3521 $info["businessCategory"] = "Suppliers";
3522 }
3523 }
3524
3525 // When password is modified
3526 if (!empty($this->pass)) {
3527 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3528 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass; // this->pass = unencrypted password
3529 }
3530 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3531 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3532 }
3533 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3534 // Set LDAP password if possible
3535 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3536 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
3537 // Just for the default MD5 !
3538 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) {
3539 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3540 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3541 }
3542 }
3543 } elseif (!empty($this->pass_indatabase)) {
3544 // Use $this->pass_indatabase value if exists
3545 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3546 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = unencrypted password
3547 }
3548 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3549 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3550 }
3551 }
3552 }
3553
3554 if (getDolGlobalString('LDAP_SERVER_TYPE') == 'egroupware') {
3555 $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3556
3557 $info['uidnumber'] = $this->id;
3558
3559 $info['phpgwTz'] = 0;
3560 $info['phpgwMailType'] = 'INTERNET';
3561 $info['phpgwMailHomeType'] = 'INTERNET';
3562
3563 $info["phpgwContactTypeId"] = 'n';
3564 $info["phpgwContactCatId"] = 0;
3565 $info["phpgwContactAccess"] = "public";
3566
3567 /*
3568 if (dol_strlen($this->egroupware_id) == 0) {
3569 $this->egroupware_id = 1;
3570 }
3571 $info["phpgwContactOwner"] = $this->egroupware_id;
3572 */
3573 $info["phpgwContactOwner"] = 1;
3574
3575 if ($this->email) {
3576 $info["rfc822Mailbox"] = $this->email;
3577 }
3578 if ($this->user_mobile) {
3579 $info["phpgwCellTelephoneNumber"] = $this->user_mobile;
3580 }
3581 }
3582
3583 if (getDolGlobalString('LDAP_FIELD_USERID')) {
3584 $info[getDolGlobalString('LDAP_FIELD_USERID')] = $this->id;
3585 }
3586 if (getDolGlobalString('LDAP_FIELD_GROUPID')) {
3587 $usergroup = new UserGroup($this->db);
3588 $groupslist = $usergroup->listGroupsForUser($this->id);
3589 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = '65534';
3590 if (!empty($groupslist)) {
3591 foreach ($groupslist as $groupforuser) {
3592 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = $groupforuser->id; //Select first group in list
3593 break;
3594 }
3595 }
3596 }
3597 if (getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY') && getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')) {
3598 $info[getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY')] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->login";
3599 }
3600
3601 return $info;
3602 }
3603
3604
3612 public function initAsSpecimen()
3613 {
3614 global $user, $langs;
3615
3616 $now = dol_now();
3617
3618 // Initialise parameters
3619 $this->id = 0;
3620 $this->ref = 'SPECIMEN';
3621 $this->specimen = 1;
3622
3623 $this->lastname = 'DOLIBARR';
3624 $this->firstname = 'SPECIMEN';
3625 $this->gender = 'man';
3626 $this->note_public = 'This is a note public';
3627 $this->note_private = 'This is a note private';
3628 $this->email = 'email@specimen.com';
3629 $this->personal_email = 'personalemail@specimen.com';
3630 $this->socialnetworks = array(
3631 'skype' => 'skypepseudo',
3632 'twitter' => 'twitterpseudo',
3633 'facebook' => 'facebookpseudo',
3634 'linkedin' => 'linkedinpseudo',
3635 );
3636 $this->office_phone = '0999999999';
3637 $this->office_fax = '0999999998';
3638 $this->user_mobile = '0999999997';
3639 $this->personal_mobile = '0999999996';
3640 $this->admin = 0;
3641 $this->login = 'dolibspec';
3642 $this->pass = 'dolibSpec+@123';
3643 //$this->pass_indatabase='dolibspec'; Set after a fetch
3644 //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3645 $this->datec = $now;
3646 $this->datem = $now;
3647
3648 $this->datelastlogin = $now;
3649 $this->iplastlogin = '127.0.0.1';
3650 $this->datepreviouslogin = $now;
3651 $this->ippreviouslogin = '127.0.0.1';
3652 $this->statut = 1; // deprecated
3653 $this->status = 1;
3654
3655 $this->entity = 1;
3656
3657 return 1;
3658 }
3659
3666 public function info($id)
3667 {
3668 $sql = "SELECT u.rowid, u.login as ref, u.datec,";
3669 $sql .= " u.tms as date_modification, u.entity";
3670 $sql .= " FROM ".$this->db->prefix()."user as u";
3671 $sql .= " WHERE u.rowid = ".((int) $id);
3672
3673 $result = $this->db->query($sql);
3674 if ($result) {
3675 if ($this->db->num_rows($result)) {
3676 $obj = $this->db->fetch_object($result);
3677
3678 $this->id = $obj->rowid;
3679
3680 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3681 $this->date_creation = $this->db->jdate($obj->datec);
3682 $this->date_modification = $this->db->jdate($obj->date_modification);
3683 $this->entity = $obj->entity;
3684 }
3685
3686 $this->db->free($result);
3687 } else {
3688 dol_print_error($this->db);
3689 }
3690 }
3691
3692
3698 public function getNbOfEMailings()
3699 {
3700 $sql = "SELECT count(mc.email) as nb";
3701 $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3702 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3703 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
3704
3705 $resql = $this->db->query($sql);
3706 if ($resql) {
3707 $obj = $this->db->fetch_object($resql);
3708 $nb = $obj->nb;
3709
3710 $this->db->free($resql);
3711 return $nb;
3712 } else {
3713 $this->error = $this->db->error();
3714 return -1;
3715 }
3716 }
3717
3726 public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3727 {
3728 global $conf;
3729
3730 $sql = "SELECT count(rowid) as nb";
3731 $sql .= " FROM ".$this->db->prefix()."user";
3732 if ($option == 'superadmin') {
3733 $sql .= " WHERE entity = 0";
3734 } else {
3735 $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3736 if ($limitTo == 'active') {
3737 $sql .= " AND statut = 1";
3738 }
3739 }
3740 if ($admin >= 0) {
3741 $sql .= " AND admin = ".(int) $admin;
3742 }
3743
3744 $resql = $this->db->query($sql);
3745 if ($resql) {
3746 $obj = $this->db->fetch_object($resql);
3747 $nb = (int) $obj->nb;
3748
3749 $this->db->free($resql);
3750 return $nb;
3751 } else {
3752 $this->error = $this->db->lasterror();
3753 return -1;
3754 }
3755 }
3756
3757 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3764 public function update_ldap2dolibarr(&$ldapuser)
3765 {
3766 // phpcs:enable
3767 // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3768 global $user, $conf;
3769
3770 $socialnetworks = getArrayOfSocialNetworks();
3771
3772 $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3773 $this->firstname = $ldapuser->$tmpvar;
3774 $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3775 $this->lastname = $ldapuser->$tmpvar;
3776 $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3777 $this->login = $ldapuser->$tmpvar;
3778 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3779 $this->pass = $ldapuser->$tmpvar;
3780 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3781 $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3782
3783 $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3784 $this->office_phone = $ldapuser->$tmpvar;
3785 $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3786 $this->user_mobile = $ldapuser->$tmpvar;
3787 $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3788 $this->office_fax = $ldapuser->$tmpvar;
3789 $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3790 $this->email = $ldapuser->$tmpvar;
3791 foreach ($socialnetworks as $key => $value) {
3792 $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3793 $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3794 }
3795 $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3796 $this->ldap_sid = $ldapuser->$tmpvar;
3797
3798 $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3799 $this->job = $ldapuser->$tmpvar;
3800 $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3801 $this->note_public = $ldapuser->$tmpvar;
3802
3803 $result = $this->update($user);
3804
3805 dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3806
3807 return $result;
3808 }
3809
3810
3811 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3818 public function get_children()
3819 {
3820 // phpcs:enable
3821 $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3822 $sql .= " WHERE fk_user = ".((int) $this->id);
3823
3824 dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3825 $res = $this->db->query($sql);
3826 if ($res) {
3827 $users = array();
3828 while ($rec = $this->db->fetch_array($res)) {
3829 $user = new User($this->db);
3830 $user->fetch($rec['rowid']);
3831 $users[] = $user;
3832 }
3833 return $users;
3834 } else {
3835 dol_print_error($this->db);
3836 return -1;
3837 }
3838 }
3839
3840
3846 private function loadParentOf()
3847 {
3848 global $conf;
3849
3850 $this->parentof = array();
3851
3852 // Load array[child]=parent
3853 $sql = "SELECT fk_user as id_parent, rowid as id_son";
3854 $sql .= " FROM ".$this->db->prefix()."user";
3855 $sql .= " WHERE fk_user <> 0";
3856 $sql .= " AND entity IN (".getEntity('user').")";
3857
3858 dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3859 $resql = $this->db->query($sql);
3860 if ($resql) {
3861 while ($obj = $this->db->fetch_object($resql)) {
3862 $this->parentof[$obj->id_son] = $obj->id_parent;
3863 }
3864 return 1;
3865 } else {
3866 dol_print_error($this->db);
3867 return -1;
3868 }
3869 }
3870
3871 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3885 public function get_full_tree($deleteafterid = 0, $filter = '')
3886 {
3887 // phpcs:enable
3888 global $hookmanager;
3889
3890 // Actions hooked (by external module)
3891 $hookmanager->initHooks(array('userdao'));
3892
3893 $this->users = array();
3894
3895 // Init this->parentof that is array(id_son=>id_parent, ...)
3896 $this->loadParentOf();
3897
3898 // Init $this->users array
3899 $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
3900 $sql .= " FROM ".$this->db->prefix()."user as u";
3901 // Add fields from hooks
3902 $parameters = array();
3903 $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3904 if ($reshook > 0) {
3905 $sql .= $hookmanager->resPrint;
3906 } else {
3907 $sql .= " WHERE u.entity IN (".getEntity('user').")";
3908 }
3909 if ($filter) {
3910 $sql .= " AND ".$filter; // already sanitized
3911 }
3912
3913 dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3914 $resql = $this->db->query($sql);
3915 if ($resql) {
3916 $i = 0;
3917 while ($obj = $this->db->fetch_object($resql)) {
3918 $this->users[$obj->rowid]['rowid'] = $obj->rowid;
3919 $this->users[$obj->rowid]['id'] = $obj->rowid;
3920 $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
3921 $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
3922 $this->users[$obj->rowid]['firstname'] = $obj->firstname;
3923 $this->users[$obj->rowid]['lastname'] = $obj->lastname;
3924 $this->users[$obj->rowid]['login'] = $obj->login;
3925 $this->users[$obj->rowid]['statut'] = $obj->statut;
3926 $this->users[$obj->rowid]['entity'] = $obj->entity;
3927 $this->users[$obj->rowid]['email'] = $obj->email;
3928 $this->users[$obj->rowid]['gender'] = $obj->gender;
3929 $this->users[$obj->rowid]['admin'] = $obj->admin;
3930 $this->users[$obj->rowid]['photo'] = $obj->photo;
3931 // fields are filled with build_path_from_id_user
3932 $this->users[$obj->rowid]['fullpath'] = '';
3933 $this->users[$obj->rowid]['fullname'] = '';
3934 $this->users[$obj->rowid]['level'] = 0;
3935 $i++;
3936 }
3937 } else {
3938 dol_print_error($this->db);
3939 return -1;
3940 }
3941
3942 // We add the fullpath property to each element of the first level (no parent exists)
3943 dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3944 foreach ($this->users as $key => $val) {
3945 $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3946 if ($result < 0) {
3947 $this->error = 'ErrorLoopInHierarchy';
3948 return -1;
3949 }
3950 }
3951
3952 // Exclude leaf including $deleteafterid from tree
3953 if ($deleteafterid) {
3954 //print "Look to discard user ".$deleteafterid."\n";
3955 $keyfilter1 = '^'.$deleteafterid.'$';
3956 $keyfilter2 = '_'.$deleteafterid.'$';
3957 $keyfilter3 = '^'.$deleteafterid.'_';
3958 $keyfilter4 = '_'.$deleteafterid.'_';
3959 foreach (array_keys($this->users) as $key) {
3960 $fullpath = (string) $this->users[$key]['fullpath'];
3961 if (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
3962 || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath)) {
3963 unset($this->users[$key]);
3964 }
3965 }
3966 }
3967
3968 dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
3969 $this->users = dol_sort_array($this->users, 'fullname', 'asc', 1, 0, 1);
3970
3971 //var_dump($this->users);
3972
3973 return $this->users;
3974 }
3975
3984 public function getAllChildIds($addcurrentuser = 0)
3985 {
3986 $childids = array();
3987
3988 if (isset($this->cache_childids[$this->id])) {
3989 $childids = $this->cache_childids[$this->id];
3990 } else {
3991 // Init this->users
3992 $this->get_full_tree();
3993
3994 $idtoscan = $this->id;
3995
3996 dol_syslog("Build childid for id = ".$idtoscan);
3997 foreach ($this->users as $id => $val) {
3998 //var_dump($val['fullpath']);
3999 if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
4000 $childids[$val['id']] = $val['id'];
4001 }
4002 }
4003 }
4004 $this->cache_childids[$this->id] = $childids;
4005
4006 if ($addcurrentuser) {
4007 $childids[$this->id] = $this->id;
4008 }
4009
4010 return $childids;
4011 }
4012
4013 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4022 public function build_path_from_id_user($id_user, $protection = 0)
4023 {
4024 // phpcs:enable
4025 //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
4026
4027 if (!empty($this->users[$id_user]['fullpath'])) {
4028 // Already defined
4029 dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
4030 return 0;
4031 }
4032
4033 // Define fullpath and fullname
4034 $this->users[$id_user]['fullpath'] = '_'.$id_user;
4035 $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
4036 $i = 0;
4037 $cursor_user = $id_user;
4038
4039 $useridfound = array($id_user);
4040 while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) { // @phan-suppress-current-line PhanTypeMismatchProperty
4041 if (in_array($this->parentof[$cursor_user], $useridfound)) {
4042 dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
4043 return -1; // Should not happen. Protection against looping hierarchy
4044 }
4045 $useridfound[] = $this->parentof[$cursor_user];
4046 $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
4047 $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
4048 $i++;
4049 $cursor_user = $this->parentof[$cursor_user];
4050 }
4051
4052 // We count number of _ to have level
4053 $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
4054
4055 return 1;
4056 }
4057
4066 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4067 {
4068 $tables = array(
4069 'user',
4070 );
4071
4072 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4073 }
4074
4075
4081 public function loadStateBoard()
4082 {
4083 global $conf;
4084
4085 $this->nb = array();
4086
4087 $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
4088 $sql .= " FROM ".$this->db->prefix()."user as u";
4089 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4090 $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
4091 $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
4092 $sql .= " AND ug.fk_user = u.rowid";
4093 } else {
4094 $sql .= " WHERE u.entity IN (".getEntity('user').")";
4095 }
4096 $sql .= " AND u.statut > 0";
4097 //$sql.= " AND employee != 0";
4098
4099 $resql = $this->db->query($sql);
4100 if ($resql) {
4101 while ($obj = $this->db->fetch_object($resql)) {
4102 $this->nb["users"] = $obj->nb;
4103 }
4104 $this->db->free($resql);
4105 return 1;
4106 } else {
4107 dol_print_error($this->db);
4108 $this->error = $this->db->error();
4109 return -1;
4110 }
4111 }
4112
4124 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4125 {
4126 global $conf, $user, $langs;
4127
4128 $langs->load("user");
4129
4130 // Set the '$modele' to the name of the document template (model) to use
4131 if (!dol_strlen($modele)) {
4132 if (getDolGlobalString('USER_ADDON_PDF')) {
4133 $modele = getDolGlobalString('USER_ADDON_PDF');
4134 } else {
4135 $modele = 'bluesky';
4136 }
4137 }
4138
4139 $modelpath = "core/modules/user/doc/";
4140
4141 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4142 }
4143
4144 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4152 public function user_get_property($rowid, $mode)
4153 {
4154 // phpcs:enable
4155 $user_property = '';
4156
4157 if (empty($rowid)) {
4158 return '';
4159 }
4160
4161 $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
4162 $sql .= " FROM ".$this->db->prefix()."user";
4163 $sql .= " WHERE rowid = ".((int) $rowid);
4164
4165 $resql = $this->db->query($sql);
4166 if ($resql) {
4167 $nump = $this->db->num_rows($resql);
4168
4169 if ($nump) {
4170 $obj = $this->db->fetch_object($resql);
4171
4172 if ($mode == 'email') {
4173 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
4174 } elseif ($mode == 'mobile') {
4175 $user_property = $obj->user_mobile;
4176 } elseif ($mode == 'name') {
4177 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname);
4178 }
4179 }
4180 return $user_property;
4181 } else {
4182 dol_print_error($this->db);
4183 }
4184
4185 return '';
4186 }
4187
4195 public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
4196 {
4198 global $conf;
4199
4200 $encodedsecurekey = dol_hash($conf->file->instance_unique_id.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
4201 if (isModEnabled('multicompany')) {
4202 $entity_qr = '&entity='.((int) $conf->entity);
4203 } else {
4204 $entity_qr = '';
4205 }
4206 // Define $urlwithroot
4207 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
4208 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
4209 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
4210
4211 if ($typeofurl == 'internal') {
4212 $urlwithroot = DOL_URL_ROOT;
4213 }
4214
4215 return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
4216 }
4217
4231 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND', $entityfilter = false)
4232 {
4233 global $conf, $user;
4234
4235 $sql = "SELECT t.rowid";
4236 $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
4237
4238 if ($entityfilter) {
4239 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4240 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
4241 $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
4242 } else {
4243 $sql .= " WHERE t.entity = 0 OR EXISTS (";
4244 $sql .= " SELECT ug.rowid FROM " . $this->db->prefix() . "usergroup_user as ug";
4245 $sql .= " WHERE ug.fk_user = t.rowid AND ug.entity IN (" . getEntity('usergroup') . "))";
4246 }
4247 } else {
4248 $sql .= " WHERE t.entity IN (".getEntity('user').")";
4249 }
4250 } else {
4251 $sql .= " WHERE 1 = 1";
4252 }
4253
4254 // Manage filter
4255 $errormessage = '';
4256 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
4257 if ($errormessage) {
4258 $this->errors[] = $errormessage;
4259 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
4260 return -1;
4261 }
4262
4263 $sql .= $this->db->order($sortfield, $sortorder);
4264 if ($limit) {
4265 $sql .= $this->db->plimit($limit + 1, $offset);
4266 }
4267
4268 dol_syslog(__METHOD__, LOG_DEBUG);
4269
4270 $resql = $this->db->query($sql);
4271 if ($resql) {
4272 $this->users = array();
4273 $num = $this->db->num_rows($resql);
4274 if ($num) {
4275 while ($obj = $this->db->fetch_object($resql)) {
4276 $line = new self($this->db);
4277 $result = $line->fetch($obj->rowid);
4278 if ($result > 0 && !empty($line->id)) {
4279 $this->users[$obj->rowid] = clone $line;
4280 }
4281 }
4282 $this->db->free($resql);
4283 }
4284 return $num;
4285 } else {
4286 $this->errors[] = $this->db->lasterror();
4287 return -1;
4288 }
4289 }
4290
4298 private $findUserIdByEmailCache;
4299
4310 public function findUserIdByEmail($email)
4311 {
4312 if (isset($this->findUserIdByEmailCache[$email])) {
4313 return $this->findUserIdByEmailCache[$email];
4314 }
4315
4316 $this->findUserIdByEmailCache[$email] = -1;
4317
4318 $sql = 'SELECT rowid';
4319 $sql .= ' FROM '.$this->db->prefix().'user';
4320 if (getDolGlobalString('AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR')) {
4321 $sql .= " WHERE email LIKE '%".$this->db->escape($this->db->escapeforlike($email))."%'";
4322 } else {
4323 $sql .= " WHERE email = '".$this->db->escape($email)."'";
4324 }
4325 $sql .= ' LIMIT 1';
4326
4327 $resql = $this->db->query($sql);
4328 if (!$resql) {
4329 return -1;
4330 }
4331
4332 $obj = $this->db->fetch_object($resql);
4333 if (!$obj) {
4334 return -1;
4335 }
4336
4337 $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4338
4339 return $this->findUserIdByEmailCache[$email];
4340 }
4341
4348 public function cloneRights($fromId, $toId)
4349 {
4350 if (empty($fromId) || empty($toId)) {
4351 return -1;
4352 }
4353
4354 $this->db->begin();
4355
4356 // delete default rights for UserTo
4357 $sqlDelete = "DELETE FROM ".$this->db->prefix()."user_rights";
4358 $sqlDelete .= " WHERE fk_user = ".((int) $toId);
4359
4360 dol_syslog(get_class($this)."::clone_rights (delete default permissions)", LOG_DEBUG);
4361
4362 if (!$this->db->query($sqlDelete)) {
4363 $this->db->rollback();
4364 return -1;
4365 }
4366
4367 // Construction of the insertion request
4368 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id)";
4369 $sql .= " SELECT entity, ".((int) $toId).", fk_id";
4370 $sql .= " FROM ".$this->db->prefix()."user_rights src";
4371 $sql .= " WHERE fk_user = ".((int) $fromId);
4372 $sql .= " AND NOT EXISTS (";
4373 $sql .= " SELECT 1";
4374 $sql .= " FROM ".$this->db->prefix()."user_rights dest";
4375 $sql .= " WHERE dest.entity = src.entity";
4376 $sql .= " AND dest.fk_user = ".((int) $toId);
4377 $sql .= " AND dest.fk_id = src.fk_id";
4378 $sql .= " )";
4379
4380 dol_syslog(get_class($this)."::clone_rights", LOG_DEBUG);
4381
4382 // Execute request
4383 if (!$this->db->query($sql)) {
4384 $this->db->rollback();
4385 return -1;
4386 }
4387
4388 $this->db->commit();
4389 return 1;
4390 }
4391
4400 public function cloneCategories($fromId, $toId, $type = 'user')
4401 {
4402 $this->db->begin();
4403
4404 if (empty($type)) {
4405 $type = $this->table_element;
4406 }
4407
4408 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4409 $categorystatic = new Categorie($this->db);
4410
4411 $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_user)";
4412 $sql .= " SELECT fk_categorie, ".((int) $toId)." FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
4413 $sql .= " WHERE fk_user = ".((int) $fromId);
4414
4415 if (!$this->db->query($sql)) {
4416 $this->error = $this->db->lasterror();
4417 $this->db->rollback();
4418 return -1;
4419 }
4420
4421 $this->db->commit();
4422 return 1;
4423 }
4424}
global $dolibarr_main_url_root
$c
Definition line.php:331
$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.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage contact/addresses.
Class for MyObject.
Class to manage Dolibarr database access.
Class to manage warehouses.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage user groups.
Class to manage Dolibarr users.
fetch($id=0, $login='', $sid='', $loadpersonalconf=0, $entity=-1, $email='', $fk_socpeople=0, $use_email_oauth2=0)
Load a user from database with its id or ref (login).
SetInGroup($group, $entity, $notrigger=0)
Add user into a group.
LibStatut($status, $mode=0)
Return the label of a status of user (active, inactive)
loadRights($moduletag='', $forcereload=0)
Load permissions granted to a user->id into object user->rights.
get_children()
Return and array with all instantiated first level children users of current user.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
loadStateBoard()
Load metrics this->nb for dashboard.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
info($id)
Load info of user object.
create_from_contact($contact, $login='', $password='')
Create a user from a contact object.
setstatus($status)
Change status of a user.
get_full_tree($deleteafterid=0, $filter='')
Build the hierarchy/tree of users into an array.
_load_ldap_info()
Initialize the info array (array of LDAP values) that will be used to call LDAP functions.
delrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0)
Remove a right to the user.
update_last_login_date()
Update the user's last login date in the database.
__construct($db)
Constructor of the class.
RemoveFromGroup($group, $entity, $notrigger=0)
Remove a user from a group.
isNotIntoValidityDateRange()
Return a link with photo Use this->id,this->photo.
getNbOfUsers($limitTo, $option='', $admin=-1)
Return number of existing users.
set_default_rights()
Assign rights by default.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND', $entityfilter=false)
Load all objects into $this->users.
getOnlineVirtualCardUrl($mode='', $typeofurl='external')
Return string with full Url to virtual card.
update($user, $notrigger=0, $nosyncmember=0, $nosyncmemberpass=0, $nosynccontact=0)
Update a user into database (and also password if this->pass is defined)
getLoginUrl($withpictoimg=0, $option='', $notooltip=0, $morecss='')
Return clickable link of login (optionally with picto)
setCategories($categories)
Sets object to supplied categories.
loadParentOf()
Load this->parentof that is array(id_son=>id_parent, ...)
fetch_clicktodial()
Read clicktodial information for user.
build_path_from_id_user($id_user, $protection=0)
For user id_user and its children available in this->users, define property fullpath and fullname.
error()
Renvoie la derniere erreur fonctionnelle de manipulation de l'objet.
cloneCategories($fromId, $toId, $type='user')
Copy related categories to another object.
getAllChildIds($addcurrentuser=0)
Return list of all child user ids in hierarchy (all sublevels).
initAsSpecimen()
Initialise an instance with random values.
setPassword($user, $password='', $changelater=0, $notrigger=0, $nosyncmember=0, $passwordalreadycrypted=0, $flagdelsessionsbefore=1)
Change password of a user.
clearrights()
Clear all permissions array of user.
update_clicktodial()
Update clicktodial info.
cloneRights($fromId, $toId)
Clone permissions of user.
getLibStatut($mode=0)
Return the label of the status of user (active, inactive)
getNomUrl($withpictoimg=0, $option='', $infologin=0, $notooltip=0, $maxlen=24, $hidethirdpartylogo=0, $mode='', $morecss='valignmiddle', $save_lastsearch_value=-1)
Return a HTML link to the user card (with optionally the picto) Use this->id,this->lastname,...
create_from_member($member, $login='')
Create a user into database from a member object.
loadPersonalConf()
Load const values from database table user_param and set it into user->conf->XXX.
_load_ldap_dn($info, $mode=0)
Retourne chaine DN complete dans l'annuaire LDAP pour l'objet.
loadDefaultValues()
Load default values from database table into property ->default_values.
getPhotoUrl($width, $height, $cssclass='', $imagesize='')
Return a link with photo Use this->id,this->photo.
update_ldap2dolibarr(&$ldapuser)
Update user using data from the LDAP.
getrights($moduletag='', $forcereload=0)
Load permissions granted to a user->id into object user->rights TODO Remove this method.
user_get_property($rowid, $mode)
Return property of user from its id.
send_password($user, $password='', $changelater=0)
Send a new password (or instructions to reset it) by email.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (optionally with picto)
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
addrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0)
Add a right to the user.
create($user, $notrigger=0)
Create a user into database.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
findUserIdByEmail($email)
Find a user by the given e-mail and return it's user id when found.
getTooltipContentArray($params)
getTooltipContentArray
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:660
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
Definition date.lib.php:646
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
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.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
getArrayOfSocialNetworks()
Get array of social network dictionary.
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.
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)
Load conf file (file must exists)
Definition inc.php:423
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
global $dolibarr_main_demo
Definition index.php:57
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
dol_verifyHash($chain, $hash, $type='0')
Compute a hash and compare it to the given one For backward compatibility reasons,...
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dolGetLdapPasswordHash($password, $type='md5')
Returns a specific ldap hash of a password.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.