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