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