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 // A user that still has HRM data (competency assessments, job positions, skills) must not be deleted
1673 if (isModEnabled('hrm')) {
1674 global $langs;
1675
1676 $hrmtables = array(
1677 'hrm_evaluation' => array('label' => 'EvaluationCard', 'filter' => "fk_user = ".((int) $this->id)),
1678 'hrm_job_user' => array('label' => 'EmployeePosition', 'filter' => "fk_user = ".((int) $this->id)),
1679 'hrm_skillrank' => array('label' => 'Skill', 'filter' => "objecttype = 'user' AND fk_object = ".((int) $this->id)),
1680 );
1681 foreach ($hrmtables as $hrmtable => $hrminfo) {
1682 $sanitizedfilter = $hrminfo['filter']; // Built above from the id of the user only
1683 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->db->sanitize($hrmtable)." WHERE ".$sanitizedfilter;
1684 $resql = $this->db->query($sql);
1685 if ($resql) {
1686 $obj = $this->db->fetch_object($resql);
1687 if ($obj && $obj->nb > 0) {
1688 $langs->loadLangs(array('errors', 'hrm'));
1689 $this->error = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $this->login, $langs->transnoentitiesnoconv($hrminfo['label']));
1690 $this->errors[] = $this->error;
1691 $this->db->rollback();
1692 return -1;
1693 }
1694 }
1695 }
1696 }
1697
1698 // Remove rights
1699 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1700
1701 if (!$error && !$this->db->query($sql)) {
1702 $error++;
1703 $this->error = $this->db->lasterror();
1704 }
1705
1706 // Remove group
1707 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1708 if (!$error && !$this->db->query($sql)) {
1709 $error++;
1710 $this->error = $this->db->lasterror();
1711 }
1712
1713 // Remove params
1714 $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1715 if (!$error && !$this->db->query($sql)) {
1716 $error++;
1717 $this->error = $this->db->lasterror();
1718 }
1719
1720 // Remove the private bookmarks of the user (the public ones have no owner and are kept)
1721 $sql = "DELETE FROM ".$this->db->prefix()."bookmark WHERE fk_user = ".((int) $this->id);
1722 if (!$error && !$this->db->query($sql)) {
1723 $error++;
1724 $this->error = $this->db->lasterror();
1725 }
1726
1727 // If contact, remove link
1728 if ($this->contact_id > 0) {
1729 $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1730 if (!$error && !$this->db->query($sql)) {
1731 $error++;
1732 $this->error = $this->db->lasterror();
1733 }
1734 }
1735
1736 // Remove extrafields
1737 if (!$error) {
1738 $result = $this->deleteExtraFields();
1739 if ($result < 0) {
1740 $error++;
1741 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1742 }
1743 }
1744
1745 // Remove user
1746 if (!$error) {
1747 $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1748 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1749 if (!$this->db->query($sql)) {
1750 $error++;
1751 $this->error = $this->db->lasterror();
1752 }
1753 }
1754
1755 if (!$error) {
1756 // Call trigger
1757 $result = $this->call_trigger('USER_DELETE', $user);
1758 if ($result < 0) {
1759 $error++;
1760 $this->db->rollback();
1761 return -1;
1762 }
1763 // End call triggers
1764
1765 $this->db->commit();
1766 return 1;
1767 } else {
1768 $this->db->rollback();
1769 return -1;
1770 }
1771 }
1772
1780 public function create($user, $notrigger = 0)
1781 {
1782 global $conf, $langs;
1783 global $mysoc;
1784
1785 // Clean parameters
1786 $this->setUpperOrLowerCase();
1787
1788 $this->civility_code = trim((string) $this->civility_code);
1789 $this->login = trim((string) $this->login);
1790 if (!isset($this->entity)) {
1791 $this->entity = $conf->entity; // If not defined, we use default value
1792 }
1793 dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1794
1795 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1796
1797 // Check parameters
1798 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
1799 $langs->load("errors");
1800 $this->error = $langs->trans("ErrorBadEMail", $this->email);
1801 return -1;
1802 }
1803 if (empty($this->login)) {
1804 $langs->load("errors");
1805 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1806 return -1;
1807 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1808 $langs->load("errors");
1809 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1810 return -1;
1811 }
1812
1813 $this->datec = dol_now();
1814
1815 $error = 0;
1816 $this->db->begin();
1817
1818 // Check if login already exists in same entity or into entity 0.
1819 if ($this->login) {
1820 $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)."'";
1821 $resqltochecklogin = $this->db->query($sqltochecklogin);
1822 if ($resqltochecklogin) {
1823 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1824 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1825 $langs->load("errors");
1826 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1827 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1828 $this->db->rollback();
1829 return -6;
1830 }
1831 $this->db->free($resqltochecklogin);
1832 }
1833 }
1834 if (!empty($this->email)) {
1835 $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)."'";
1836 $resqltochecklogin = $this->db->query($sqltochecklogin);
1837 if ($resqltochecklogin) {
1838 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1839 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1840 $langs->load("errors");
1841 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1842 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1843 $this->db->rollback();
1844 return -6;
1845 }
1846 $this->db->free($resqltochecklogin);
1847 }
1848 }
1849
1850 // Insert into database
1851 $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, entity)";
1852 $sql .= " VALUES('".$this->db->idate($this->datec)."', '".$this->db->escape($this->login)."', '".$this->db->escape($this->ldap_sid)."', ".((int) $this->entity).")";
1853 $result = $this->db->query($sql);
1854
1855 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1856 if ($result) {
1857 $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1858
1859 // Set default rights
1860 if ($this->set_default_rights() < 0) {
1861 $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1862 $this->db->rollback();
1863 return -5;
1864 }
1865
1866 if (getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && getDolGlobalString('STOCK_USERSTOCK_AUTOCREATE')) {
1867 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1868 $langs->load("stocks");
1869
1870 $entrepot = new Entrepot($this->db);
1871 $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1872 $entrepot->libelle = $entrepot->label; // For backward compatibility
1873 $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1874 $entrepot->statut = 1;
1875 $entrepot->country_id = $mysoc->country_id;
1876
1877 $warehouseid = $entrepot->create($user);
1878
1879 $this->fk_warehouse = $warehouseid;
1880 }
1881
1882 // Update minor fields
1883 $result = $this->update($user, 1, 1);
1884 if ($result < 0) {
1885 $this->db->rollback();
1886 return -4;
1887 }
1888
1889 if (!$notrigger) {
1890 // Call trigger
1891 $result = $this->call_trigger('USER_CREATE', $user);
1892 if ($result < 0) {
1893 $error++;
1894 }
1895 // End call triggers
1896 }
1897
1898 if (!$error) {
1899 $this->db->commit();
1900 return $this->id;
1901 } else {
1902 //$this->error=$interface->error;
1903 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1904 $this->db->rollback();
1905 return -3;
1906 }
1907 } else {
1908 $this->error = $this->db->lasterror();
1909 $this->db->rollback();
1910 return -2;
1911 }
1912 }
1913
1914
1915 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1924 public function create_from_contact($contact, $login = '', $password = '')
1925 {
1926 // phpcs:enable
1927 global $conf, $user, $langs;
1928
1929 $error = 0;
1930
1931 // Define parameters
1932 $this->admin = 0;
1933 $this->civility_code = $contact->civility_code;
1934 $this->lastname = $contact->lastname;
1935 $this->firstname = $contact->firstname;
1936 //$this->gender = $contact->gender; // contact has no gender
1937 $this->email = $contact->email;
1938 $this->socialnetworks = $contact->socialnetworks;
1939 $this->office_phone = $contact->phone_pro;
1940 $this->office_fax = $contact->fax;
1941 $this->user_mobile = $contact->phone_mobile;
1942 $this->address = $contact->address;
1943 $this->zip = $contact->zip;
1944 $this->town = $contact->town;
1945 $this->setUpperOrLowerCase();
1946 $this->state_id = $contact->state_id;
1947 $this->country_id = $contact->country_id;
1948 $this->employee = 0;
1949
1950 if (empty($login)) {
1951 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1952 $login = dol_buildlogin($contact->lastname, $contact->firstname);
1953 }
1954 $this->login = $login;
1955
1956 $this->db->begin();
1957
1958 // Create user and set $this->id. Trigger is disabled because executed later.
1959 $result = $this->create($user, 1);
1960 if ($result > 0) {
1961 $sql = "UPDATE ".$this->db->prefix()."user";
1962 $sql .= " SET fk_socpeople=".((int) $contact->id);
1963 $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
1964 if ($contact->socid > 0) {
1965 $sql .= ", fk_soc=".((int) $contact->socid);
1966 }
1967 $sql .= " WHERE rowid=".((int) $this->id);
1968
1969 $resql = $this->db->query($sql);
1970
1971 dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1972 if ($resql) {
1973 $this->context['createfromcontact'] = 'createfromcontact';
1974
1975 // Call trigger
1976 $result = $this->call_trigger('USER_CREATE', $user);
1977 if ($result < 0) {
1978 $error++;
1979 $this->db->rollback();
1980 return -1;
1981 }
1982 // End call triggers
1983
1984 $this->db->commit();
1985 return $this->id;
1986 } else {
1987 $this->error = $this->db->error();
1988
1989 $this->db->rollback();
1990 return -1;
1991 }
1992 } else {
1993 // $this->error deja positionne
1994 dol_syslog(get_class($this)."::create_from_contact - 0");
1995
1996 $this->db->rollback();
1997 return $result;
1998 }
1999 }
2000
2001 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2010 public function create_from_member($member, $login = '')
2011 {
2012 // phpcs:enable
2013 global $user;
2014
2015 // Set properties on new user
2016 $this->admin = 0;
2017 $this->civility_code = $member->civility_code;
2018 $this->lastname = $member->lastname;
2019 $this->firstname = $member->firstname;
2020 $this->gender = $member->gender;
2021 $this->email = $member->email;
2022 $this->fk_member = $member->id;
2023 $this->address = $member->address;
2024 $this->zip = $member->zip;
2025 $this->town = $member->town;
2026 $this->setUpperOrLowerCase();
2027 $this->state_id = $member->state_id;
2028 $this->country_id = $member->country_id;
2029 $this->socialnetworks = $member->socialnetworks;
2030
2031 $this->pass = $member->pass;
2032 $this->pass_crypted = $member->pass_indatabase_crypted;
2033
2034 if (empty($login)) {
2035 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2036 $login = dol_buildlogin($member->lastname, $member->firstname);
2037 }
2038 $this->login = $login;
2039
2040 $this->db->begin();
2041
2042 // Create and set $this->id
2043 $result = $this->create($user);
2044 if ($result > 0) {
2045 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
2046 $newpass = $this->setPassword($user, $this->pass);
2047 if (is_int($newpass) && $newpass < 0) {
2048 $result = -2;
2049 }
2050 } 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.
2051 $sql = "UPDATE ".$this->db->prefix()."user";
2052 $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
2053 $sql .= " WHERE rowid=".((int) $this->id);
2054
2055 $resql = $this->db->query($sql);
2056 if (!$resql) {
2057 $result = -1;
2058 }
2059 }
2060
2061 if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
2062 $sql = "UPDATE ".$this->db->prefix()."user";
2063 $sql .= " SET fk_soc=".((int) $member->socid);
2064 $sql .= " WHERE rowid=".((int) $this->id);
2065
2066 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
2067 $resql = $this->db->query($sql);
2068 if ($resql) {
2069 $this->db->commit();
2070 return $this->id;
2071 } else {
2072 $this->error = $this->db->lasterror();
2073
2074 $this->db->rollback();
2075 return -1;
2076 }
2077 }
2078 }
2079
2080 if ($result > 0) {
2081 $this->db->commit();
2082 return $this->id;
2083 } else {
2084 // $this->error was already set
2085 $this->db->rollback();
2086 return -2;
2087 }
2088 }
2089
2090 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2096 public function set_default_rights()
2097 {
2098 // phpcs:enable
2099 global $conf;
2100
2101 $rd = array();
2102 $num = 0;
2103 $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
2104 $sql .= " WHERE bydefault = 1";
2105 $sql .= " AND entity = ".((int) $conf->entity);
2106
2107 $resql = $this->db->query($sql);
2108 if ($resql) {
2109 $num = $this->db->num_rows($resql);
2110 $i = 0;
2111 while ($i < $num) {
2112 $row = $this->db->fetch_row($resql);
2113 $rd[$i] = $row[0];
2114 $i++;
2115 }
2116 $this->db->free($resql);
2117 }
2118 $i = 0;
2119 while ($i < $num) {
2120 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
2121 $result = $this->db->query($sql);
2122
2123 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
2124 $result = $this->db->query($sql);
2125 if (!$result) {
2126 return -1;
2127 }
2128 $i++;
2129 }
2130
2131 return $i;
2132 }
2133
2144 public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
2145 {
2146 global $conf, $langs;
2147
2148 if (empty($this->country_id) && !empty($this->country_code)) {
2149 $country_id = getCountry($this->country_code, '3');
2150 $this->country_id = is_int($country_id) ? $country_id : 0;
2151 }
2152
2153 $nbrowsaffected = 0;
2154 $error = 0;
2155
2156 dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
2157
2158 // Clean parameters
2159 $this->civility_code = trim((string) $this->civility_code);
2160 $this->lastname = trim((string) $this->lastname);
2161 $this->firstname = trim((string) $this->firstname);
2162 $this->ref_employee = trim((string) $this->ref_employee);
2163 $this->national_registration_number = trim((string) $this->national_registration_number);
2164 $this->employee = ($this->employee > 0 ? $this->employee : 0);
2165 $this->login = trim((string) $this->login);
2166 $this->gender = trim((string) $this->gender);
2167
2168 $this->pass = trim((string) $this->pass);
2169 $this->api_key = trim((string) $this->api_key);
2170 $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
2171 $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
2172
2173 $this->address = trim((string) $this->address);
2174 $this->zip = trim((string) $this->zip);
2175 $this->town = trim((string) $this->town);
2176
2177 $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
2178 $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
2179 $this->office_phone = trim((string) $this->office_phone);
2180 $this->office_fax = trim((string) $this->office_fax);
2181 $this->user_mobile = trim((string) $this->user_mobile);
2182 $this->personal_mobile = trim((string) $this->personal_mobile);
2183 $this->email = trim((string) $this->email);
2184 $this->personal_email = trim((string) $this->personal_email);
2185
2186 $this->job = trim((string) $this->job);
2187 $this->signature = trim((string) $this->signature);
2188 $this->note_public = trim((string) $this->note_public);
2189 $this->note_private = trim((string) $this->note_private);
2190 $this->openid = trim((string) $this->openid);
2191 $this->admin = ($this->admin > 0 ? $this->admin : 0);
2192
2193 $this->accountancy_code_user_general = trim((string) $this->accountancy_code_user_general);
2194 $this->accountancy_code = trim((string) $this->accountancy_code);
2195 $this->color = trim(str_replace('#', '', (string) $this->color));
2196 $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
2197 $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
2198
2199 $this->birth = empty($this->birth) ? '' : $this->birth;
2200 $this->fk_warehouse = (int) $this->fk_warehouse;
2201 $this->fk_establishment = (int) $this->fk_establishment;
2202
2203 $this->setUpperOrLowerCase();
2204
2205 // Check parameters
2206 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
2207
2208 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
2209 $langs->load("errors");
2210 $this->error = $langs->trans("ErrorBadEMail", $this->email);
2211 return -1;
2212 }
2213 if (empty($this->login)) {
2214 $langs->load("errors");
2215 $this->error = $langs->trans("ErrorFieldRequired", 'Login');
2216 return -1;
2217 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
2218 $langs->load("errors");
2219 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
2220 return -1;
2221 }
2222
2223 $this->db->begin();
2224
2225 // Check if login already exists in same entity or into entity 0.
2226 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->oldcopy->login != $this->login) {
2227 $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)."'";
2228 $resqltochecklogin = $this->db->query($sqltochecklogin);
2229 if ($resqltochecklogin) {
2230 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2231 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2232 $langs->load("errors");
2233 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
2234 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2235 $this->db->rollback();
2236 return -1;
2237 }
2238 }
2239 }
2240 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && !empty($this->email) && $this->oldcopy->email != $this->email) {
2241 $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)."'";
2242 $resqltochecklogin = $this->db->query($sqltochecklogin);
2243 if ($resqltochecklogin) {
2244 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2245 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2246 $langs->load("errors");
2247 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
2248 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2249 $this->db->rollback();
2250 return -1;
2251 }
2252 }
2253 }
2254
2255 // Update data
2256 $sql = "UPDATE ".$this->db->prefix()."user SET";
2257 $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
2258 $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
2259 $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
2260 $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
2261 $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
2262 $sql .= ", employee = ".(int) $this->employee;
2263 $sql .= ", login = '".$this->db->escape($this->login)."'";
2264 $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
2265 $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' or 'other'
2266 $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
2267 if (!empty($user->admin)) {
2268 $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
2269 }
2270 $sql .= ", address = '".$this->db->escape($this->address)."'";
2271 $sql .= ", zip = '".$this->db->escape($this->zip)."'";
2272 $sql .= ", town = '".$this->db->escape($this->town)."'";
2273 $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".((int) $this->state_id)."'" : "null");
2274 $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".((int) $this->country_id)."'" : "null");
2275 $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
2276 $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
2277 $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
2278 $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
2279 $sql .= ", email = '".$this->db->escape($this->email)."'";
2280 $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
2281 $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
2282 $sql .= ", job = '".$this->db->escape($this->job)."'";
2283 $sql .= ", signature = '".$this->db->escape($this->signature)."'";
2284 $sql .= ", accountancy_code_user_general = '".$this->db->escape($this->accountancy_code_user_general)."'";
2285 $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
2286 $sql .= ", color = '".$this->db->escape($this->color)."'";
2287 $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
2288 $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
2289 $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2290 $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2291 $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2292 $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2293 $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2294 $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2295 $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".((int) $this->fk_user)."'" : "null");
2296 $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".((int) $this->fk_user_expense_validator)."'" : "null");
2297 $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".((int) $this->fk_user_holiday_validator)."'" : "null");
2298 if (isset($this->thm) || $this->thm != '') {
2299 $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2300 }
2301 if (isset($this->tjm) || $this->tjm != '') {
2302 $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2303 }
2304 if (isset($this->salary) || $this->salary != '') {
2305 $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2306 }
2307 if (isset($this->salaryextra) || $this->salaryextra != '') {
2308 $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2309 }
2310 $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2311 if (isModEnabled('multicompany') && !empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2312 // entity flag can be set/unset only by another superadmin user, and only when multicompany is enabled.
2313 // Without multicompany, entity must never be written here: fetch() forces an admin's entity to 0 in memory
2314 // (an admin is a global admin without multicompany), and persisting that would wrongly turn the user into
2315 // a "whole database" (entity 0) admin.
2316 $sql .= ", entity = ".((int) $this->entity);
2317 }
2318 $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
2319 $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
2320 $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
2321 $sql .= ", fk_establishment = ".($this->fk_establishment > 0 ? $this->fk_establishment : "null");
2322 $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2323 $sql .= " WHERE rowid = ".((int) $this->id);
2324
2325 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2326 $resql = $this->db->query($sql);
2327 if ($resql) {
2328 $nbrowsaffected += $this->db->affected_rows($resql);
2329
2330 // Update password
2331 if (!empty($this->pass)) {
2332 if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2333 // If a new value for password is set and different than the one encrypted into database
2334 $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2335 if (is_int($result) && $result < 0) {
2336 return -5;
2337 }
2338 }
2339 }
2340
2341 // If user is linked to a member, remove old link to this member
2342 if ($this->fk_member > 0) {
2343 dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2344 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2345 $resql = $this->db->query($sql);
2346 if (!$resql) {
2347 $this->error = $this->db->error();
2348 $this->db->rollback();
2349 return -5;
2350 }
2351 }
2352 // Set link to user
2353 dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2354 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2355 $resql = $this->db->query($sql);
2356 if (!$resql) {
2357 $this->error = $this->db->error();
2358 $this->db->rollback();
2359 return -5;
2360 }
2361
2362 if ($nbrowsaffected) { // If something has changed in data
2363 if ($this->fk_member > 0 && !$nosyncmember) {
2364 dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2365
2366 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2367
2368 // This user is linked with a member, so we also update member information
2369 // if this is an update.
2370 $adh = new Adherent($this->db);
2371 $result = $adh->fetch($this->fk_member);
2372
2373 if ($result > 0) {
2374 $adh->civility_code = $this->civility_code;
2375 $adh->firstname = $this->firstname;
2376 $adh->lastname = $this->lastname;
2377 $adh->login = $this->login;
2378 $adh->gender = $this->gender;
2379 $adh->birth = $this->birth;
2380
2381 $adh->pass = $this->pass;
2382
2383 $adh->address = $this->address;
2384 $adh->town = $this->town;
2385 $adh->zip = $this->zip;
2386 $adh->state_id = $this->state_id;
2387 $adh->country_id = $this->country_id;
2388
2389 $adh->email = $this->email;
2390
2391 $adh->socialnetworks = $this->socialnetworks;
2392
2393 $adh->phone = $this->office_phone;
2394 $adh->phone_mobile = $this->user_mobile;
2395
2396 $adh->default_lang = $this->lang;
2397
2398 $adh->user_id = $this->id;
2399 $adh->user_login = $this->login;
2400
2401 $result = $adh->update($user, 0, 1, 0);
2402 if ($result < 0) {
2403 $this->error = $adh->error;
2404 $this->errors = $adh->errors;
2405 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2406 $error++;
2407 }
2408 } elseif ($result < 0) {
2409 $this->error = $adh->error;
2410 $this->errors = $adh->errors;
2411 $error++;
2412 }
2413 }
2414
2415 if ($this->contact_id > 0 && !$nosynccontact) {
2416 dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2417
2418 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2419
2420 // This user is linked with a contact, so we also update contact information if this is an update.
2421 $tmpobj = new Contact($this->db);
2422 $result = $tmpobj->fetch($this->contact_id);
2423
2424 if ($result > 0) {
2425 $tmpobj->civility_code = $this->civility_code;
2426 $tmpobj->firstname = $this->firstname;
2427 $tmpobj->lastname = $this->lastname;
2428 $tmpobj->login = $this->login;
2429 $tmpobj->gender = $this->gender;
2430 $tmpobj->birth = $this->birth;
2431
2432 //$tmpobj->pass=$this->pass;
2433
2434 $tmpobj->email = $this->email;
2435
2436 $tmpobj->socialnetworks = $this->socialnetworks;
2437
2438 $tmpobj->phone_pro = $this->office_phone;
2439 $tmpobj->phone_mobile = $this->user_mobile;
2440 $tmpobj->fax = $this->office_fax;
2441
2442 $tmpobj->default_lang = $this->lang;
2443
2444 $tmpobj->address = $this->address;
2445 $tmpobj->town = $this->town;
2446 $tmpobj->zip = $this->zip;
2447 $tmpobj->state_id = $this->state_id;
2448 $tmpobj->country_id = $this->country_id;
2449
2450 $tmpobj->user_id = $this->id;
2451 $tmpobj->user_login = $this->login;
2452
2453 $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2454 if ($result < 0) {
2455 $this->error = $tmpobj->error;
2456 $this->errors = $tmpobj->errors;
2457 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2458 $error++;
2459 }
2460 } else {
2461 $this->error = $tmpobj->error;
2462 $this->errors = $tmpobj->errors;
2463 $error++;
2464 }
2465 }
2466 }
2467
2468 $action = 'update';
2469
2470 // Actions on extra fields
2471 if (!$error) {
2472 $result = $this->insertExtraFields();
2473 if ($result < 0) {
2474 $error++;
2475 }
2476 }
2477
2478 if (!$error && !$notrigger) {
2479 // Call trigger
2480 $result = $this->call_trigger('USER_MODIFY', $user);
2481 if ($result < 0) {
2482 $error++;
2483 }
2484 // End call triggers
2485 }
2486
2487 if (!$error) {
2488 $this->db->commit();
2489 return $nbrowsaffected;
2490 } else {
2491 dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2492 $this->db->rollback();
2493 return -1;
2494 }
2495 } else {
2496 $this->error = $this->db->lasterror();
2497 $this->db->rollback();
2498 return -2;
2499 }
2500 }
2501
2502 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2509 public function update_last_login_date()
2510 {
2511 // phpcs:enable
2512 $now = dol_now();
2513
2514 $userremoteip = getUserRemoteIP();
2515
2516 $sql = "UPDATE ".$this->db->prefix()."user SET";
2517 $sql .= " datepreviouslogin = datelastlogin,";
2518 $sql .= " ippreviouslogin = iplastlogin,";
2519 $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2520 $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2521 $sql .= " tms = tms"; // The last update date must change because the last login date is updated
2522 $sql .= " WHERE rowid = ".((int) $this->id);
2523
2524 dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2525 $resql = $this->db->query($sql);
2526 if ($resql) {
2527 $this->datepreviouslogin = $this->datelastlogin;
2528 $this->datelastlogin = $now;
2529 $this->ippreviouslogin = $this->iplastlogin;
2530 $this->iplastlogin = $userremoteip;
2531 return 1;
2532 } else {
2533 $this->error = $this->db->lasterror().' sql='.$sql;
2534 return -1;
2535 }
2536 }
2537
2538
2551 public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2552 {
2553 global $conf, $langs;
2554 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2555
2556 $error = 0;
2557
2558 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2559
2560 // If new password not provided, we generate one
2561 if (!$password) {
2562 $password = getRandomPassword(false);
2563 }
2564
2565 $password_crypted = null;
2566 // Check and encrypt the password
2567 if (empty($passwordalreadycrypted)) {
2568 if (getDolGlobalString('USER_PASSWORD_GENERATED')) {
2569 // Add a check on rules for password syntax using the setup of the password generator
2570 $modGeneratePassClass = 'modGeneratePass'.ucfirst($conf->global->USER_PASSWORD_GENERATED);
2571
2572 include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2573 if (class_exists($modGeneratePassClass)) {
2574 $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2575 '@phan-var-force ModeleGenPassword $modGeneratePass';
2576
2577 // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2578 $modGeneratePass->WithoutAmbi = 0;
2579
2580 // Call to validatePassword($password) to check pass match rules
2581 $testpassword = $modGeneratePass->validatePassword($password);
2582 if (!$testpassword) {
2583 $this->error = $modGeneratePass->error;
2584 return -1;
2585 }
2586 }
2587 }
2588
2589
2590 // Now, we encrypt the new password
2591 $password_crypted = dol_hash($password);
2592 }
2593
2594 // Update password
2595 if (!$changelater) {
2596 if (!is_object($this->oldcopy)) {
2597 $this->oldcopy = clone $this;
2598 }
2599
2600 $now = dol_now();
2601
2602 $this->db->begin();
2603
2604 $sql = "UPDATE ".$this->db->prefix()."user";
2605 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2606 $sql .= " datelastpassvalidation = '".$this->db->idate(dol_now())."',";
2607 $sql .= " pass_temp = null";
2608 if (!empty($flagdelsessionsbefore)) {
2609 $sql .= ", flagdelsessionsbefore = '".$this->db->idate($now - 5, 'gmt')."'";
2610 }
2611 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
2612 $sql .= ", pass = null";
2613 } else {
2614 $sql .= ", pass = '".$this->db->escape($password)."'";
2615 }
2616 $sql .= " WHERE rowid = ".((int) $this->id);
2617
2618 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2619
2620 $result = $this->db->query($sql);
2621 if ($result) {
2622 if ($this->db->affected_rows($result)) {
2623 $this->pass = $password;
2624 $this->pass_indatabase = $password;
2625 $this->pass_indatabase_crypted = (string) $password_crypted;
2626
2627 if ($this->fk_member && !$nosyncmember) {
2628 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2629
2630 // This user is linked with a member, so we also update members information
2631 // if this is an update.
2632 $adh = new Adherent($this->db);
2633 $result = $adh->fetch($this->fk_member);
2634
2635 if ($result >= 0) {
2636 $result = $adh->setPassword($user, $this->pass, (!getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 0 : 1), 1); // The encryption is not managed in the 'adherent' module
2637 if (is_int($result) && $result < 0) {
2638 $this->error = $adh->error;
2639 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2640 $error++;
2641 }
2642 } else {
2643 $this->error = $adh->error;
2644 $error++;
2645 }
2646 }
2647
2648 dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2649
2650 // Call trigger for the "security events" log
2651 $user->context['audit'] = 'login='.$user->login;
2652 if (!empty($flagdelsessionsbefore)) {
2653 $user->context['audit'] .= " - flagdelsessionsbefore set to '".$this->db->idate($now - 5, 'gmt')."'";
2654 }
2655
2656 if (!$error && !$notrigger) {
2657 // Call trigger
2658 $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2659 if ($result < 0) {
2660 $error++;
2661 $this->db->rollback();
2662 return -1;
2663 }
2664 // End call triggers
2665 }
2666
2667 $this->db->commit();
2668 return $this->pass;
2669 } else {
2670 $this->db->rollback();
2671 return 0;
2672 }
2673 } else {
2674 $this->db->rollback();
2675 dol_print_error($this->db);
2676 return -1;
2677 }
2678 } else {
2679 // We store password in password temporary field.
2680 // After receiving confirmation link, we will erase and store it in pass_crypted
2681 $sql = "UPDATE ".$this->db->prefix()."user";
2682 $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2683 $sql .= " WHERE rowid = ".((int) $this->id);
2684
2685 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2686 $result = $this->db->query($sql);
2687 if ($result) {
2688 return $password;
2689 } else {
2690 dol_print_error($this->db);
2691 return -3;
2692 }
2693 }
2694 }
2695
2696 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2705 public function send_password($user, $password = '', $changelater = 0)
2706 {
2707 // phpcs:enable
2708 global $conf, $langs;
2710
2711 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2712
2713 $msgishtml = 0;
2714
2715 // Define $msg
2716 $mesg = '';
2717
2718 $outputlangs = new Translate("", $conf);
2719
2720 if (getDolGlobalString('MAIN_LANG_DEFAULT')) {
2721 $outputlangs->setDefaultLang(getDolGlobalString('MAIN_LANG_DEFAULT'));
2722 } else { // If user has not defined its own language, we used current language
2723 $outputlangs = $langs;
2724 }
2725
2726 // Load translation files required by the page
2727 $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2728
2729 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', constant('DOL_APPLICATION_TITLE'));
2730
2731 $subject = '['.$appli.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2732
2733 // Define $urlwithroot
2734 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2735 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2736
2737 if (!$changelater) {
2738 $url = $urlwithroot.'/';
2739 if (getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD')) {
2740 $url = getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD');
2741 }
2742
2743 dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2744
2745 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2746 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2747 $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2748 $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2749 $mesg .= "\n";
2750
2751 $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2752 $mesg .= "--\n";
2753 $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2754 } else {
2755 //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2756 $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2757 $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2758 if (isModEnabled('multicompany')) {
2759 $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2760 }
2761
2762 dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2763
2764 $msgishtml = 1;
2765
2766 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2767 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2768 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2769 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2770 $mesg .= "<br>\n";
2771 $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2772 $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2773 $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2774 }
2775
2776 $trackid = 'use'.$this->id;
2777 $sendcontext = 'passwordreset';
2778
2779 $mailfile = new CMailFile(
2780 $subject,
2781 $this->email,
2782 getDolGlobalString("MAIN_MAIL_EMAIL_FROM_PASSWORDRESET", getDolGlobalString("MAIN_MAIL_EMAIL_FROM")),
2783 $mesg,
2784 array(),
2785 array(),
2786 array(),
2787 '',
2788 '',
2789 0,
2790 $msgishtml,
2791 '',
2792 '',
2793 $trackid,
2794 '',
2795 $sendcontext
2796 );
2797
2798 if ($mailfile->sendfile()) {
2799 return 1;
2800 } else {
2801 $langs->trans("errors");
2802 $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2803 return -1;
2804 }
2805 }
2806
2812 public function error()
2813 {
2814 return $this->error;
2815 }
2816
2817
2818 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2824 public function fetch_clicktodial()
2825 {
2826 // phpcs:enable
2827 $sql = "SELECT url, login, pass, poste ";
2828 $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2829 $sql .= " WHERE u.fk_user = ".((int) $this->id);
2830
2831 $resql = $this->db->query($sql);
2832 if ($resql) {
2833 if ($this->db->num_rows($resql)) {
2834 $obj = $this->db->fetch_object($resql);
2835
2836 $this->clicktodial_url = $obj->url;
2837 $this->clicktodial_login = $obj->login;
2838 $this->clicktodial_password = $obj->pass;
2839 $this->clicktodial_poste = $obj->poste;
2840 }
2841
2842 $this->clicktodial_loaded = 1; // Data loaded (found or not)
2843
2844 $this->db->free($resql);
2845 return 1;
2846 } else {
2847 $this->error = $this->db->error();
2848 return -1;
2849 }
2850 }
2851
2852 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2858 public function update_clicktodial()
2859 {
2860 // phpcs:enable
2861 $this->db->begin();
2862
2863 $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2864 $sql .= " WHERE fk_user = ".((int) $this->id);
2865
2866 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2867
2868 $result = $this->db->query($sql);
2869
2870 $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
2871 $sql .= " (fk_user,url,login,pass,poste)";
2872 $sql .= " VALUES (".$this->id;
2873 $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2874 $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2875 $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2876 $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2877
2878 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2879
2880 $result = $this->db->query($sql);
2881 if ($result) {
2882 $this->db->commit();
2883 return 1;
2884 } else {
2885 $this->db->rollback();
2886 $this->error = $this->db->lasterror();
2887 return -1;
2888 }
2889 }
2890
2891
2892 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2901 public function SetInGroup($group, $entity, $notrigger = 0)
2902 {
2903 // phpcs:enable
2904 global $conf, $langs, $user;
2905
2906 $error = 0;
2907
2908 $this->db->begin();
2909
2910 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2911 $sql .= " WHERE fk_user = ".((int) $this->id);
2912 $sql .= " AND fk_usergroup = ".((int) $group);
2913 $sql .= " AND entity = ".((int) $entity);
2914
2915 $result = $this->db->query($sql);
2916
2917 $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
2918 $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
2919
2920 $result = $this->db->query($sql);
2921 if ($result) {
2922 if (!$error && !$notrigger) {
2923 $this->context = array('audit' => $langs->trans("UserSetInGroup"), 'newgroupid' => $group);
2924
2925 // Call trigger
2926 $result = $this->call_trigger('USER_MODIFY', $user);
2927 if ($result < 0) {
2928 $error++;
2929 }
2930 // End call triggers
2931 }
2932
2933 if (!$error) {
2934 $this->db->commit();
2935 return 1;
2936 } else {
2937 dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2938 $this->db->rollback();
2939 return -2;
2940 }
2941 } else {
2942 $this->error = $this->db->lasterror();
2943 $this->db->rollback();
2944 return -1;
2945 }
2946 }
2947
2948 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2957 public function RemoveFromGroup($group, $entity, $notrigger = 0)
2958 {
2959 // phpcs:enable
2960 global $conf, $langs, $user;
2961
2962 $error = 0;
2963
2964 $this->db->begin();
2965
2966 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2967 $sql .= " WHERE fk_user = ".((int) $this->id);
2968 $sql .= " AND fk_usergroup = ".((int) $group);
2969 if (empty($entity)) {
2970 $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
2971 } else {
2972 $sql .= " AND entity = ".((int) $entity);
2973 }
2974
2975 $result = $this->db->query($sql);
2976 if ($result) {
2977 if (!$error && !$notrigger) {
2978 $this->context = array('audit' => $langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
2979
2980 // Call trigger
2981 $result = $this->call_trigger('USER_MODIFY', $user);
2982 if ($result < 0) {
2983 $error++;
2984 }
2985 // End call triggers
2986 }
2987
2988 if (!$error) {
2989 $this->db->commit();
2990 return 1;
2991 } else {
2992 dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2993 $this->db->rollback();
2994 return -2;
2995 }
2996 } else {
2997 $this->error = $this->db->lasterror();
2998 $this->db->rollback();
2999 return -1;
3000 }
3001 }
3002
3003
3011 {
3012 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3013
3014 $now = dol_now();
3015
3016 //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
3017
3018 // Check date start validity
3019 if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
3020 return 1;
3021 }
3022 // Check date end validity
3023 if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
3024 return 1;
3025 }
3026
3027 return 0;
3028 }
3029
3030
3042 public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
3043 {
3044 $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3045 $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
3046 $result .= '</a>';
3047
3048 return $result;
3049 }
3050
3057 public function getTooltipContentArray($params)
3058 {
3059 global $conf, $langs, $menumanager;
3060 global $dolibarr_main_demo;
3061
3062 $infologin = $params['infologin'] ?? 0;
3063 $option = $params['option'] ?? '';
3064
3065 $data = [];
3066 if (!empty($this->photo)) {
3067 $photo = '<div class="photointooltip floatright">';
3068 $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
3069 $photo .= '</div>';
3070 $data['photo'] = $photo;
3071 //$label .= '<div style="clear: both;"></div>';
3072 }
3073
3074 // Info Login
3075 $data['opendiv'] = '<div class="centpercent divtooltip">';
3076 $data['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
3077 $data['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs));
3078 if (!empty($this->login)) {
3079 $data['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
3080 }
3081 if (!empty($this->job)) {
3082 $data['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
3083 }
3084 $data['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
3085 if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
3086 $phonelist = array();
3087 if ($this->office_phone) {
3088 $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3089 }
3090 if ($this->office_fax) {
3091 $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3092 }
3093 if ($this->user_mobile) {
3094 $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3095 }
3096 $data['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
3097 }
3098 if (!empty($this->admin)) {
3099 $data['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
3100 }
3101 if (!empty($this->accountancy_code) || $option == 'accountancy') {
3102 $langs->load("companies");
3103 $data['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
3104 }
3105 $company = '';
3106 if (!empty($this->socid)) { // Add thirdparty for external users
3107 $thirdpartystatic = new Societe($this->db);
3108 $thirdpartystatic->fetch($this->socid);
3109 $companyimg = '';
3110 if (empty($params['hidethirdpartylogo'])) {
3111 $companyimg = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3112 }
3113 $company = ' ('.$langs->trans("Company").': '.($companyimg ? $companyimg : img_picto('', 'company')).' '.dol_string_nohtmltag($thirdpartystatic->name).')';
3114 }
3115 $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
3116 $data['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
3117 $data['closediv'] = '</div>';
3118
3119 if ($infologin > 0) {
3120 $data['newlinelogin'] = '<br>';
3121 $data['session'] = '<br><u>'.$langs->trans("Session").'</u>';
3122 $data['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
3123 if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
3124 $data['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
3125 }
3126 $data['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
3127 $data['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
3128 $data['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
3129 $data['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
3130 // @phan-suppress-next-line PhanRedefinedClassReference
3131 $data['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
3132 $s = picto_from_langcode($langs->getDefaultLang());
3133 $data['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
3134 $data['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
3135 $data['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
3136 $data['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
3137 if ($conf->browser->layout == 'phone') {
3138 $data['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
3139 }
3140 if (!empty($_SESSION["disablemodules"])) {
3141 $data['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(implode(', ', explode(',', $_SESSION["disablemodules"])));
3142 }
3143 }
3144
3145 return $data;
3146 }
3147
3163 public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = 'valignmiddle', $save_lastsearch_value = -1)
3164 {
3165 global $langs, $hookmanager, $user;
3166
3167 if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
3168 $option = 'nolink';
3169 }
3170
3171 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
3172 $withpictoimg = 0;
3173 }
3174
3175 $result = '';
3176 $params = [
3177 'id' => $this->id,
3178 'objecttype' => $this->element,
3179 'infologin' => $infologin,
3180 'option' => $option,
3181 'hidethirdpartylogo' => $hidethirdpartylogo,
3182 ];
3183 $classfortooltip = 'classfortooltip';
3184 $dataparams = '';
3185 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3186 $classfortooltip = 'classforajaxtooltip';
3187 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3188 $label = '';
3189 } else {
3190 $label = implode($this->getTooltipContentArray($params));
3191 }
3192
3193 $companylink = '';
3194 if (!empty($this->socid)) { // Add thirdparty for external users
3195 $thirdpartystatic = new Societe($this->db);
3196 $thirdpartystatic->fetch($this->socid);
3197 if (empty($hidethirdpartylogo)) {
3198 $companylink = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3199 }
3200 }
3201
3202 if ($infologin < 0) {
3203 $label = '';
3204 }
3205
3206 $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id;
3207 if ($option == 'leave') {
3208 $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id;
3209 }
3210
3211 if ($option != 'nolink') {
3212 // Add param to save lastsearch_values or not
3213 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3214 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3215 $add_save_lastsearch_values = 1;
3216 }
3217 if ($add_save_lastsearch_values) {
3218 $url .= '&save_lastsearch_values=1';
3219 }
3220 }
3221
3222 $linkstart = '<a href="'.$url.'"';
3223 $linkclose = "";
3224 if (empty($notooltip)) {
3225 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3226 $langs->load("users");
3227 $label = $langs->trans("ShowUser");
3228 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3229 }
3230 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3231 $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
3232 } else {
3233 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
3234 }
3235
3236 $linkstart .= $linkclose.'>';
3237 $linkend = '</a>';
3238
3239 //if ($withpictoimg == -1) $result.='<div class="nowrap">';
3240 $result .= (($option == 'nolink') ? '' : $linkstart);
3241 if ($withpictoimg) {
3242 $paddafterimage = '';
3243 if (abs((int) $withpictoimg) == 1) {
3244 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3245 }
3246 // Only picto
3247 if ($withpictoimg > 0) {
3248 $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>';
3249 } else {
3250 // Picto must be a photo
3251 $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>';
3252 }
3253 $result .= $picto;
3254 }
3255 if ($withpictoimg > -2 && $withpictoimg != 2) {
3256 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3257 $result .= '<span class="nopadding usertext'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
3258 }
3259 if ($mode == 'login') {
3260 $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
3261 } else {
3262 $result .= dol_string_nohtmltag($this->getFullName($langs, 0, ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
3263 }
3264 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3265 $result .= '</span>';
3266 }
3267 }
3268 $result .= (($option == 'nolink') ? '' : $linkend);
3269 //if ($withpictoimg == -1) $result.='</div>';
3270
3271 $result .= $companylink;
3272
3273 global $action;
3274 $hookmanager->initHooks(array('userdao'));
3275 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
3276 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3277 if ($reshook > 0) {
3278 $result = $hookmanager->resPrint;
3279 } else {
3280 $result .= $hookmanager->resPrint;
3281 }
3282
3283 return $result;
3284 }
3285
3295 public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
3296 {
3297 global $langs, $user;
3298
3299 $result = '';
3300
3301 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3302 $linkend = '</a>';
3303
3304 //Check user's rights to see an other user
3305 if ((!$user->hasRight('user', 'user', 'lire') && $this->id != $user->id)) {
3306 $option = 'nolink';
3307 }
3308
3309 if ($option == 'xxx') {
3310 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3311 $linkend = '</a>';
3312 }
3313
3314 if ($option == 'nolink') {
3315 $linkstart = '';
3316 $linkend = '';
3317 }
3318
3319 $result .= $linkstart;
3320 if ($withpictoimg) {
3321 $paddafterimage = '';
3322 if (abs($withpictoimg) == 1) {
3323 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3324 }
3325 // Only picto
3326 if ($withpictoimg > 0) {
3327 $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3328 } else {
3329 // Picto must be a photo
3330 $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>';
3331 }
3332 $result .= $picto;
3333 }
3334 $result .= $this->login;
3335 $result .= $linkend;
3336
3337 return $result;
3338 }
3339
3346 public function getLibStatut($mode = 0)
3347 {
3348 return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3349 }
3350
3351 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3359 public function LibStatut($status, $mode = 0)
3360 {
3361 // phpcs:enable
3362 global $langs;
3363
3364 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3365 global $langs;
3366 //$langs->load("mymodule");
3367 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3368 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3369 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3370 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3371 }
3372
3373 $statusType = 'status5';
3374 if ($status == self::STATUS_ENABLED) {
3375 $statusType = 'status4';
3376 }
3377
3378 $label = $this->labelStatus[$status];
3379 $labelshort = $this->labelStatusShort[$status];
3380
3381 $now = dol_now();
3382 if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3383 $statusType = 'status3';
3384 $label .= ' ('.$langs->trans("UserNotYetValid").')';
3385 }
3386 if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3387 $statusType = 'status2';
3388 $label .= ' ('.$langs->trans("UserExpired").')';
3389 }
3390
3391 return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3392 }
3393
3394
3402 public function getKanbanView($option = '', $arraydata = null)
3403 {
3404 global $langs;
3405
3406 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3407
3408 $return = '<div class="box-flex-item box-flex-grow-zero">';
3409 $return .= '<div class="info-box info-box-sm">';
3410 $return .= '<span class="info-box-icon bg-infobox-action">';
3411
3412 $label = '';
3413 if (!empty($this->photo)) {
3414 //$label .= '<div class="photointooltip floatright">';
3415 $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
3416 //$label .= '</div>';
3417 //$label .= '<div style="clear: both;"></div>';
3418 $return .= $label;
3419 } else {
3420 $return .= img_picto('', $this->picto);
3421 }
3422
3423 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3424 $return .= '</span>';
3425 $return .= '<div class="info-box-content">';
3426 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3427 if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3428 $return .= img_picto($langs->trans("SuperAdministratorDesc"), 'redstar', 'class="valignmiddle paddingright paddingleft"');
3429 } elseif ($this->admin) {
3430 $return .= img_picto($langs->trans("AdministratorDesc"), 'star', 'class="valignmiddle paddingright paddingleft"');
3431 }
3432 $return .= '</span>';
3433 if ($selected >= 0) {
3434 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3435 }
3436 if (property_exists($this, 'label')) {
3437 $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3438 }
3439 if ($this->email) {
3440 $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3441 }
3442 if (method_exists($this, 'getLibStatut')) {
3443 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3444 }
3445 $return .= '</div>';
3446 $return .= '</div>';
3447 $return .= '</div>';
3448
3449 return $return;
3450 }
3451
3452
3453 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3454 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3464 public function _load_ldap_dn($info, $mode = 0)
3465 {
3466 // phpcs:enable
3467 global $conf;
3468 $dn = '';
3469 if ($mode == 0) {
3470 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')]."," . getDolGlobalString('LDAP_USER_DN');
3471 } elseif ($mode == 1) {
3472 $dn = getDolGlobalString('LDAP_USER_DN');
3473 } elseif ($mode == 2) {
3474 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')];
3475 }
3476 return $dn;
3477 }
3478
3479 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3480 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3486 public function _load_ldap_info()
3487 {
3488 // phpcs:enable
3489 global $conf, $langs;
3490
3491 $info = array();
3492
3493 $socialnetworks = getArrayOfSocialNetworks();
3494
3495 $keymodified = false;
3496
3497 // Object classes
3498 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_USER_OBJECT_CLASS'));
3499
3500 $this->fullname = $this->getFullName($langs);
3501
3502 // Possible LDAP KEY (constname => varname)
3503 $ldapkey = array(
3504 'LDAP_FIELD_FULLNAME' => 'fullname',
3505 'LDAP_FIELD_NAME' => 'lastname',
3506 'LDAP_FIELD_FIRSTNAME' => 'firstname',
3507 'LDAP_FIELD_LOGIN' => 'login',
3508 'LDAP_FIELD_LOGIN_SAMBA' => 'login',
3509 'LDAP_FIELD_PHONE' => 'office_phone',
3510 'LDAP_FIELD_MOBILE' => 'user_mobile',
3511 'LDAP_FIELD_FAX' => 'office_fax',
3512 'LDAP_FIELD_MAIL' => 'email',
3513 'LDAP_FIELD_SID' => 'ldap_sid',
3514 );
3515
3516 // Champs
3517 foreach ($ldapkey as $constname => $varname) {
3518 if (!empty($this->$varname) && getDolGlobalString($constname)) {
3519 $info[getDolGlobalString($constname)] = $this->$varname;
3520
3521 // Check if it is the LDAP key and if its value has been changed
3522 if (getDolGlobalString('LDAP_KEY_USERS') && $conf->global->LDAP_KEY_USERS == getDolGlobalString($constname)) {
3523 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->$varname != $this->oldcopy->$varname) {
3524 $keymodified = true; // For check if LDAP key has been modified
3525 }
3526 }
3527 }
3528 }
3529 foreach ($socialnetworks as $key => $value) {
3530 if (!empty($this->socialnetworks[$value['label']]) && getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))) {
3531 $info[getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3532 }
3533 }
3534 if ($this->address && getDolGlobalString('LDAP_FIELD_ADDRESS')) {
3535 $info[getDolGlobalString('LDAP_FIELD_ADDRESS')] = $this->address;
3536 }
3537 if ($this->zip && getDolGlobalString('LDAP_FIELD_ZIP')) {
3538 $info[getDolGlobalString('LDAP_FIELD_ZIP')] = $this->zip;
3539 }
3540 if ($this->town && getDolGlobalString('LDAP_FIELD_TOWN')) {
3541 $info[getDolGlobalString('LDAP_FIELD_TOWN')] = $this->town;
3542 }
3543 if ($this->note_public && getDolGlobalString('LDAP_FIELD_DESCRIPTION')) {
3544 $info[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_public, 2);
3545 }
3546 if ($this->socid > 0 && getDolGlobalString('LDAP_FIELD_COMPANY')) {
3547 $soc = new Societe($this->db);
3548 $soc->fetch($this->socid);
3549
3550 $info[getDolGlobalString('LDAP_FIELD_COMPANY')] = $soc->name;
3551 if ($soc->client == 1) {
3552 $info["businessCategory"] = "Customers";
3553 }
3554 if ($soc->client == 2) {
3555 $info["businessCategory"] = "Prospects";
3556 }
3557 if ($soc->fournisseur == 1) {
3558 $info["businessCategory"] = "Suppliers";
3559 }
3560 }
3561
3562 // When password is modified
3563 if (!empty($this->pass)) {
3564 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3565 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass; // this->pass = unencrypted password
3566 }
3567 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3568 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3569 }
3570 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3571 // Set LDAP password if possible
3572 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3573 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
3574 // Just for the default MD5 !
3575 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) {
3576 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3577 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3578 }
3579 }
3580 } elseif (!empty($this->pass_indatabase)) {
3581 // Use $this->pass_indatabase value if exists
3582 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3583 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = unencrypted password
3584 }
3585 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3586 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3587 }
3588 }
3589 }
3590
3591 if (getDolGlobalString('LDAP_SERVER_TYPE') == 'egroupware') {
3592 $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3593
3594 $info['uidnumber'] = $this->id;
3595
3596 $info['phpgwTz'] = 0;
3597 $info['phpgwMailType'] = 'INTERNET';
3598 $info['phpgwMailHomeType'] = 'INTERNET';
3599
3600 $info["phpgwContactTypeId"] = 'n';
3601 $info["phpgwContactCatId"] = 0;
3602 $info["phpgwContactAccess"] = "public";
3603
3604 /*
3605 if (dol_strlen($this->egroupware_id) == 0) {
3606 $this->egroupware_id = 1;
3607 }
3608 $info["phpgwContactOwner"] = $this->egroupware_id;
3609 */
3610 $info["phpgwContactOwner"] = 1;
3611
3612 if ($this->email) {
3613 $info["rfc822Mailbox"] = $this->email;
3614 }
3615 if ($this->user_mobile) {
3616 $info["phpgwCellTelephoneNumber"] = $this->user_mobile;
3617 }
3618 }
3619
3620 if (getDolGlobalString('LDAP_FIELD_USERID')) {
3621 $info[getDolGlobalString('LDAP_FIELD_USERID')] = $this->id;
3622 }
3623 if (getDolGlobalString('LDAP_FIELD_GROUPID')) {
3624 $usergroup = new UserGroup($this->db);
3625 $groupslist = $usergroup->listGroupsForUser($this->id);
3626 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = '65534';
3627 if (!empty($groupslist)) {
3628 foreach ($groupslist as $groupforuser) {
3629 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = $groupforuser->id; //Select first group in list
3630 break;
3631 }
3632 }
3633 }
3634 if (getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY') && getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')) {
3635 $info[getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY')] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->login";
3636 }
3637
3638 return $info;
3639 }
3640
3641
3649 public function initAsSpecimen()
3650 {
3651 global $user, $langs;
3652
3653 $now = dol_now();
3654
3655 // Initialise parameters
3656 $this->id = 0;
3657 $this->ref = 'SPECIMEN';
3658 $this->specimen = 1;
3659
3660 $this->lastname = 'DOLIBARR';
3661 $this->firstname = 'SPECIMEN';
3662 $this->gender = 'man';
3663 $this->note_public = 'This is a note public';
3664 $this->note_private = 'This is a note private';
3665 $this->email = 'email@specimen.com';
3666 $this->personal_email = 'personalemail@specimen.com';
3667 $this->socialnetworks = array(
3668 'skype' => 'skypepseudo',
3669 'twitter' => 'twitterpseudo',
3670 'facebook' => 'facebookpseudo',
3671 'linkedin' => 'linkedinpseudo',
3672 );
3673 $this->office_phone = '0999999999';
3674 $this->office_fax = '0999999998';
3675 $this->user_mobile = '0999999997';
3676 $this->personal_mobile = '0999999996';
3677 $this->admin = 0;
3678 $this->login = 'dolibspec';
3679 $this->pass = 'dolibSpec+@123';
3680 //$this->pass_indatabase='dolibspec'; Set after a fetch
3681 //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3682 $this->datec = $now;
3683 $this->datem = $now;
3684
3685 $this->datelastlogin = $now;
3686 $this->iplastlogin = '127.0.0.1';
3687 $this->datepreviouslogin = $now;
3688 $this->ippreviouslogin = '127.0.0.1';
3689 $this->statut = 1; // deprecated
3690 $this->status = 1;
3691
3692 $this->entity = 1;
3693
3694 return 1;
3695 }
3696
3703 public function info($id)
3704 {
3705 $sql = "SELECT u.rowid, u.login as ref, u.datec,";
3706 $sql .= " u.tms as date_modification, u.entity";
3707 $sql .= " FROM ".$this->db->prefix()."user as u";
3708 $sql .= " WHERE u.rowid = ".((int) $id);
3709
3710 $result = $this->db->query($sql);
3711 if ($result) {
3712 if ($this->db->num_rows($result)) {
3713 $obj = $this->db->fetch_object($result);
3714
3715 $this->id = $obj->rowid;
3716
3717 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3718 $this->date_creation = $this->db->jdate($obj->datec);
3719 $this->date_modification = $this->db->jdate($obj->date_modification);
3720 $this->entity = $obj->entity;
3721 }
3722
3723 $this->db->free($result);
3724 } else {
3725 dol_print_error($this->db);
3726 }
3727 }
3728
3729
3735 public function getNbOfEMailings()
3736 {
3737 $sql = "SELECT count(mc.email) as nb";
3738 $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3739 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3740 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
3741
3742 $resql = $this->db->query($sql);
3743 if ($resql) {
3744 $obj = $this->db->fetch_object($resql);
3745 $nb = $obj->nb;
3746
3747 $this->db->free($resql);
3748 return $nb;
3749 } else {
3750 $this->error = $this->db->error();
3751 return -1;
3752 }
3753 }
3754
3763 public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3764 {
3765 global $conf;
3766
3767 $sql = "SELECT count(rowid) as nb";
3768 $sql .= " FROM ".$this->db->prefix()."user";
3769 if ($option == 'superadmin') {
3770 $sql .= " WHERE entity = 0";
3771 } else {
3772 $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3773 if ($limitTo == 'active') {
3774 $sql .= " AND statut = 1";
3775 }
3776 }
3777 if ($admin >= 0) {
3778 $sql .= " AND admin = ".(int) $admin;
3779 }
3780
3781 $resql = $this->db->query($sql);
3782 if ($resql) {
3783 $obj = $this->db->fetch_object($resql);
3784 $nb = (int) $obj->nb;
3785
3786 $this->db->free($resql);
3787 return $nb;
3788 } else {
3789 $this->error = $this->db->lasterror();
3790 return -1;
3791 }
3792 }
3793
3794 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3801 public function update_ldap2dolibarr(&$ldapuser)
3802 {
3803 // phpcs:enable
3804 // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3805 global $user, $conf;
3806
3807 $socialnetworks = getArrayOfSocialNetworks();
3808
3809 $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3810 $this->firstname = $ldapuser->$tmpvar;
3811 $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3812 $this->lastname = $ldapuser->$tmpvar;
3813 $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3814 $this->login = $ldapuser->$tmpvar;
3815 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3816 $this->pass = $ldapuser->$tmpvar;
3817 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3818 $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3819
3820 $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3821 $this->office_phone = $ldapuser->$tmpvar;
3822 $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3823 $this->user_mobile = $ldapuser->$tmpvar;
3824 $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3825 $this->office_fax = $ldapuser->$tmpvar;
3826 $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3827 $this->email = $ldapuser->$tmpvar;
3828 foreach ($socialnetworks as $key => $value) {
3829 $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3830 $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3831 }
3832 $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3833 $this->ldap_sid = $ldapuser->$tmpvar;
3834
3835 $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3836 $this->job = $ldapuser->$tmpvar;
3837 $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3838 $this->note_public = $ldapuser->$tmpvar;
3839
3840 $result = $this->update($user);
3841
3842 dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3843
3844 return $result;
3845 }
3846
3847
3848 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3855 public function get_children()
3856 {
3857 // phpcs:enable
3858 $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3859 $sql .= " WHERE fk_user = ".((int) $this->id);
3860
3861 dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3862 $res = $this->db->query($sql);
3863 if ($res) {
3864 $users = array();
3865 while ($rec = $this->db->fetch_array($res)) {
3866 $user = new User($this->db);
3867 $user->fetch($rec['rowid']);
3868 $users[] = $user;
3869 }
3870 return $users;
3871 } else {
3872 dol_print_error($this->db);
3873 return -1;
3874 }
3875 }
3876
3877
3883 private function loadParentOf()
3884 {
3885 global $conf;
3886
3887 $this->parentof = array();
3888
3889 // Load array[child]=parent
3890 $sql = "SELECT fk_user as id_parent, rowid as id_son";
3891 $sql .= " FROM ".$this->db->prefix()."user";
3892 $sql .= " WHERE fk_user <> 0";
3893 $sql .= " AND entity IN (".getEntity('user').")";
3894
3895 dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3896 $resql = $this->db->query($sql);
3897 if ($resql) {
3898 while ($obj = $this->db->fetch_object($resql)) {
3899 $this->parentof[$obj->id_son] = $obj->id_parent;
3900 }
3901 return 1;
3902 } else {
3903 dol_print_error($this->db);
3904 return -1;
3905 }
3906 }
3907
3908 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3922 public function get_full_tree($deleteafterid = 0, $filter = '')
3923 {
3924 // phpcs:enable
3925 global $hookmanager;
3926
3927 // Actions hooked (by external module)
3928 $hookmanager->initHooks(array('userdao'));
3929
3930 $this->users = array();
3931
3932 // Init this->parentof that is array(id_son=>id_parent, ...)
3933 $this->loadParentOf();
3934
3935 // Init $this->users array
3936 $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
3937 $sql .= " FROM ".$this->db->prefix()."user as u";
3938 // Add fields from hooks
3939 $parameters = array();
3940 $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3941 if ($reshook > 0) {
3942 $sql .= $hookmanager->resPrint;
3943 } else {
3944 $sql .= " WHERE u.entity IN (".getEntity('user').")";
3945 }
3946 if ($filter) {
3947 $sql .= " AND ".$filter; // already sanitized
3948 }
3949
3950 dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3951 $resql = $this->db->query($sql);
3952 if ($resql) {
3953 $i = 0;
3954 while ($obj = $this->db->fetch_object($resql)) {
3955 $this->users[$obj->rowid]['rowid'] = $obj->rowid;
3956 $this->users[$obj->rowid]['id'] = $obj->rowid;
3957 $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
3958 $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
3959 $this->users[$obj->rowid]['firstname'] = $obj->firstname;
3960 $this->users[$obj->rowid]['lastname'] = $obj->lastname;
3961 $this->users[$obj->rowid]['login'] = $obj->login;
3962 $this->users[$obj->rowid]['statut'] = $obj->statut;
3963 $this->users[$obj->rowid]['entity'] = $obj->entity;
3964 $this->users[$obj->rowid]['email'] = $obj->email;
3965 $this->users[$obj->rowid]['gender'] = $obj->gender;
3966 $this->users[$obj->rowid]['admin'] = $obj->admin;
3967 $this->users[$obj->rowid]['photo'] = $obj->photo;
3968 // fields are filled with build_path_from_id_user
3969 $this->users[$obj->rowid]['fullpath'] = '';
3970 $this->users[$obj->rowid]['fullname'] = '';
3971 $this->users[$obj->rowid]['level'] = 0;
3972 $i++;
3973 }
3974 } else {
3975 dol_print_error($this->db);
3976 return -1;
3977 }
3978
3979 // We add the fullpath property to each element of the first level (no parent exists)
3980 dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3981 foreach ($this->users as $key => $val) {
3982 $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3983 if ($result < 0) {
3984 $this->error = 'ErrorLoopInHierarchy';
3985 return -1;
3986 }
3987 }
3988
3989 // Exclude leaf including $deleteafterid from tree
3990 if ($deleteafterid) {
3991 //print "Look to discard user ".$deleteafterid."\n";
3992 $keyfilter1 = '^'.$deleteafterid.'$';
3993 $keyfilter2 = '_'.$deleteafterid.'$';
3994 $keyfilter3 = '^'.$deleteafterid.'_';
3995 $keyfilter4 = '_'.$deleteafterid.'_';
3996 foreach (array_keys($this->users) as $key) {
3997 $fullpath = (string) $this->users[$key]['fullpath'];
3998 if (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
3999 || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath)) {
4000 unset($this->users[$key]);
4001 }
4002 }
4003 }
4004
4005 dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
4006 $this->users = dol_sort_array($this->users, 'fullname', 'asc', 1, 0, 1);
4007
4008 //var_dump($this->users);
4009
4010 return $this->users;
4011 }
4012
4021 public function getAllChildIds($addcurrentuser = 0)
4022 {
4023 $childids = array();
4024
4025 if (isset($this->cache_childids[$this->id])) {
4026 $childids = $this->cache_childids[$this->id];
4027 } else {
4028 // Init this->users
4029 $treeresult = $this->get_full_tree();
4030
4031 $idtoscan = $this->id;
4032
4033 dol_syslog("Build childid for id = ".$idtoscan);
4034 foreach ($this->users as $id => $val) {
4035 //var_dump($val['fullpath']);
4036 if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
4037 $childids[$val['id']] = $val['id'];
4038 }
4039 }
4040
4041 // A loop anywhere in the hierarchy aborts get_full_tree(), leaving the branches it had not
4042 // walked yet with an empty fullpath, so they silently drop out of the list above. Do not
4043 // cache such a truncated result, it would be reused for the whole request.
4044 if ($treeresult < 0) {
4045 dol_syslog(get_class($this)."::getAllChildIds got a truncated tree: ".$this->error, LOG_WARNING);
4046 return $addcurrentuser ? array($this->id => $this->id) : $childids;
4047 }
4048 }
4049 $this->cache_childids[$this->id] = $childids;
4050
4051 if ($addcurrentuser) {
4052 $childids[$this->id] = $this->id;
4053 }
4054
4055 return $childids;
4056 }
4057
4058 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4067 public function build_path_from_id_user($id_user, $protection = 0)
4068 {
4069 // phpcs:enable
4070 //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
4071
4072 if (!empty($this->users[$id_user]['fullpath'])) {
4073 // Already defined
4074 dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
4075 return 0;
4076 }
4077
4078 // Define fullpath and fullname
4079 $this->users[$id_user]['fullpath'] = '_'.$id_user;
4080 $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
4081 $i = 0;
4082 $cursor_user = $id_user;
4083
4084 $useridfound = array($id_user);
4085 while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) { // @phan-suppress-current-line PhanTypeMismatchProperty
4086 if (in_array($this->parentof[$cursor_user], $useridfound)) {
4087 dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
4088 return -1; // Should not happen. Protection against looping hierarchy
4089 }
4090 $useridfound[] = $this->parentof[$cursor_user];
4091 $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
4092 $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
4093 $i++;
4094 $cursor_user = $this->parentof[$cursor_user];
4095 }
4096
4097 // We count number of _ to have level
4098 $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
4099
4100 return 1;
4101 }
4102
4111 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4112 {
4113 $tables = array(
4114 'user',
4115 );
4116
4117 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4118 }
4119
4120
4126 public function loadStateBoard()
4127 {
4128 global $conf;
4129
4130 $this->nb = array();
4131
4132 $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
4133 $sql .= " FROM ".$this->db->prefix()."user as u";
4134 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4135 $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
4136 $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
4137 $sql .= " AND ug.fk_user = u.rowid";
4138 } else {
4139 $sql .= " WHERE u.entity IN (".getEntity('user').")";
4140 }
4141 $sql .= " AND u.statut > 0";
4142 //$sql.= " AND employee != 0";
4143
4144 $resql = $this->db->query($sql);
4145 if ($resql) {
4146 while ($obj = $this->db->fetch_object($resql)) {
4147 $this->nb["users"] = $obj->nb;
4148 }
4149 $this->db->free($resql);
4150 return 1;
4151 } else {
4152 dol_print_error($this->db);
4153 $this->error = $this->db->error();
4154 return -1;
4155 }
4156 }
4157
4169 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4170 {
4171 global $conf, $user, $langs;
4172
4173 $langs->load("user");
4174
4175 // Set the '$modele' to the name of the document template (model) to use
4176 if (!dol_strlen($modele)) {
4177 if (getDolGlobalString('USER_ADDON_PDF')) {
4178 $modele = getDolGlobalString('USER_ADDON_PDF');
4179 } else {
4180 $modele = 'bluesky';
4181 }
4182 }
4183
4184 $modelpath = "core/modules/user/doc/";
4185
4186 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4187 }
4188
4189 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4197 public function user_get_property($rowid, $mode)
4198 {
4199 // phpcs:enable
4200 $user_property = '';
4201
4202 if (empty($rowid)) {
4203 return '';
4204 }
4205
4206 $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
4207 $sql .= " FROM ".$this->db->prefix()."user";
4208 $sql .= " WHERE rowid = ".((int) $rowid);
4209
4210 $resql = $this->db->query($sql);
4211 if ($resql) {
4212 $nump = $this->db->num_rows($resql);
4213
4214 if ($nump) {
4215 $obj = $this->db->fetch_object($resql);
4216
4217 if ($mode == 'email') {
4218 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
4219 } elseif ($mode == 'mobile') {
4220 $user_property = $obj->user_mobile;
4221 } elseif ($mode == 'name') {
4222 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname);
4223 }
4224 }
4225 return $user_property;
4226 } else {
4227 dol_print_error($this->db);
4228 }
4229
4230 return '';
4231 }
4232
4240 public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
4241 {
4243 global $conf;
4244
4245 $encodedsecurekey = dol_hash($conf->file->instance_unique_id.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
4246 if (isModEnabled('multicompany')) {
4247 $entity_qr = '&entity='.((int) $conf->entity);
4248 } else {
4249 $entity_qr = '';
4250 }
4251 // Define $urlwithroot
4252 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
4253 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
4254 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
4255
4256 if ($typeofurl == 'internal') {
4257 $urlwithroot = DOL_URL_ROOT;
4258 }
4259
4260 return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
4261 }
4262
4276 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND', $entityfilter = false)
4277 {
4278 global $conf, $user;
4279
4280 $sql = "SELECT t.rowid";
4281 $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
4282
4283 if ($entityfilter) {
4284 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4285 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
4286 $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
4287 } else {
4288 $sql .= " WHERE t.entity = 0 OR EXISTS (";
4289 $sql .= " SELECT ug.rowid FROM " . $this->db->prefix() . "usergroup_user as ug";
4290 $sql .= " WHERE ug.fk_user = t.rowid AND ug.entity IN (" . getEntity('usergroup') . "))";
4291 }
4292 } else {
4293 $sql .= " WHERE t.entity IN (".getEntity('user').")";
4294 }
4295 } else {
4296 $sql .= " WHERE 1 = 1";
4297 }
4298
4299 // Manage filter
4300 $errormessage = '';
4301 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
4302 if ($errormessage) {
4303 $this->errors[] = $errormessage;
4304 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
4305 return -1;
4306 }
4307
4308 $sql .= $this->db->order($sortfield, $sortorder);
4309 if ($limit) {
4310 $sql .= $this->db->plimit($limit + 1, $offset);
4311 }
4312
4313 dol_syslog(__METHOD__, LOG_DEBUG);
4314
4315 $resql = $this->db->query($sql);
4316 if ($resql) {
4317 $this->users = array();
4318 $num = $this->db->num_rows($resql);
4319 if ($num) {
4320 while ($obj = $this->db->fetch_object($resql)) {
4321 $line = new self($this->db);
4322 $result = $line->fetch($obj->rowid);
4323 if ($result > 0 && !empty($line->id)) {
4324 $this->users[$obj->rowid] = clone $line;
4325 }
4326 }
4327 $this->db->free($resql);
4328 }
4329 return $num;
4330 } else {
4331 $this->errors[] = $this->db->lasterror();
4332 return -1;
4333 }
4334 }
4335
4343 private $findUserIdByEmailCache;
4344
4355 public function findUserIdByEmail($email)
4356 {
4357 if (isset($this->findUserIdByEmailCache[$email])) {
4358 return $this->findUserIdByEmailCache[$email];
4359 }
4360
4361 $this->findUserIdByEmailCache[$email] = -1;
4362
4363 $sql = 'SELECT rowid';
4364 $sql .= ' FROM '.$this->db->prefix().'user';
4365 if (getDolGlobalString('AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR')) {
4366 $sql .= " WHERE email LIKE '%".$this->db->escape($this->db->escapeforlike($email))."%'";
4367 } else {
4368 $sql .= " WHERE email = '".$this->db->escape($email)."'";
4369 }
4370 $sql .= ' LIMIT 1';
4371
4372 $resql = $this->db->query($sql);
4373 if (!$resql) {
4374 return -1;
4375 }
4376
4377 $obj = $this->db->fetch_object($resql);
4378 if (!$obj) {
4379 return -1;
4380 }
4381
4382 $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4383
4384 return $this->findUserIdByEmailCache[$email];
4385 }
4386
4393 public function cloneRights($fromId, $toId)
4394 {
4395 if (empty($fromId) || empty($toId)) {
4396 return -1;
4397 }
4398
4399 $this->db->begin();
4400
4401 // delete default rights for UserTo
4402 $sqlDelete = "DELETE FROM ".$this->db->prefix()."user_rights";
4403 $sqlDelete .= " WHERE fk_user = ".((int) $toId);
4404
4405 dol_syslog(get_class($this)."::clone_rights (delete default permissions)", LOG_DEBUG);
4406
4407 if (!$this->db->query($sqlDelete)) {
4408 $this->db->rollback();
4409 return -1;
4410 }
4411
4412 // Construction of the insertion request
4413 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id)";
4414 $sql .= " SELECT entity, ".((int) $toId).", fk_id";
4415 $sql .= " FROM ".$this->db->prefix()."user_rights src";
4416 $sql .= " WHERE fk_user = ".((int) $fromId);
4417 $sql .= " AND NOT EXISTS (";
4418 $sql .= " SELECT 1";
4419 $sql .= " FROM ".$this->db->prefix()."user_rights dest";
4420 $sql .= " WHERE dest.entity = src.entity";
4421 $sql .= " AND dest.fk_user = ".((int) $toId);
4422 $sql .= " AND dest.fk_id = src.fk_id";
4423 $sql .= " )";
4424
4425 dol_syslog(get_class($this)."::clone_rights", LOG_DEBUG);
4426
4427 // Execute request
4428 if (!$this->db->query($sql)) {
4429 $this->db->rollback();
4430 return -1;
4431 }
4432
4433 $this->db->commit();
4434 return 1;
4435 }
4436
4445 public function cloneCategories($fromId, $toId, $type = 'user')
4446 {
4447 $this->db->begin();
4448
4449 if (empty($type)) {
4450 $type = $this->table_element;
4451 }
4452
4453 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4454 $categorystatic = new Categorie($this->db);
4455
4456 $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_user)";
4457 $sql .= " SELECT fk_categorie, ".((int) $toId)." FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
4458 $sql .= " WHERE fk_user = ".((int) $fromId);
4459
4460 if (!$this->db->query($sql)) {
4461 $this->error = $this->db->lasterror();
4462 $this->db->rollback();
4463 return -1;
4464 }
4465
4466 $this->db->commit();
4467 return 1;
4468 }
4469}
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.