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 (isModEnabled('multicompany') && !empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2279 // entity flag can be set/unset only by another superadmin user, and only when multicompany is enabled.
2280 // Without multicompany, entity must never be written here: fetch() forces an admin's entity to 0 in memory
2281 // (an admin is a global admin without multicompany), and persisting that would wrongly turn the user into
2282 // a "whole database" (entity 0) admin.
2283 $sql .= ", entity = ".((int) $this->entity);
2284 }
2285 $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
2286 $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
2287 $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
2288 $sql .= ", fk_establishment = ".($this->fk_establishment > 0 ? $this->fk_establishment : "null");
2289 $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2290 $sql .= " WHERE rowid = ".((int) $this->id);
2291
2292 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2293 $resql = $this->db->query($sql);
2294 if ($resql) {
2295 $nbrowsaffected += $this->db->affected_rows($resql);
2296
2297 // Update password
2298 if (!empty($this->pass)) {
2299 if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2300 // If a new value for password is set and different than the one encrypted into database
2301 $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2302 if (is_int($result) && $result < 0) {
2303 return -5;
2304 }
2305 }
2306 }
2307
2308 // If user is linked to a member, remove old link to this member
2309 if ($this->fk_member > 0) {
2310 dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2311 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2312 $resql = $this->db->query($sql);
2313 if (!$resql) {
2314 $this->error = $this->db->error();
2315 $this->db->rollback();
2316 return -5;
2317 }
2318 }
2319 // Set link to user
2320 dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2321 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2322 $resql = $this->db->query($sql);
2323 if (!$resql) {
2324 $this->error = $this->db->error();
2325 $this->db->rollback();
2326 return -5;
2327 }
2328
2329 if ($nbrowsaffected) { // If something has changed in data
2330 if ($this->fk_member > 0 && !$nosyncmember) {
2331 dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2332
2333 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2334
2335 // This user is linked with a member, so we also update member information
2336 // if this is an update.
2337 $adh = new Adherent($this->db);
2338 $result = $adh->fetch($this->fk_member);
2339
2340 if ($result > 0) {
2341 $adh->civility_code = $this->civility_code;
2342 $adh->firstname = $this->firstname;
2343 $adh->lastname = $this->lastname;
2344 $adh->login = $this->login;
2345 $adh->gender = $this->gender;
2346 $adh->birth = $this->birth;
2347
2348 $adh->pass = $this->pass;
2349
2350 $adh->address = $this->address;
2351 $adh->town = $this->town;
2352 $adh->zip = $this->zip;
2353 $adh->state_id = $this->state_id;
2354 $adh->country_id = $this->country_id;
2355
2356 $adh->email = $this->email;
2357
2358 $adh->socialnetworks = $this->socialnetworks;
2359
2360 $adh->phone = $this->office_phone;
2361 $adh->phone_mobile = $this->user_mobile;
2362
2363 $adh->default_lang = $this->lang;
2364
2365 $adh->user_id = $this->id;
2366 $adh->user_login = $this->login;
2367
2368 $result = $adh->update($user, 0, 1, 0);
2369 if ($result < 0) {
2370 $this->error = $adh->error;
2371 $this->errors = $adh->errors;
2372 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2373 $error++;
2374 }
2375 } elseif ($result < 0) {
2376 $this->error = $adh->error;
2377 $this->errors = $adh->errors;
2378 $error++;
2379 }
2380 }
2381
2382 if ($this->contact_id > 0 && !$nosynccontact) {
2383 dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2384
2385 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2386
2387 // This user is linked with a contact, so we also update contact information if this is an update.
2388 $tmpobj = new Contact($this->db);
2389 $result = $tmpobj->fetch($this->contact_id);
2390
2391 if ($result >= 0) {
2392 $tmpobj->civility_code = $this->civility_code;
2393 $tmpobj->firstname = $this->firstname;
2394 $tmpobj->lastname = $this->lastname;
2395 $tmpobj->login = $this->login;
2396 $tmpobj->gender = $this->gender;
2397 $tmpobj->birth = $this->birth;
2398
2399 //$tmpobj->pass=$this->pass;
2400
2401 $tmpobj->email = $this->email;
2402
2403 $tmpobj->socialnetworks = $this->socialnetworks;
2404
2405 $tmpobj->phone_pro = $this->office_phone;
2406 $tmpobj->phone_mobile = $this->user_mobile;
2407 $tmpobj->fax = $this->office_fax;
2408
2409 $tmpobj->default_lang = $this->lang;
2410
2411 $tmpobj->address = $this->address;
2412 $tmpobj->town = $this->town;
2413 $tmpobj->zip = $this->zip;
2414 $tmpobj->state_id = $this->state_id;
2415 $tmpobj->country_id = $this->country_id;
2416
2417 $tmpobj->user_id = $this->id;
2418 $tmpobj->user_login = $this->login;
2419
2420 $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2421 if ($result < 0) {
2422 $this->error = $tmpobj->error;
2423 $this->errors = $tmpobj->errors;
2424 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2425 $error++;
2426 }
2427 } else {
2428 $this->error = $tmpobj->error;
2429 $this->errors = $tmpobj->errors;
2430 $error++;
2431 }
2432 }
2433 }
2434
2435 $action = 'update';
2436
2437 // Actions on extra fields
2438 if (!$error) {
2439 $result = $this->insertExtraFields();
2440 if ($result < 0) {
2441 $error++;
2442 }
2443 }
2444
2445 if (!$error && !$notrigger) {
2446 // Call trigger
2447 $result = $this->call_trigger('USER_MODIFY', $user);
2448 if ($result < 0) {
2449 $error++;
2450 }
2451 // End call triggers
2452 }
2453
2454 if (!$error) {
2455 $this->db->commit();
2456 return $nbrowsaffected;
2457 } else {
2458 dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2459 $this->db->rollback();
2460 return -1;
2461 }
2462 } else {
2463 $this->error = $this->db->lasterror();
2464 $this->db->rollback();
2465 return -2;
2466 }
2467 }
2468
2469 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2476 public function update_last_login_date()
2477 {
2478 // phpcs:enable
2479 $now = dol_now();
2480
2481 $userremoteip = getUserRemoteIP();
2482
2483 $sql = "UPDATE ".$this->db->prefix()."user SET";
2484 $sql .= " datepreviouslogin = datelastlogin,";
2485 $sql .= " ippreviouslogin = iplastlogin,";
2486 $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2487 $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2488 $sql .= " tms = tms"; // The last update date must change because the last login date is updated
2489 $sql .= " WHERE rowid = ".((int) $this->id);
2490
2491 dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2492 $resql = $this->db->query($sql);
2493 if ($resql) {
2494 $this->datepreviouslogin = $this->datelastlogin;
2495 $this->datelastlogin = $now;
2496 $this->ippreviouslogin = $this->iplastlogin;
2497 $this->iplastlogin = $userremoteip;
2498 return 1;
2499 } else {
2500 $this->error = $this->db->lasterror().' sql='.$sql;
2501 return -1;
2502 }
2503 }
2504
2505
2518 public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2519 {
2520 global $conf, $langs;
2521 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2522
2523 $error = 0;
2524
2525 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2526
2527 // If new password not provided, we generate one
2528 if (!$password) {
2529 $password = getRandomPassword(false);
2530 }
2531
2532 $password_crypted = null;
2533 // Check and encrypt the password
2534 if (empty($passwordalreadycrypted)) {
2535 if (getDolGlobalString('USER_PASSWORD_GENERATED')) {
2536 // Add a check on rules for password syntax using the setup of the password generator
2537 $modGeneratePassClass = 'modGeneratePass'.ucfirst($conf->global->USER_PASSWORD_GENERATED);
2538
2539 include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2540 if (class_exists($modGeneratePassClass)) {
2541 $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2542 '@phan-var-force ModeleGenPassword $modGeneratePass';
2543
2544 // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2545 $modGeneratePass->WithoutAmbi = 0;
2546
2547 // Call to validatePassword($password) to check pass match rules
2548 $testpassword = $modGeneratePass->validatePassword($password);
2549 if (!$testpassword) {
2550 $this->error = $modGeneratePass->error;
2551 return -1;
2552 }
2553 }
2554 }
2555
2556
2557 // Now, we encrypt the new password
2558 $password_crypted = dol_hash($password);
2559 }
2560
2561 // Update password
2562 if (!$changelater) {
2563 if (!is_object($this->oldcopy)) {
2564 $this->oldcopy = clone $this;
2565 }
2566
2567 $now = dol_now();
2568
2569 $this->db->begin();
2570
2571 $sql = "UPDATE ".$this->db->prefix()."user";
2572 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2573 $sql .= " datelastpassvalidation = '".$this->db->idate(dol_now())."',";
2574 $sql .= " pass_temp = null";
2575 if (!empty($flagdelsessionsbefore)) {
2576 $sql .= ", flagdelsessionsbefore = '".$this->db->idate($now - 5, 'gmt')."'";
2577 }
2578 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
2579 $sql .= ", pass = null";
2580 } else {
2581 $sql .= ", pass = '".$this->db->escape($password)."'";
2582 }
2583 $sql .= " WHERE rowid = ".((int) $this->id);
2584
2585 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2586
2587 $result = $this->db->query($sql);
2588 if ($result) {
2589 if ($this->db->affected_rows($result)) {
2590 $this->pass = $password;
2591 $this->pass_indatabase = $password;
2592 $this->pass_indatabase_crypted = (string) $password_crypted;
2593
2594 if ($this->fk_member && !$nosyncmember) {
2595 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2596
2597 // This user is linked with a member, so we also update members information
2598 // if this is an update.
2599 $adh = new Adherent($this->db);
2600 $result = $adh->fetch($this->fk_member);
2601
2602 if ($result >= 0) {
2603 $result = $adh->setPassword($user, $this->pass, (!getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 0 : 1), 1); // The encryption is not managed in the 'adherent' module
2604 if (is_int($result) && $result < 0) {
2605 $this->error = $adh->error;
2606 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2607 $error++;
2608 }
2609 } else {
2610 $this->error = $adh->error;
2611 $error++;
2612 }
2613 }
2614
2615 dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2616
2617 // Call trigger for the "security events" log
2618 $user->context['audit'] = 'login='.$user->login;
2619 if (!empty($flagdelsessionsbefore)) {
2620 $user->context['audit'] .= " - flagdelsessionsbefore set to '".$this->db->idate($now - 5, 'gmt')."'";
2621 }
2622
2623 if (!$error && !$notrigger) {
2624 // Call trigger
2625 $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2626 if ($result < 0) {
2627 $error++;
2628 $this->db->rollback();
2629 return -1;
2630 }
2631 // End call triggers
2632 }
2633
2634 $this->db->commit();
2635 return $this->pass;
2636 } else {
2637 $this->db->rollback();
2638 return 0;
2639 }
2640 } else {
2641 $this->db->rollback();
2642 dol_print_error($this->db);
2643 return -1;
2644 }
2645 } else {
2646 // We store password in password temporary field.
2647 // After receiving confirmation link, we will erase and store it in pass_crypted
2648 $sql = "UPDATE ".$this->db->prefix()."user";
2649 $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2650 $sql .= " WHERE rowid = ".((int) $this->id);
2651
2652 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2653 $result = $this->db->query($sql);
2654 if ($result) {
2655 return $password;
2656 } else {
2657 dol_print_error($this->db);
2658 return -3;
2659 }
2660 }
2661 }
2662
2663 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2672 public function send_password($user, $password = '', $changelater = 0)
2673 {
2674 // phpcs:enable
2675 global $conf, $langs;
2677
2678 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2679
2680 $msgishtml = 0;
2681
2682 // Define $msg
2683 $mesg = '';
2684
2685 $outputlangs = new Translate("", $conf);
2686
2687 if (getDolGlobalString('MAIN_LANG_DEFAULT')) {
2688 $outputlangs->setDefaultLang(getDolGlobalString('MAIN_LANG_DEFAULT'));
2689 } else { // If user has not defined its own language, we used current language
2690 $outputlangs = $langs;
2691 }
2692
2693 // Load translation files required by the page
2694 $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2695
2696 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', constant('DOL_APPLICATION_TITLE'));
2697
2698 $subject = '['.$appli.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2699
2700 // Define $urlwithroot
2701 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2702 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2703
2704 if (!$changelater) {
2705 $url = $urlwithroot.'/';
2706 if (getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD')) {
2707 $url = getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD');
2708 }
2709
2710 dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2711
2712 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2713 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2714 $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2715 $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2716 $mesg .= "\n";
2717
2718 $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2719 $mesg .= "--\n";
2720 $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2721 } else {
2722 //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2723 $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2724 $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2725 if (isModEnabled('multicompany')) {
2726 $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2727 }
2728
2729 dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2730
2731 $msgishtml = 1;
2732
2733 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2734 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2735 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2736 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2737 $mesg .= "<br>\n";
2738 $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2739 $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2740 $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2741 }
2742
2743 $trackid = 'use'.$this->id;
2744 $sendcontext = 'passwordreset';
2745
2746 $mailfile = new CMailFile(
2747 $subject,
2748 $this->email,
2749 getDolGlobalString("MAIN_MAIL_EMAIL_FROM_PASSWORDRESET", getDolGlobalString("MAIN_MAIL_EMAIL_FROM")),
2750 $mesg,
2751 array(),
2752 array(),
2753 array(),
2754 '',
2755 '',
2756 0,
2757 $msgishtml,
2758 '',
2759 '',
2760 $trackid,
2761 '',
2762 $sendcontext
2763 );
2764
2765 if ($mailfile->sendfile()) {
2766 return 1;
2767 } else {
2768 $langs->trans("errors");
2769 $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2770 return -1;
2771 }
2772 }
2773
2779 public function error()
2780 {
2781 return $this->error;
2782 }
2783
2784
2785 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2791 public function fetch_clicktodial()
2792 {
2793 // phpcs:enable
2794 $sql = "SELECT url, login, pass, poste ";
2795 $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2796 $sql .= " WHERE u.fk_user = ".((int) $this->id);
2797
2798 $resql = $this->db->query($sql);
2799 if ($resql) {
2800 if ($this->db->num_rows($resql)) {
2801 $obj = $this->db->fetch_object($resql);
2802
2803 $this->clicktodial_url = $obj->url;
2804 $this->clicktodial_login = $obj->login;
2805 $this->clicktodial_password = $obj->pass;
2806 $this->clicktodial_poste = $obj->poste;
2807 }
2808
2809 $this->clicktodial_loaded = 1; // Data loaded (found or not)
2810
2811 $this->db->free($resql);
2812 return 1;
2813 } else {
2814 $this->error = $this->db->error();
2815 return -1;
2816 }
2817 }
2818
2819 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2825 public function update_clicktodial()
2826 {
2827 // phpcs:enable
2828 $this->db->begin();
2829
2830 $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2831 $sql .= " WHERE fk_user = ".((int) $this->id);
2832
2833 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2834
2835 $result = $this->db->query($sql);
2836
2837 $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
2838 $sql .= " (fk_user,url,login,pass,poste)";
2839 $sql .= " VALUES (".$this->id;
2840 $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2841 $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2842 $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2843 $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2844
2845 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2846
2847 $result = $this->db->query($sql);
2848 if ($result) {
2849 $this->db->commit();
2850 return 1;
2851 } else {
2852 $this->db->rollback();
2853 $this->error = $this->db->lasterror();
2854 return -1;
2855 }
2856 }
2857
2858
2859 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2868 public function SetInGroup($group, $entity, $notrigger = 0)
2869 {
2870 // phpcs:enable
2871 global $conf, $langs, $user;
2872
2873 $error = 0;
2874
2875 $this->db->begin();
2876
2877 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2878 $sql .= " WHERE fk_user = ".((int) $this->id);
2879 $sql .= " AND fk_usergroup = ".((int) $group);
2880 $sql .= " AND entity = ".((int) $entity);
2881
2882 $result = $this->db->query($sql);
2883
2884 $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
2885 $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
2886
2887 $result = $this->db->query($sql);
2888 if ($result) {
2889 if (!$error && !$notrigger) {
2890 $this->context = array('audit' => $langs->trans("UserSetInGroup"), 'newgroupid' => $group);
2891
2892 // Call trigger
2893 $result = $this->call_trigger('USER_MODIFY', $user);
2894 if ($result < 0) {
2895 $error++;
2896 }
2897 // End call triggers
2898 }
2899
2900 if (!$error) {
2901 $this->db->commit();
2902 return 1;
2903 } else {
2904 dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2905 $this->db->rollback();
2906 return -2;
2907 }
2908 } else {
2909 $this->error = $this->db->lasterror();
2910 $this->db->rollback();
2911 return -1;
2912 }
2913 }
2914
2915 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2924 public function RemoveFromGroup($group, $entity, $notrigger = 0)
2925 {
2926 // phpcs:enable
2927 global $conf, $langs, $user;
2928
2929 $error = 0;
2930
2931 $this->db->begin();
2932
2933 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2934 $sql .= " WHERE fk_user = ".((int) $this->id);
2935 $sql .= " AND fk_usergroup = ".((int) $group);
2936 if (empty($entity)) {
2937 $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
2938 } else {
2939 $sql .= " AND entity = ".((int) $entity);
2940 }
2941
2942 $result = $this->db->query($sql);
2943 if ($result) {
2944 if (!$error && !$notrigger) {
2945 $this->context = array('audit' => $langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
2946
2947 // Call trigger
2948 $result = $this->call_trigger('USER_MODIFY', $user);
2949 if ($result < 0) {
2950 $error++;
2951 }
2952 // End call triggers
2953 }
2954
2955 if (!$error) {
2956 $this->db->commit();
2957 return 1;
2958 } else {
2959 dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2960 $this->db->rollback();
2961 return -2;
2962 }
2963 } else {
2964 $this->error = $this->db->lasterror();
2965 $this->db->rollback();
2966 return -1;
2967 }
2968 }
2969
2970
2978 {
2979 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2980
2981 $now = dol_now();
2982
2983 //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
2984
2985 // Check date start validity
2986 if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
2987 return 1;
2988 }
2989 // Check date end validity
2990 if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
2991 return 1;
2992 }
2993
2994 return 0;
2995 }
2996
2997
3009 public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
3010 {
3011 $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3012 $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
3013 $result .= '</a>';
3014
3015 return $result;
3016 }
3017
3024 public function getTooltipContentArray($params)
3025 {
3026 global $conf, $langs, $menumanager;
3027 global $dolibarr_main_demo;
3028
3029 $infologin = $params['infologin'] ?? 0;
3030 $option = $params['option'] ?? '';
3031
3032 $data = [];
3033 if (!empty($this->photo)) {
3034 $photo = '<div class="photointooltip floatright">';
3035 $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
3036 $photo .= '</div>';
3037 $data['photo'] = $photo;
3038 //$label .= '<div style="clear: both;"></div>';
3039 }
3040
3041 // Info Login
3042 $data['opendiv'] = '<div class="centpercent divtooltip">';
3043 $data['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
3044 $data['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs));
3045 if (!empty($this->login)) {
3046 $data['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
3047 }
3048 if (!empty($this->job)) {
3049 $data['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
3050 }
3051 $data['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
3052 if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
3053 $phonelist = array();
3054 if ($this->office_phone) {
3055 $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3056 }
3057 if ($this->office_fax) {
3058 $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3059 }
3060 if ($this->user_mobile) {
3061 $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3062 }
3063 $data['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
3064 }
3065 if (!empty($this->admin)) {
3066 $data['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
3067 }
3068 if (!empty($this->accountancy_code) || $option == 'accountancy') {
3069 $langs->load("companies");
3070 $data['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
3071 }
3072 $company = '';
3073 if (!empty($this->socid)) { // Add thirdparty for external users
3074 $thirdpartystatic = new Societe($this->db);
3075 $thirdpartystatic->fetch($this->socid);
3076 $companyimg = '';
3077 if (empty($params['hidethirdpartylogo'])) {
3078 $companyimg = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3079 }
3080 $company = ' ('.$langs->trans("Company").': '.($companyimg ? $companyimg : img_picto('', 'company')).' '.dol_string_nohtmltag($thirdpartystatic->name).')';
3081 }
3082 $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
3083 $data['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
3084 $data['closediv'] = '</div>';
3085
3086 if ($infologin > 0) {
3087 $data['newlinelogin'] = '<br>';
3088 $data['session'] = '<br><u>'.$langs->trans("Session").'</u>';
3089 $data['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
3090 if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
3091 $data['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
3092 }
3093 $data['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
3094 $data['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
3095 $data['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
3096 $data['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
3097 // @phan-suppress-next-line PhanRedefinedClassReference
3098 $data['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
3099 $s = picto_from_langcode($langs->getDefaultLang());
3100 $data['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
3101 $data['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
3102 $data['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
3103 $data['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
3104 if ($conf->browser->layout == 'phone') {
3105 $data['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
3106 }
3107 if (!empty($_SESSION["disablemodules"])) {
3108 $data['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(implode(', ', explode(',', $_SESSION["disablemodules"])));
3109 }
3110 }
3111
3112 return $data;
3113 }
3114
3130 public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = 'valignmiddle', $save_lastsearch_value = -1)
3131 {
3132 global $langs, $hookmanager, $user;
3133
3134 if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
3135 $option = 'nolink';
3136 }
3137
3138 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
3139 $withpictoimg = 0;
3140 }
3141
3142 $result = '';
3143 $params = [
3144 'id' => $this->id,
3145 'objecttype' => $this->element,
3146 'infologin' => $infologin,
3147 'option' => $option,
3148 'hidethirdpartylogo' => $hidethirdpartylogo,
3149 ];
3150 $classfortooltip = 'classfortooltip';
3151 $dataparams = '';
3152 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3153 $classfortooltip = 'classforajaxtooltip';
3154 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3155 $label = '';
3156 } else {
3157 $label = implode($this->getTooltipContentArray($params));
3158 }
3159
3160 $companylink = '';
3161 if (!empty($this->socid)) { // Add thirdparty for external users
3162 $thirdpartystatic = new Societe($this->db);
3163 $thirdpartystatic->fetch($this->socid);
3164 if (empty($hidethirdpartylogo)) {
3165 $companylink = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3166 }
3167 }
3168
3169 if ($infologin < 0) {
3170 $label = '';
3171 }
3172
3173 $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id;
3174 if ($option == 'leave') {
3175 $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id;
3176 }
3177
3178 if ($option != 'nolink') {
3179 // Add param to save lastsearch_values or not
3180 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3181 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3182 $add_save_lastsearch_values = 1;
3183 }
3184 if ($add_save_lastsearch_values) {
3185 $url .= '&save_lastsearch_values=1';
3186 }
3187 }
3188
3189 $linkstart = '<a href="'.$url.'"';
3190 $linkclose = "";
3191 if (empty($notooltip)) {
3192 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3193 $langs->load("users");
3194 $label = $langs->trans("ShowUser");
3195 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3196 }
3197 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3198 $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
3199 } else {
3200 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
3201 }
3202
3203 $linkstart .= $linkclose.'>';
3204 $linkend = '</a>';
3205
3206 //if ($withpictoimg == -1) $result.='<div class="nowrap">';
3207 $result .= (($option == 'nolink') ? '' : $linkstart);
3208 if ($withpictoimg) {
3209 $paddafterimage = '';
3210 if (abs((int) $withpictoimg) == 1) {
3211 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3212 }
3213 // Only picto
3214 if ($withpictoimg > 0) {
3215 $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>';
3216 } else {
3217 // Picto must be a photo
3218 $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>';
3219 }
3220 $result .= $picto;
3221 }
3222 if ($withpictoimg > -2 && $withpictoimg != 2) {
3223 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3224 $result .= '<span class="nopadding usertext'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
3225 }
3226 if ($mode == 'login') {
3227 $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
3228 } else {
3229 $result .= dol_string_nohtmltag($this->getFullName($langs, 0, ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
3230 }
3231 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3232 $result .= '</span>';
3233 }
3234 }
3235 $result .= (($option == 'nolink') ? '' : $linkend);
3236 //if ($withpictoimg == -1) $result.='</div>';
3237
3238 $result .= $companylink;
3239
3240 global $action;
3241 $hookmanager->initHooks(array('userdao'));
3242 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
3243 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3244 if ($reshook > 0) {
3245 $result = $hookmanager->resPrint;
3246 } else {
3247 $result .= $hookmanager->resPrint;
3248 }
3249
3250 return $result;
3251 }
3252
3262 public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
3263 {
3264 global $langs, $user;
3265
3266 $result = '';
3267
3268 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3269 $linkend = '</a>';
3270
3271 //Check user's rights to see an other user
3272 if ((!$user->hasRight('user', 'user', 'lire') && $this->id != $user->id)) {
3273 $option = 'nolink';
3274 }
3275
3276 if ($option == 'xxx') {
3277 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3278 $linkend = '</a>';
3279 }
3280
3281 if ($option == 'nolink') {
3282 $linkstart = '';
3283 $linkend = '';
3284 }
3285
3286 $result .= $linkstart;
3287 if ($withpictoimg) {
3288 $paddafterimage = '';
3289 if (abs($withpictoimg) == 1) {
3290 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3291 }
3292 // Only picto
3293 if ($withpictoimg > 0) {
3294 $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3295 } else {
3296 // Picto must be a photo
3297 $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>';
3298 }
3299 $result .= $picto;
3300 }
3301 $result .= $this->login;
3302 $result .= $linkend;
3303
3304 return $result;
3305 }
3306
3313 public function getLibStatut($mode = 0)
3314 {
3315 return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3316 }
3317
3318 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3326 public function LibStatut($status, $mode = 0)
3327 {
3328 // phpcs:enable
3329 global $langs;
3330
3331 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3332 global $langs;
3333 //$langs->load("mymodule");
3334 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3335 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3336 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3337 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3338 }
3339
3340 $statusType = 'status5';
3341 if ($status == self::STATUS_ENABLED) {
3342 $statusType = 'status4';
3343 }
3344
3345 $label = $this->labelStatus[$status];
3346 $labelshort = $this->labelStatusShort[$status];
3347
3348 $now = dol_now();
3349 if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3350 $statusType = 'status3';
3351 $label .= ' ('.$langs->trans("UserNotYetValid").')';
3352 }
3353 if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3354 $statusType = 'status2';
3355 $label .= ' ('.$langs->trans("UserExpired").')';
3356 }
3357
3358 return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3359 }
3360
3361
3369 public function getKanbanView($option = '', $arraydata = null)
3370 {
3371 global $langs;
3372
3373 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3374
3375 $return = '<div class="box-flex-item box-flex-grow-zero">';
3376 $return .= '<div class="info-box info-box-sm">';
3377 $return .= '<span class="info-box-icon bg-infobox-action">';
3378
3379 $label = '';
3380 if (!empty($this->photo)) {
3381 //$label .= '<div class="photointooltip floatright">';
3382 $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
3383 //$label .= '</div>';
3384 //$label .= '<div style="clear: both;"></div>';
3385 $return .= $label;
3386 } else {
3387 $return .= img_picto('', $this->picto);
3388 }
3389
3390 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3391 $return .= '</span>';
3392 $return .= '<div class="info-box-content">';
3393 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3394 if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3395 $return .= img_picto($langs->trans("SuperAdministratorDesc"), 'redstar', 'class="valignmiddle paddingright paddingleft"');
3396 } elseif ($this->admin) {
3397 $return .= img_picto($langs->trans("AdministratorDesc"), 'star', 'class="valignmiddle paddingright paddingleft"');
3398 }
3399 $return .= '</span>';
3400 if ($selected >= 0) {
3401 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3402 }
3403 if (property_exists($this, 'label')) {
3404 $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3405 }
3406 if ($this->email) {
3407 $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3408 }
3409 if (method_exists($this, 'getLibStatut')) {
3410 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3411 }
3412 $return .= '</div>';
3413 $return .= '</div>';
3414 $return .= '</div>';
3415
3416 return $return;
3417 }
3418
3419
3420 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3421 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3431 public function _load_ldap_dn($info, $mode = 0)
3432 {
3433 // phpcs:enable
3434 global $conf;
3435 $dn = '';
3436 if ($mode == 0) {
3437 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')]."," . getDolGlobalString('LDAP_USER_DN');
3438 } elseif ($mode == 1) {
3439 $dn = getDolGlobalString('LDAP_USER_DN');
3440 } elseif ($mode == 2) {
3441 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')];
3442 }
3443 return $dn;
3444 }
3445
3446 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3447 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3453 public function _load_ldap_info()
3454 {
3455 // phpcs:enable
3456 global $conf, $langs;
3457
3458 $info = array();
3459
3460 $socialnetworks = getArrayOfSocialNetworks();
3461
3462 $keymodified = false;
3463
3464 // Object classes
3465 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_USER_OBJECT_CLASS'));
3466
3467 $this->fullname = $this->getFullName($langs);
3468
3469 // Possible LDAP KEY (constname => varname)
3470 $ldapkey = array(
3471 'LDAP_FIELD_FULLNAME' => 'fullname',
3472 'LDAP_FIELD_NAME' => 'lastname',
3473 'LDAP_FIELD_FIRSTNAME' => 'firstname',
3474 'LDAP_FIELD_LOGIN' => 'login',
3475 'LDAP_FIELD_LOGIN_SAMBA' => 'login',
3476 'LDAP_FIELD_PHONE' => 'office_phone',
3477 'LDAP_FIELD_MOBILE' => 'user_mobile',
3478 'LDAP_FIELD_FAX' => 'office_fax',
3479 'LDAP_FIELD_MAIL' => 'email',
3480 'LDAP_FIELD_SID' => 'ldap_sid',
3481 );
3482
3483 // Champs
3484 foreach ($ldapkey as $constname => $varname) {
3485 if (!empty($this->$varname) && getDolGlobalString($constname)) {
3486 $info[getDolGlobalString($constname)] = $this->$varname;
3487
3488 // Check if it is the LDAP key and if its value has been changed
3489 if (getDolGlobalString('LDAP_KEY_USERS') && $conf->global->LDAP_KEY_USERS == getDolGlobalString($constname)) {
3490 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->$varname != $this->oldcopy->$varname) {
3491 $keymodified = true; // For check if LDAP key has been modified
3492 }
3493 }
3494 }
3495 }
3496 foreach ($socialnetworks as $key => $value) {
3497 if (!empty($this->socialnetworks[$value['label']]) && getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))) {
3498 $info[getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3499 }
3500 }
3501 if ($this->address && getDolGlobalString('LDAP_FIELD_ADDRESS')) {
3502 $info[getDolGlobalString('LDAP_FIELD_ADDRESS')] = $this->address;
3503 }
3504 if ($this->zip && getDolGlobalString('LDAP_FIELD_ZIP')) {
3505 $info[getDolGlobalString('LDAP_FIELD_ZIP')] = $this->zip;
3506 }
3507 if ($this->town && getDolGlobalString('LDAP_FIELD_TOWN')) {
3508 $info[getDolGlobalString('LDAP_FIELD_TOWN')] = $this->town;
3509 }
3510 if ($this->note_public && getDolGlobalString('LDAP_FIELD_DESCRIPTION')) {
3511 $info[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_public, 2);
3512 }
3513 if ($this->socid > 0 && getDolGlobalString('LDAP_FIELD_COMPANY')) {
3514 $soc = new Societe($this->db);
3515 $soc->fetch($this->socid);
3516
3517 $info[getDolGlobalString('LDAP_FIELD_COMPANY')] = $soc->name;
3518 if ($soc->client == 1) {
3519 $info["businessCategory"] = "Customers";
3520 }
3521 if ($soc->client == 2) {
3522 $info["businessCategory"] = "Prospects";
3523 }
3524 if ($soc->fournisseur == 1) {
3525 $info["businessCategory"] = "Suppliers";
3526 }
3527 }
3528
3529 // When password is modified
3530 if (!empty($this->pass)) {
3531 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3532 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass; // this->pass = unencrypted password
3533 }
3534 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3535 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3536 }
3537 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3538 // Set LDAP password if possible
3539 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3540 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
3541 // Just for the default MD5 !
3542 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) {
3543 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3544 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3545 }
3546 }
3547 } elseif (!empty($this->pass_indatabase)) {
3548 // Use $this->pass_indatabase value if exists
3549 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3550 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = unencrypted password
3551 }
3552 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3553 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3554 }
3555 }
3556 }
3557
3558 if (getDolGlobalString('LDAP_SERVER_TYPE') == 'egroupware') {
3559 $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3560
3561 $info['uidnumber'] = $this->id;
3562
3563 $info['phpgwTz'] = 0;
3564 $info['phpgwMailType'] = 'INTERNET';
3565 $info['phpgwMailHomeType'] = 'INTERNET';
3566
3567 $info["phpgwContactTypeId"] = 'n';
3568 $info["phpgwContactCatId"] = 0;
3569 $info["phpgwContactAccess"] = "public";
3570
3571 /*
3572 if (dol_strlen($this->egroupware_id) == 0) {
3573 $this->egroupware_id = 1;
3574 }
3575 $info["phpgwContactOwner"] = $this->egroupware_id;
3576 */
3577 $info["phpgwContactOwner"] = 1;
3578
3579 if ($this->email) {
3580 $info["rfc822Mailbox"] = $this->email;
3581 }
3582 if ($this->user_mobile) {
3583 $info["phpgwCellTelephoneNumber"] = $this->user_mobile;
3584 }
3585 }
3586
3587 if (getDolGlobalString('LDAP_FIELD_USERID')) {
3588 $info[getDolGlobalString('LDAP_FIELD_USERID')] = $this->id;
3589 }
3590 if (getDolGlobalString('LDAP_FIELD_GROUPID')) {
3591 $usergroup = new UserGroup($this->db);
3592 $groupslist = $usergroup->listGroupsForUser($this->id);
3593 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = '65534';
3594 if (!empty($groupslist)) {
3595 foreach ($groupslist as $groupforuser) {
3596 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = $groupforuser->id; //Select first group in list
3597 break;
3598 }
3599 }
3600 }
3601 if (getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY') && getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')) {
3602 $info[getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY')] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->login";
3603 }
3604
3605 return $info;
3606 }
3607
3608
3616 public function initAsSpecimen()
3617 {
3618 global $user, $langs;
3619
3620 $now = dol_now();
3621
3622 // Initialise parameters
3623 $this->id = 0;
3624 $this->ref = 'SPECIMEN';
3625 $this->specimen = 1;
3626
3627 $this->lastname = 'DOLIBARR';
3628 $this->firstname = 'SPECIMEN';
3629 $this->gender = 'man';
3630 $this->note_public = 'This is a note public';
3631 $this->note_private = 'This is a note private';
3632 $this->email = 'email@specimen.com';
3633 $this->personal_email = 'personalemail@specimen.com';
3634 $this->socialnetworks = array(
3635 'skype' => 'skypepseudo',
3636 'twitter' => 'twitterpseudo',
3637 'facebook' => 'facebookpseudo',
3638 'linkedin' => 'linkedinpseudo',
3639 );
3640 $this->office_phone = '0999999999';
3641 $this->office_fax = '0999999998';
3642 $this->user_mobile = '0999999997';
3643 $this->personal_mobile = '0999999996';
3644 $this->admin = 0;
3645 $this->login = 'dolibspec';
3646 $this->pass = 'dolibSpec+@123';
3647 //$this->pass_indatabase='dolibspec'; Set after a fetch
3648 //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3649 $this->datec = $now;
3650 $this->datem = $now;
3651
3652 $this->datelastlogin = $now;
3653 $this->iplastlogin = '127.0.0.1';
3654 $this->datepreviouslogin = $now;
3655 $this->ippreviouslogin = '127.0.0.1';
3656 $this->statut = 1; // deprecated
3657 $this->status = 1;
3658
3659 $this->entity = 1;
3660
3661 return 1;
3662 }
3663
3670 public function info($id)
3671 {
3672 $sql = "SELECT u.rowid, u.login as ref, u.datec,";
3673 $sql .= " u.tms as date_modification, u.entity";
3674 $sql .= " FROM ".$this->db->prefix()."user as u";
3675 $sql .= " WHERE u.rowid = ".((int) $id);
3676
3677 $result = $this->db->query($sql);
3678 if ($result) {
3679 if ($this->db->num_rows($result)) {
3680 $obj = $this->db->fetch_object($result);
3681
3682 $this->id = $obj->rowid;
3683
3684 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3685 $this->date_creation = $this->db->jdate($obj->datec);
3686 $this->date_modification = $this->db->jdate($obj->date_modification);
3687 $this->entity = $obj->entity;
3688 }
3689
3690 $this->db->free($result);
3691 } else {
3692 dol_print_error($this->db);
3693 }
3694 }
3695
3696
3702 public function getNbOfEMailings()
3703 {
3704 $sql = "SELECT count(mc.email) as nb";
3705 $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3706 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3707 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
3708
3709 $resql = $this->db->query($sql);
3710 if ($resql) {
3711 $obj = $this->db->fetch_object($resql);
3712 $nb = $obj->nb;
3713
3714 $this->db->free($resql);
3715 return $nb;
3716 } else {
3717 $this->error = $this->db->error();
3718 return -1;
3719 }
3720 }
3721
3730 public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3731 {
3732 global $conf;
3733
3734 $sql = "SELECT count(rowid) as nb";
3735 $sql .= " FROM ".$this->db->prefix()."user";
3736 if ($option == 'superadmin') {
3737 $sql .= " WHERE entity = 0";
3738 } else {
3739 $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3740 if ($limitTo == 'active') {
3741 $sql .= " AND statut = 1";
3742 }
3743 }
3744 if ($admin >= 0) {
3745 $sql .= " AND admin = ".(int) $admin;
3746 }
3747
3748 $resql = $this->db->query($sql);
3749 if ($resql) {
3750 $obj = $this->db->fetch_object($resql);
3751 $nb = (int) $obj->nb;
3752
3753 $this->db->free($resql);
3754 return $nb;
3755 } else {
3756 $this->error = $this->db->lasterror();
3757 return -1;
3758 }
3759 }
3760
3761 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3768 public function update_ldap2dolibarr(&$ldapuser)
3769 {
3770 // phpcs:enable
3771 // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3772 global $user, $conf;
3773
3774 $socialnetworks = getArrayOfSocialNetworks();
3775
3776 $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3777 $this->firstname = $ldapuser->$tmpvar;
3778 $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3779 $this->lastname = $ldapuser->$tmpvar;
3780 $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3781 $this->login = $ldapuser->$tmpvar;
3782 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3783 $this->pass = $ldapuser->$tmpvar;
3784 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3785 $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3786
3787 $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3788 $this->office_phone = $ldapuser->$tmpvar;
3789 $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3790 $this->user_mobile = $ldapuser->$tmpvar;
3791 $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3792 $this->office_fax = $ldapuser->$tmpvar;
3793 $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3794 $this->email = $ldapuser->$tmpvar;
3795 foreach ($socialnetworks as $key => $value) {
3796 $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3797 $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3798 }
3799 $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3800 $this->ldap_sid = $ldapuser->$tmpvar;
3801
3802 $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3803 $this->job = $ldapuser->$tmpvar;
3804 $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3805 $this->note_public = $ldapuser->$tmpvar;
3806
3807 $result = $this->update($user);
3808
3809 dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3810
3811 return $result;
3812 }
3813
3814
3815 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3822 public function get_children()
3823 {
3824 // phpcs:enable
3825 $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3826 $sql .= " WHERE fk_user = ".((int) $this->id);
3827
3828 dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3829 $res = $this->db->query($sql);
3830 if ($res) {
3831 $users = array();
3832 while ($rec = $this->db->fetch_array($res)) {
3833 $user = new User($this->db);
3834 $user->fetch($rec['rowid']);
3835 $users[] = $user;
3836 }
3837 return $users;
3838 } else {
3839 dol_print_error($this->db);
3840 return -1;
3841 }
3842 }
3843
3844
3850 private function loadParentOf()
3851 {
3852 global $conf;
3853
3854 $this->parentof = array();
3855
3856 // Load array[child]=parent
3857 $sql = "SELECT fk_user as id_parent, rowid as id_son";
3858 $sql .= " FROM ".$this->db->prefix()."user";
3859 $sql .= " WHERE fk_user <> 0";
3860 $sql .= " AND entity IN (".getEntity('user').")";
3861
3862 dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3863 $resql = $this->db->query($sql);
3864 if ($resql) {
3865 while ($obj = $this->db->fetch_object($resql)) {
3866 $this->parentof[$obj->id_son] = $obj->id_parent;
3867 }
3868 return 1;
3869 } else {
3870 dol_print_error($this->db);
3871 return -1;
3872 }
3873 }
3874
3875 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3889 public function get_full_tree($deleteafterid = 0, $filter = '')
3890 {
3891 // phpcs:enable
3892 global $hookmanager;
3893
3894 // Actions hooked (by external module)
3895 $hookmanager->initHooks(array('userdao'));
3896
3897 $this->users = array();
3898
3899 // Init this->parentof that is array(id_son=>id_parent, ...)
3900 $this->loadParentOf();
3901
3902 // Init $this->users array
3903 $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
3904 $sql .= " FROM ".$this->db->prefix()."user as u";
3905 // Add fields from hooks
3906 $parameters = array();
3907 $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3908 if ($reshook > 0) {
3909 $sql .= $hookmanager->resPrint;
3910 } else {
3911 $sql .= " WHERE u.entity IN (".getEntity('user').")";
3912 }
3913 if ($filter) {
3914 $sql .= " AND ".$filter; // already sanitized
3915 }
3916
3917 dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3918 $resql = $this->db->query($sql);
3919 if ($resql) {
3920 $i = 0;
3921 while ($obj = $this->db->fetch_object($resql)) {
3922 $this->users[$obj->rowid]['rowid'] = $obj->rowid;
3923 $this->users[$obj->rowid]['id'] = $obj->rowid;
3924 $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
3925 $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
3926 $this->users[$obj->rowid]['firstname'] = $obj->firstname;
3927 $this->users[$obj->rowid]['lastname'] = $obj->lastname;
3928 $this->users[$obj->rowid]['login'] = $obj->login;
3929 $this->users[$obj->rowid]['statut'] = $obj->statut;
3930 $this->users[$obj->rowid]['entity'] = $obj->entity;
3931 $this->users[$obj->rowid]['email'] = $obj->email;
3932 $this->users[$obj->rowid]['gender'] = $obj->gender;
3933 $this->users[$obj->rowid]['admin'] = $obj->admin;
3934 $this->users[$obj->rowid]['photo'] = $obj->photo;
3935 // fields are filled with build_path_from_id_user
3936 $this->users[$obj->rowid]['fullpath'] = '';
3937 $this->users[$obj->rowid]['fullname'] = '';
3938 $this->users[$obj->rowid]['level'] = 0;
3939 $i++;
3940 }
3941 } else {
3942 dol_print_error($this->db);
3943 return -1;
3944 }
3945
3946 // We add the fullpath property to each element of the first level (no parent exists)
3947 dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3948 foreach ($this->users as $key => $val) {
3949 $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3950 if ($result < 0) {
3951 $this->error = 'ErrorLoopInHierarchy';
3952 return -1;
3953 }
3954 }
3955
3956 // Exclude leaf including $deleteafterid from tree
3957 if ($deleteafterid) {
3958 //print "Look to discard user ".$deleteafterid."\n";
3959 $keyfilter1 = '^'.$deleteafterid.'$';
3960 $keyfilter2 = '_'.$deleteafterid.'$';
3961 $keyfilter3 = '^'.$deleteafterid.'_';
3962 $keyfilter4 = '_'.$deleteafterid.'_';
3963 foreach (array_keys($this->users) as $key) {
3964 $fullpath = (string) $this->users[$key]['fullpath'];
3965 if (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
3966 || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath)) {
3967 unset($this->users[$key]);
3968 }
3969 }
3970 }
3971
3972 dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
3973 $this->users = dol_sort_array($this->users, 'fullname', 'asc', 1, 0, 1);
3974
3975 //var_dump($this->users);
3976
3977 return $this->users;
3978 }
3979
3988 public function getAllChildIds($addcurrentuser = 0)
3989 {
3990 $childids = array();
3991
3992 if (isset($this->cache_childids[$this->id])) {
3993 $childids = $this->cache_childids[$this->id];
3994 } else {
3995 // Init this->users
3996 $treeresult = $this->get_full_tree();
3997
3998 $idtoscan = $this->id;
3999
4000 dol_syslog("Build childid for id = ".$idtoscan);
4001 foreach ($this->users as $id => $val) {
4002 //var_dump($val['fullpath']);
4003 if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
4004 $childids[$val['id']] = $val['id'];
4005 }
4006 }
4007
4008 // A loop anywhere in the hierarchy aborts get_full_tree(), leaving the branches it had not
4009 // walked yet with an empty fullpath, so they silently drop out of the list above. Do not
4010 // cache such a truncated result, it would be reused for the whole request.
4011 if ($treeresult < 0) {
4012 dol_syslog(get_class($this)."::getAllChildIds got a truncated tree: ".$this->error, LOG_WARNING);
4013 return $addcurrentuser ? array($this->id => $this->id) : $childids;
4014 }
4015 }
4016 $this->cache_childids[$this->id] = $childids;
4017
4018 if ($addcurrentuser) {
4019 $childids[$this->id] = $this->id;
4020 }
4021
4022 return $childids;
4023 }
4024
4025 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4034 public function build_path_from_id_user($id_user, $protection = 0)
4035 {
4036 // phpcs:enable
4037 //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
4038
4039 if (!empty($this->users[$id_user]['fullpath'])) {
4040 // Already defined
4041 dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
4042 return 0;
4043 }
4044
4045 // Define fullpath and fullname
4046 $this->users[$id_user]['fullpath'] = '_'.$id_user;
4047 $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
4048 $i = 0;
4049 $cursor_user = $id_user;
4050
4051 $useridfound = array($id_user);
4052 while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) { // @phan-suppress-current-line PhanTypeMismatchProperty
4053 if (in_array($this->parentof[$cursor_user], $useridfound)) {
4054 dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
4055 return -1; // Should not happen. Protection against looping hierarchy
4056 }
4057 $useridfound[] = $this->parentof[$cursor_user];
4058 $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
4059 $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
4060 $i++;
4061 $cursor_user = $this->parentof[$cursor_user];
4062 }
4063
4064 // We count number of _ to have level
4065 $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
4066
4067 return 1;
4068 }
4069
4078 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4079 {
4080 $tables = array(
4081 'user',
4082 );
4083
4084 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4085 }
4086
4087
4093 public function loadStateBoard()
4094 {
4095 global $conf;
4096
4097 $this->nb = array();
4098
4099 $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
4100 $sql .= " FROM ".$this->db->prefix()."user as u";
4101 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4102 $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
4103 $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
4104 $sql .= " AND ug.fk_user = u.rowid";
4105 } else {
4106 $sql .= " WHERE u.entity IN (".getEntity('user').")";
4107 }
4108 $sql .= " AND u.statut > 0";
4109 //$sql.= " AND employee != 0";
4110
4111 $resql = $this->db->query($sql);
4112 if ($resql) {
4113 while ($obj = $this->db->fetch_object($resql)) {
4114 $this->nb["users"] = $obj->nb;
4115 }
4116 $this->db->free($resql);
4117 return 1;
4118 } else {
4119 dol_print_error($this->db);
4120 $this->error = $this->db->error();
4121 return -1;
4122 }
4123 }
4124
4136 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4137 {
4138 global $conf, $user, $langs;
4139
4140 $langs->load("user");
4141
4142 // Set the '$modele' to the name of the document template (model) to use
4143 if (!dol_strlen($modele)) {
4144 if (getDolGlobalString('USER_ADDON_PDF')) {
4145 $modele = getDolGlobalString('USER_ADDON_PDF');
4146 } else {
4147 $modele = 'bluesky';
4148 }
4149 }
4150
4151 $modelpath = "core/modules/user/doc/";
4152
4153 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4154 }
4155
4156 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4164 public function user_get_property($rowid, $mode)
4165 {
4166 // phpcs:enable
4167 $user_property = '';
4168
4169 if (empty($rowid)) {
4170 return '';
4171 }
4172
4173 $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
4174 $sql .= " FROM ".$this->db->prefix()."user";
4175 $sql .= " WHERE rowid = ".((int) $rowid);
4176
4177 $resql = $this->db->query($sql);
4178 if ($resql) {
4179 $nump = $this->db->num_rows($resql);
4180
4181 if ($nump) {
4182 $obj = $this->db->fetch_object($resql);
4183
4184 if ($mode == 'email') {
4185 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
4186 } elseif ($mode == 'mobile') {
4187 $user_property = $obj->user_mobile;
4188 } elseif ($mode == 'name') {
4189 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname);
4190 }
4191 }
4192 return $user_property;
4193 } else {
4194 dol_print_error($this->db);
4195 }
4196
4197 return '';
4198 }
4199
4207 public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
4208 {
4210 global $conf;
4211
4212 $encodedsecurekey = dol_hash($conf->file->instance_unique_id.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
4213 if (isModEnabled('multicompany')) {
4214 $entity_qr = '&entity='.((int) $conf->entity);
4215 } else {
4216 $entity_qr = '';
4217 }
4218 // Define $urlwithroot
4219 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
4220 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
4221 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
4222
4223 if ($typeofurl == 'internal') {
4224 $urlwithroot = DOL_URL_ROOT;
4225 }
4226
4227 return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
4228 }
4229
4243 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND', $entityfilter = false)
4244 {
4245 global $conf, $user;
4246
4247 $sql = "SELECT t.rowid";
4248 $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
4249
4250 if ($entityfilter) {
4251 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4252 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
4253 $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
4254 } else {
4255 $sql .= " WHERE t.entity = 0 OR EXISTS (";
4256 $sql .= " SELECT ug.rowid FROM " . $this->db->prefix() . "usergroup_user as ug";
4257 $sql .= " WHERE ug.fk_user = t.rowid AND ug.entity IN (" . getEntity('usergroup') . "))";
4258 }
4259 } else {
4260 $sql .= " WHERE t.entity IN (".getEntity('user').")";
4261 }
4262 } else {
4263 $sql .= " WHERE 1 = 1";
4264 }
4265
4266 // Manage filter
4267 $errormessage = '';
4268 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
4269 if ($errormessage) {
4270 $this->errors[] = $errormessage;
4271 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
4272 return -1;
4273 }
4274
4275 $sql .= $this->db->order($sortfield, $sortorder);
4276 if ($limit) {
4277 $sql .= $this->db->plimit($limit + 1, $offset);
4278 }
4279
4280 dol_syslog(__METHOD__, LOG_DEBUG);
4281
4282 $resql = $this->db->query($sql);
4283 if ($resql) {
4284 $this->users = array();
4285 $num = $this->db->num_rows($resql);
4286 if ($num) {
4287 while ($obj = $this->db->fetch_object($resql)) {
4288 $line = new self($this->db);
4289 $result = $line->fetch($obj->rowid);
4290 if ($result > 0 && !empty($line->id)) {
4291 $this->users[$obj->rowid] = clone $line;
4292 }
4293 }
4294 $this->db->free($resql);
4295 }
4296 return $num;
4297 } else {
4298 $this->errors[] = $this->db->lasterror();
4299 return -1;
4300 }
4301 }
4302
4310 private $findUserIdByEmailCache;
4311
4322 public function findUserIdByEmail($email)
4323 {
4324 if (isset($this->findUserIdByEmailCache[$email])) {
4325 return $this->findUserIdByEmailCache[$email];
4326 }
4327
4328 $this->findUserIdByEmailCache[$email] = -1;
4329
4330 $sql = 'SELECT rowid';
4331 $sql .= ' FROM '.$this->db->prefix().'user';
4332 if (getDolGlobalString('AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR')) {
4333 $sql .= " WHERE email LIKE '%".$this->db->escape($this->db->escapeforlike($email))."%'";
4334 } else {
4335 $sql .= " WHERE email = '".$this->db->escape($email)."'";
4336 }
4337 $sql .= ' LIMIT 1';
4338
4339 $resql = $this->db->query($sql);
4340 if (!$resql) {
4341 return -1;
4342 }
4343
4344 $obj = $this->db->fetch_object($resql);
4345 if (!$obj) {
4346 return -1;
4347 }
4348
4349 $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4350
4351 return $this->findUserIdByEmailCache[$email];
4352 }
4353
4360 public function cloneRights($fromId, $toId)
4361 {
4362 if (empty($fromId) || empty($toId)) {
4363 return -1;
4364 }
4365
4366 $this->db->begin();
4367
4368 // delete default rights for UserTo
4369 $sqlDelete = "DELETE FROM ".$this->db->prefix()."user_rights";
4370 $sqlDelete .= " WHERE fk_user = ".((int) $toId);
4371
4372 dol_syslog(get_class($this)."::clone_rights (delete default permissions)", LOG_DEBUG);
4373
4374 if (!$this->db->query($sqlDelete)) {
4375 $this->db->rollback();
4376 return -1;
4377 }
4378
4379 // Construction of the insertion request
4380 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id)";
4381 $sql .= " SELECT entity, ".((int) $toId).", fk_id";
4382 $sql .= " FROM ".$this->db->prefix()."user_rights src";
4383 $sql .= " WHERE fk_user = ".((int) $fromId);
4384 $sql .= " AND NOT EXISTS (";
4385 $sql .= " SELECT 1";
4386 $sql .= " FROM ".$this->db->prefix()."user_rights dest";
4387 $sql .= " WHERE dest.entity = src.entity";
4388 $sql .= " AND dest.fk_user = ".((int) $toId);
4389 $sql .= " AND dest.fk_id = src.fk_id";
4390 $sql .= " )";
4391
4392 dol_syslog(get_class($this)."::clone_rights", LOG_DEBUG);
4393
4394 // Execute request
4395 if (!$this->db->query($sql)) {
4396 $this->db->rollback();
4397 return -1;
4398 }
4399
4400 $this->db->commit();
4401 return 1;
4402 }
4403
4412 public function cloneCategories($fromId, $toId, $type = 'user')
4413 {
4414 $this->db->begin();
4415
4416 if (empty($type)) {
4417 $type = $this->table_element;
4418 }
4419
4420 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4421 $categorystatic = new Categorie($this->db);
4422
4423 $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_user)";
4424 $sql .= " SELECT fk_categorie, ".((int) $toId)." FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
4425 $sql .= " WHERE fk_user = ".((int) $fromId);
4426
4427 if (!$this->db->query($sql)) {
4428 $this->error = $this->db->lasterror();
4429 $this->db->rollback();
4430 return -1;
4431 }
4432
4433 $this->db->commit();
4434 return 1;
4435 }
4436}
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:427
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.