dolibarr 19.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-2017 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-2023 Frédéric France <frederic.france@netlogic.fr>
16 * Copyright (C) 2019 Abbes Bahfir <dolipar@dolipar.org>
17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 3 of the License, or
21 * (at your option) any later version.
22 *
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 *
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <https://www.gnu.org/licenses/>.
30 */
31
38require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
39require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
40require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
41require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
42
43
47class User extends CommonObject
48{
49 use CommonPeople;
50
54 public $element = 'user';
55
59 public $table_element = 'user';
60
64 public $fk_element = 'fk_user';
65
70 public $ismultientitymanaged = 1;
71
75 public $isextrafieldmanaged = 1;
76
80 public $picto = 'user';
81
82 public $id = 0;
83
87 public $oldcopy;
88
94 public $statut;
95
96 public $status;
97
101 public $openid;
102
103 public $ldap_sid;
104 public $search_sid;
105 public $employee;
106 public $civility_code;
107
111 public $fullname;
112
116 public $gender;
117
118 public $birth;
119
123 public $email;
124
128 public $email_oauth2;
129
133 public $personal_email;
134
138 public $socialnetworks;
139
143 public $job;
144
148 public $signature;
149
153 public $office_phone;
154
158 public $office_fax;
159
163 public $user_mobile;
164
168 public $personal_mobile;
169
173 public $admin;
174
178 public $login;
179
183 public $api_key;
184
188 public $entity;
189
193 public $pass;
194
198 public $pass_crypted;
199
203 public $pass_indatabase;
204
208 public $pass_indatabase_crypted;
209
213 public $pass_temp;
214
220 public $datec;
221
227 public $datem;
228
232 public $socid;
233
237 public $contact_id;
238
242 public $fk_member;
243
247 public $fk_user;
248
252 public $fk_user_expense_validator;
253
257 public $fk_user_holiday_validator;
258
263
267 public $clicktodial_login;
268
272 public $clicktodial_password;
273
277 public $clicktodial_poste;
278
282 public $clicktodial_loaded;
283
284
285 public $datelastlogin;
286 public $datepreviouslogin;
287 public $flagdelsessionsbefore;
288 public $iplastlogin;
289 public $ippreviouslogin;
290 public $datestartvalidity;
291 public $dateendvalidity;
292
296 public $photo;
297 public $lang;
298
302 public $rights;
303
307 public $all_permissions_are_loaded;
308
312 public $nb_rights;
313
317 public $user_group_list;
318
322 private $_tab_loaded = array();
323
327 public $conf;
328
329 public $default_values; // To store default values for user. Loaded by loadDefaultValues().
330
331 public $lastsearch_values_tmp; // To store current search criterias for user
332 public $lastsearch_values; // To store last saved search criterias for user
333
334 public $users = array(); // To store all tree of users hierarchy
335 public $parentof; // To store an array of all parents for all ids.
336 private $cache_childids; // Cache array of already loaded childs
337
338 public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
339
340 public $thm; // Average cost of employee - Used for valuation of time spent
341 public $tjm; // Average cost of employee
342
343 public $salary; // Monthly salary - Denormalized value from llx_user_employment
344 public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment
345 public $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment
346
350 public $color;
351
352 public $dateemployment; // Define date of employment by company
353 public $dateemploymentend; // Define date of employment end by company
354
355 public $default_c_exp_tax_cat;
356
360 public $ref_employee;
361
365 public $national_registration_number;
366
367 public $default_range;
368
372 public $fk_warehouse;
373
377 public $egroupware_id;
378
383 public $usergroup_entity;
384
385 public $fields = array(
386 'rowid'=>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
387 'lastname'=>array('type'=>'varchar(50)', 'label'=>'LastName', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>20, 'searchall'=>1),
388 'firstname'=>array('type'=>'varchar(50)', 'label'=>'FirstName', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1),
389 'ref_employee'=>array('type'=>'varchar(50)', 'label'=>'RefEmployee', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>30, 'searchall'=>1),
390 'national_registration_number'=>array('type'=>'varchar(50)', 'label'=>'NationalRegistrationNumber', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>40, 'searchall'=>1)
391 );
392
393
394 const STATUS_DISABLED = 0;
395 const STATUS_ENABLED = 1;
396
397
398
404 public function __construct($db)
405 {
406 $this->db = $db;
407
408 // User preference
409 $this->clicktodial_loaded = 0;
410
411 // For cache usage
412 $this->all_permissions_are_loaded = 0;
413 $this->nb_rights = 0;
414
415 // Force some default values
416 $this->admin = 0;
417 $this->employee = 1;
418
419 $this->conf = new stdClass();
420 $this->rights = new stdClass();
421 $this->rights->user = new stdClass();
422 $this->rights->user->user = new stdClass();
423 $this->rights->user->self = new stdClass();
424 $this->rights->user->user_advance = new stdClass();
425 $this->rights->user->self_advance = new stdClass();
426 $this->rights->user->group_advance = new stdClass();
427 }
428
443 public function fetch($id = 0, $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1, $email = '', $fk_socpeople = 0, $use_email_oauth2 = 0)
444 {
445 global $conf, $user;
446
447 // Clean parameters
448 $login = trim($login);
449
450 // Get user
451 $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.civility as civility_code, u.birth, u.job,";
452 $sql .= " u.email, u.email_oauth2, u.personal_email,";
453 $sql .= " u.socialnetworks,";
454 $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile, u.personal_mobile,";
455 $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
456 $sql .= " u.admin, u.login, u.note_private, u.note_public,";
457 $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.api_key,";
458 $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,";
459 $sql .= " u.statut as status, u.lang, u.entity,";
460 $sql .= " u.datec as datec,";
461 $sql .= " u.tms as datem,";
462 $sql .= " u.datelastlogin as datel,";
463 $sql .= " u.datepreviouslogin as datep,";
464 $sql .= " u.flagdelsessionsbefore,";
465 $sql .= " u.iplastlogin,";
466 $sql .= " u.ippreviouslogin,";
467 $sql .= " u.datelastpassvalidation,";
468 $sql .= " u.datestartvalidity,";
469 $sql .= " u.dateendvalidity,";
470 $sql .= " u.photo as photo,";
471 $sql .= " u.openid as openid,";
472 $sql .= " u.accountancy_code,";
473 $sql .= " u.thm,";
474 $sql .= " u.tjm,";
475 $sql .= " u.salary,";
476 $sql .= " u.salaryextra,";
477 $sql .= " u.weeklyhours,";
478 $sql .= " u.color,";
479 $sql .= " u.dateemployment, u.dateemploymentend,";
480 $sql .= " u.fk_warehouse,";
481 $sql .= " u.ref_ext,";
482 $sql .= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode
483 $sql .= " u.national_registration_number,";
484 $sql .= " u.ref_employee,";
485 $sql .= " c.code as country_code, c.label as country,";
486 $sql .= " d.code_departement as state_code, d.nom as state";
487 $sql .= " FROM ".$this->db->prefix()."user as u";
488 $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as c ON u.fk_country = c.rowid";
489 $sql .= " LEFT JOIN ".$this->db->prefix()."c_departements as d ON u.fk_state = d.rowid";
490
491 if ($entity < 0) {
492 if ((!isModEnabled('multicompany') || !getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) && (!empty($user->entity))) {
493 $sql .= " WHERE u.entity IN (0, ".((int) $conf->entity).")";
494 } else {
495 $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
496 }
497 } else {
498 // The fetch was forced on an entity
499 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
500 $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
501 } else {
502 $sql .= " WHERE u.entity IN (0, ".((int) (($entity != '' && $entity >= 0) ? $entity : $conf->entity)).")"; // search in entity provided in parameter
503 }
504 }
505
506 if ($sid) {
507 // permet une recherche du user par son SID ActiveDirectory ou Samba
508 $sql .= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."')";
509 } elseif ($login) {
510 $sql .= " AND u.login = '".$this->db->escape($login)."'";
511 } elseif ($email) {
512 $sql .= " AND (u.email = '".$this->db->escape($email)."'";
513 if ($use_email_oauth2) {
514 $sql .= " OR u.email_oauth2 = '".$this->db->escape($email)."'";
515 }
516 $sql .= ")";
517 } elseif ($fk_socpeople > 0) {
518 $sql .= " AND u.fk_socpeople = ".((int) $fk_socpeople);
519 } else {
520 $sql .= " AND u.rowid = ".((int) $id);
521 }
522 $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
523
524 if ($sid) {
525 // permet une recherche du user par son SID ActiveDirectory ou Samba
526 $sql .= ' '.$this->db->plimit(1);
527 }
528
529 $resql = $this->db->query($sql);
530 if ($resql) {
531 $num = $this->db->num_rows($resql);
532 if ($num > 1) {
533 $this->error = "USERDUPLICATEFOUND";
534 dol_syslog(get_class($this)."::fetch more than 1 user found", LOG_WARNING);
535
536 $this->db->free($resql);
537 return 0;
538 }
539
540 $obj = $this->db->fetch_object($resql);
541 if ($obj) {
542 $this->id = $obj->rowid;
543 $this->ref = $obj->rowid;
544
545 $this->ref_ext = $obj->ref_ext;
546
547 $this->ldap_sid = $obj->ldap_sid;
548 $this->civility_code = $obj->civility_code;
549 $this->lastname = $obj->lastname;
550 $this->firstname = $obj->firstname;
551 $this->ref_employee = $obj->ref_employee;
552 $this->national_registration_number = $obj->national_registration_number;
553
554 $this->employee = $obj->employee;
555
556 $this->login = $obj->login;
557 $this->gender = $obj->gender;
558 $this->birth = $this->db->jdate($obj->birth);
559 $this->pass_indatabase = $obj->pass;
560 $this->pass_indatabase_crypted = $obj->pass_crypted;
561 $this->pass = $obj->pass;
562 $this->pass_temp = $obj->pass_temp;
563 $this->api_key = dolDecrypt($obj->api_key);
564
565 $this->address = $obj->address;
566 $this->zip = $obj->zip;
567 $this->town = $obj->town;
568
569 $this->country_id = $obj->country_id;
570 $this->country_code = $obj->country_id ? $obj->country_code : '';
571 //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
572
573 $this->state_id = $obj->state_id;
574 $this->state_code = $obj->state_code;
575 $this->state = ($obj->state != '-' ? $obj->state : '');
576
577 $this->office_phone = $obj->office_phone;
578 $this->office_fax = $obj->office_fax;
579 $this->user_mobile = $obj->user_mobile;
580 $this->personal_mobile = $obj->personal_mobile;
581 $this->email = $obj->email;
582 $this->email_oauth2 = $obj->email_oauth2;
583 $this->personal_email = $obj->personal_email;
584 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
585 $this->job = $obj->job;
586 $this->signature = $obj->signature;
587 $this->admin = $obj->admin;
588 $this->note_public = $obj->note_public;
589 $this->note_private = $obj->note_private;
590 $this->note = $obj->note_private; // deprecated
591
592 $this->statut = $obj->status; // deprecated
593 $this->status = $obj->status;
594
595 $this->photo = $obj->photo;
596 $this->openid = $obj->openid;
597 $this->lang = $obj->lang;
598 $this->entity = $obj->entity;
599 $this->accountancy_code = $obj->accountancy_code;
600 $this->thm = $obj->thm;
601 $this->tjm = $obj->tjm;
602 $this->salary = $obj->salary;
603 $this->salaryextra = $obj->salaryextra;
604 $this->weeklyhours = $obj->weeklyhours;
605 $this->color = $obj->color;
606 $this->dateemployment = $this->db->jdate($obj->dateemployment);
607 $this->dateemploymentend = $this->db->jdate($obj->dateemploymentend);
608
609 $this->datec = $this->db->jdate($obj->datec);
610 $this->datem = $this->db->jdate($obj->datem);
611 $this->datelastlogin = $this->db->jdate($obj->datel);
612 $this->datepreviouslogin = $this->db->jdate($obj->datep);
613 $this->flagdelsessionsbefore = $this->db->jdate($obj->flagdelsessionsbefore, 'gmt');
614 $this->iplastlogin = $obj->iplastlogin;
615 $this->ippreviouslogin = $obj->ippreviouslogin;
616 $this->datestartvalidity = $this->db->jdate($obj->datestartvalidity);
617 $this->dateendvalidity = $this->db->jdate($obj->dateendvalidity);
618
619 $this->socid = $obj->fk_soc;
620 $this->contact_id = $obj->fk_socpeople;
621 $this->fk_member = $obj->fk_member;
622 $this->fk_user = $obj->fk_user;
623 $this->fk_user_expense_validator = $obj->fk_user_expense_validator;
624 $this->fk_user_holiday_validator = $obj->fk_user_holiday_validator;
625
626 $this->default_range = $obj->default_range;
627 $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
628 $this->fk_warehouse = $obj->fk_warehouse;
629
630 // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
631 // in such case, this admin user must be admin for ALL entities.
632 if (!isModEnabled('multicompany') && $this->admin && $this->entity == 1) {
633 $this->entity = 0;
634 }
635
636 // Retrieve all extrafield
637 // fetch optionals attributes and labels
638 $this->fetch_optionals();
639
640 $this->db->free($resql);
641 } else {
642 $this->error = "USERNOTFOUND";
643 dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
644
645 $this->db->free($resql);
646 return 0;
647 }
648 } else {
649 $this->error = $this->db->lasterror();
650 return -1;
651 }
652
653 // To get back the global configuration unique to the user
654 if ($loadpersonalconf) {
655 $result = $this->loadPersonalConf();
656
657 $result = $this->loadDefaultValues();
658
659 if ($result < 0) {
660 $this->error = $this->db->lasterror();
661 return -3;
662 }
663 }
664
665 return 1;
666 }
667
668
674 public function loadPersonalConf()
675 {
676 global $conf;
677
678 // Load user->conf for user
679 $sql = "SELECT param, value FROM ".$this->db->prefix()."user_param";
680 $sql .= " WHERE fk_user = ".((int) $this->id);
681 $sql .= " AND entity = ".((int) $conf->entity);
682 //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
683 $resql = $this->db->query($sql);
684 if ($resql) {
685 $num = $this->db->num_rows($resql);
686 $i = 0;
687 while ($i < $num) {
688 $obj = $this->db->fetch_object($resql);
689 $p = (!empty($obj->param) ? $obj->param : '');
690 if (!empty($p)) {
691 $this->conf->$p = $obj->value;
692 }
693 $i++;
694 }
695 $this->db->free($resql);
696
697 return $num;
698 } else {
699 $this->error = $this->db->lasterror();
700
701 return -2;
702 }
703 }
704
710 public function loadDefaultValues()
711 {
712 global $conf;
713
714 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
715 // Load user->default_values for user. TODO Save this in memcached ?
716 require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php';
717
718 $defaultValues = new DefaultValues($this->db);
719 $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)
720
721 if (!is_array($result) && $result < 0) {
722 setEventMessages($defaultValues->error, $defaultValues->errors, 'errors');
723 dol_print_error($this->db);
724 return -1;
725 } elseif (count($result) > 0) {
726 foreach ($result as $defval) {
727 if (!empty($defval->page) && !empty($defval->type) && !empty($defval->param)) {
728 $pagewithoutquerystring = $defval->page;
729 $pagequeries = '';
730 $reg = array();
731 if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
732 $pagewithoutquerystring = $reg[1];
733 $pagequeries = $reg[2];
734 }
735 $this->default_values[$pagewithoutquerystring][$defval->type][$pagequeries ? $pagequeries : '_noquery_'][$defval->param] = $defval->value;
736 }
737 }
738 }
739 if (!empty($this->default_values)) {
740 foreach ($this->default_values as $a => $b) {
741 foreach ($b as $c => $d) {
742 krsort($this->default_values[$a][$c]);
743 }
744 }
745 }
746 }
747 return 1;
748 }
749
761 public function hasRight($module, $permlevel1, $permlevel2 = '')
762 {
763 // For compatibility with bad naming permissions on module
764 $moduletomoduletouse = array(
765 'compta' => 'comptabilite',
766 'contract' => 'contrat',
767 'member' => 'adherent',
768 'mo' => 'mrp',
769 'order' => 'commande',
770 'produit' => 'product',
771 'project' => 'projet',
772 'propale' => 'propal',
773 'shipping' => 'expedition',
774 'task' => 'task@projet',
775 'fichinter' => 'ficheinter',
776 'inventory' => 'stock',
777 'invoice' => 'facture',
778 'invoice_supplier' => 'fournisseur',
779 'order_supplier' => 'fournisseur',
780 'knowledgerecord' => 'knowledgerecord@knowledgemanagement',
781 'skill@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
782 'job@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
783 'position@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
784 'facturerec' => 'facture',
785 'margins' => 'margin',
786 );
787
788 if (!empty($moduletomoduletouse[$module])) {
789 $module = $moduletomoduletouse[$module];
790 }
791
792 $moduleRightsMapping = array(
793 'product' => 'produit', // We must check $user->rights->produit...
794 'margin' => 'margins',
795 'comptabilite' => 'compta'
796 );
797
798 $rightsPath = $module;
799 if (!empty($moduleRightsMapping[$rightsPath])) {
800 $rightsPath = $moduleRightsMapping[$rightsPath];
801 }
802
803 // If module is abc@module, we check permission user->rights->module->abc->permlevel1
804 $tmp = explode('@', $rightsPath, 2);
805 if (!empty($tmp[1])) {
806 if (strpos($module, '@') !== false) {
807 $module = $tmp[1];
808 }
809 $rightsPath = $tmp[1];
810 $permlevel2 = $permlevel1;
811 $permlevel1 = $tmp[0];
812 }
813
814 // In $conf->modules, we have 'accounting', 'product', 'facture', ...
815 // In $user->rights, we have 'accounting', 'produit', 'facture', ...
816 //var_dump($module);
817 //var_dump($rightsPath);
818 //var_dump($this->rights->$rightsPath);
819 //var_dump($conf->modules);
820 //var_dump($module.' '.isModEnabled($module).' '.$rightsPath.' '.$permlevel1.' '.$permlevel2);
821 if (!isModEnabled($module)) {
822 return 0;
823 }
824
825 // For compatibility with bad naming permissions on permlevel1
826 if ($permlevel1 == 'propale') {
827 $permlevel1 = 'propal';
828 }
829 if ($permlevel1 == 'member') {
830 $permlevel1 = 'adherent';
831 }
832 if ($permlevel1 == 'recruitmentcandidature') {
833 $permlevel1 = 'recruitmentjobposition';
834 }
835
836 //var_dump($this->rights);
837 //var_dump($rightsPath.' '.$permlevel1.' '.$permlevel2);
838 if (empty($rightsPath) || empty($this->rights) || empty($this->rights->$rightsPath) || empty($permlevel1)) {
839 return 0;
840 }
841
842 if ($permlevel2) {
843 if (!empty($this->rights->$rightsPath->$permlevel1)) {
844 if (!empty($this->rights->$rightsPath->$permlevel1->$permlevel2)) {
845 return $this->rights->$rightsPath->$permlevel1->$permlevel2;
846 }
847 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
848 // instead of "read", "write", "delete"
849 if ($permlevel2 == 'read' && !empty($this->rights->$rightsPath->$permlevel1->lire)) {
850 return $this->rights->$rightsPath->$permlevel1->lire;
851 }
852 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->creer)) {
853 return $this->rights->$rightsPath->$permlevel1->creer;
854 }
855 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->create)) {
856 return $this->rights->$rightsPath->$permlevel1->create;
857 }
858 if ($permlevel2 == 'delete' && !empty($this->rights->$rightsPath->$permlevel1->supprimer)) {
859 return $this->rights->$rightsPath->$permlevel1->supprimer;
860 }
861 }
862 } else {
863 if (!empty($this->rights->$rightsPath->$permlevel1)) {
864 return $this->rights->$rightsPath->$permlevel1;
865 }
866 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
867 // instead of "read", "write", "delete"
868 if ($permlevel1 == 'read' && !empty($this->rights->$rightsPath->lire)) {
869 return $this->rights->$rightsPath->lire;
870 }
871 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->creer)) {
872 return $this->rights->$rightsPath->creer;
873 }
874 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->create)) {
875 return $this->rights->$rightsPath->create;
876 }
877 if ($permlevel1 == 'delete' && !empty($this->rights->$rightsPath->supprimer)) {
878 return $this->rights->$rightsPath->supprimer;
879 }
880 }
881
882 return 0;
883 }
884
896 public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
897 {
898 global $conf, $user, $langs;
899
900 $entity = (empty($entity) ? $conf->entity : $entity);
901
902 dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity, $notrigger for user id=".$this->id);
903
904 if (empty($this->id)) {
905 $this->error = 'Try to call addrights on an object user with an empty id';
906 return -1;
907 }
908
909 $error = 0;
910 $whereforadd = '';
911
912 $this->db->begin();
913
914 if (!empty($rid)) {
915 $module = $perms = $subperms = '';
916
917 // If we ask to add a given permission, we first load properties of this permission (module, perms and subperms).
918 $sql = "SELECT module, perms, subperms";
919 $sql .= " FROM ".$this->db->prefix()."rights_def";
920 $sql .= " WHERE id = ".((int) $rid);
921 $sql .= " AND entity = ".((int) $entity);
922
923 $result = $this->db->query($sql);
924 if ($result) {
925 $obj = $this->db->fetch_object($result);
926
927 if ($obj) {
928 $module = $obj->module;
929 $perms = $obj->perms;
930 $subperms = $obj->subperms;
931 }
932 } else {
933 $error++;
934 dol_print_error($this->db);
935 }
936
937 // Define the where for the permission to add
938 $whereforadd = "id=".((int) $rid);
939 // Add also inherited permissions
940 if (!empty($subperms)) {
941 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))";
942 } elseif (!empty($perms)) {
943 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND subperms IS NULL)";
944 }
945 } else {
946 // On a pas demande un droit en particulier mais une liste de droits
947 // sur la base d'un nom de module de de perms
948 // Where pour la liste des droits a ajouter
949 if (!empty($allmodule)) {
950 if ($allmodule == 'allmodules') {
951 $whereforadd = 'allmodules';
952 } else {
953 $whereforadd = "module='".$this->db->escape($allmodule)."'";
954 if (!empty($allperms)) {
955 $whereforadd .= " AND perms='".$this->db->escape($allperms)."'";
956 }
957 }
958 }
959 }
960
961 // Add automatically other permission using the criteria whereforadd
962 // $whereforadd can be a SQL filter or the string 'allmodules'
963 if (!empty($whereforadd)) {
964 //print "$module-$perms-$subperms";
965 $sql = "SELECT id";
966 $sql .= " FROM ".$this->db->prefix()."rights_def";
967 $sql .= " WHERE entity = ".((int) $entity);
968 if (!empty($whereforadd) && $whereforadd != 'allmodules') {
969 $sql .= " AND (".$whereforadd.")"; // Note: parenthesis are important because whereforadd can contains OR. Also note that $whereforadd is already sanitized
970 }
971
972 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
973 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
974 $sqldelete .= $sql;
975 $sqldelete .= ") AND entity = ".((int) $entity);
976 if (!$this->db->query($sqldelete)) {
977 $error++;
978 }
979
980 if (!$error) {
981 $resql = $this->db->query($sql);
982 if ($resql) {
983 $num = $this->db->num_rows($resql);
984 $i = 0;
985 while ($i < $num) {
986 $obj = $this->db->fetch_object($resql);
987
988 if ($obj) {
989 $nid = $obj->id;
990
991 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id) VALUES (".((int) $entity).", ".((int) $this->id).", ".((int) $nid).")";
992 if (!$this->db->query($sql)) {
993 $error++;
994 }
995 }
996
997 $i++;
998 }
999 } else {
1000 $error++;
1001 dol_print_error($this->db);
1002 }
1003 }
1004 }
1005
1006 if (!$error && !$notrigger) {
1007 $langs->load("other");
1008 $this->context = array('audit'=>$langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : ''));
1009
1010 // Call trigger
1011 $result = $this->call_trigger('USER_MODIFY', $user);
1012 if ($result < 0) {
1013 $error++;
1014 }
1015 // End call triggers
1016 }
1017
1018 if ($error) {
1019 $this->db->rollback();
1020 return -$error;
1021 } else {
1022 $this->db->commit();
1023 return 1;
1024 }
1025 }
1026
1027
1039 public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1040 {
1041 global $conf, $user, $langs;
1042
1043 $error = 0;
1044 $wherefordel = '';
1045 $entity = (!empty($entity) ? $entity : $conf->entity);
1046
1047 $this->db->begin();
1048
1049 if (!empty($rid)) {
1050 $module = $perms = $subperms = '';
1051
1052 // Si on a demande supression d'un droit en particulier, on recupere
1053 // les caracteristiques module, perms et subperms de ce droit.
1054 $sql = "SELECT module, perms, subperms";
1055 $sql .= " FROM ".$this->db->prefix()."rights_def";
1056 $sql .= " WHERE id = '".$this->db->escape($rid)."'";
1057 $sql .= " AND entity = ".((int) $entity);
1058
1059 $result = $this->db->query($sql);
1060 if ($result) {
1061 $obj = $this->db->fetch_object($result);
1062
1063 if ($obj) {
1064 $module = $obj->module;
1065 $perms = $obj->perms;
1066 $subperms = $obj->subperms;
1067 }
1068 } else {
1069 $error++;
1070 dol_print_error($this->db);
1071 }
1072
1073 // Where pour la liste des droits a supprimer
1074 $wherefordel = "id=".((int) $rid);
1075 // Suppression des droits induits
1076 if ($subperms == 'lire' || $subperms == 'read') {
1077 $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)";
1078 }
1079 if ($perms == 'lire' || $perms == 'read') {
1080 $wherefordel .= " OR (module='".$this->db->escape($module)."')";
1081 }
1082 } else {
1083 // On a demande suppression d'un droit sur la base d'un nom de module ou perms
1084 // Where pour la liste des droits a supprimer
1085 if (!empty($allmodule)) {
1086 if ($allmodule == 'allmodules') {
1087 $wherefordel = 'allmodules';
1088 } else {
1089 $wherefordel = "module='".$this->db->escape($allmodule)."'";
1090 if (!empty($allperms)) {
1091 $wherefordel .= " AND perms='".$this->db->escape($allperms)."'";
1092 }
1093 }
1094 }
1095 }
1096
1097 // Suppression des droits selon critere defini dans wherefordel
1098 if (!empty($wherefordel)) {
1099 //print "$module-$perms-$subperms";
1100 $sql = "SELECT id";
1101 $sql .= " FROM ".$this->db->prefix()."rights_def";
1102 $sql .= " WHERE entity = ".((int) $entity);
1103 if (!empty($wherefordel) && $wherefordel != 'allmodules') {
1104 $sql .= " AND (".$wherefordel.")"; // Note: parenthesis are important because wherefordel can contains OR. Also note that $wherefordel is already sanitized
1105 }
1106
1107 // avoid admin can remove his own important rights
1108 if ($this->admin == 1) {
1109 $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
1110 $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
1111 $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
1112 $sql .= " AND id NOT IN (358)"; // user export
1113 }
1114
1115 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1116 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1117 $sqldelete .= $sql;
1118 $sqldelete .= ")";
1119 $sqldelete .= " AND entity = ".((int) $entity);
1120
1121 $resql = $this->db->query($sqldelete);
1122 if (!$resql) {
1123 $error++;
1124 dol_print_error($this->db);
1125 }
1126 }
1127
1128 if (!$error && !$notrigger) {
1129 $langs->load("other");
1130 $this->context = array('audit'=>$langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : ''));
1131
1132 // Call trigger
1133 $result = $this->call_trigger('USER_MODIFY', $user);
1134 if ($result < 0) {
1135 $error++;
1136 }
1137 // End call triggers
1138 }
1139
1140 if ($error) {
1141 $this->db->rollback();
1142 return -$error;
1143 } else {
1144 $this->db->commit();
1145 return 1;
1146 }
1147 }
1148
1149
1156 public function clearrights()
1157 {
1158 dol_syslog(get_class($this)."::clearrights reset user->rights");
1159 $this->rights = null;
1160 $this->nb_rights = 0;
1161 $this->all_permissions_are_loaded = 0;
1162 $this->_tab_loaded = array();
1163 }
1164
1165
1174 public function getrights($moduletag = '', $forcereload = 0)
1175 {
1176 global $conf;
1177
1178 if (empty($forcereload)) {
1179 if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
1180 // Rights for this module are already loaded, so we leave
1181 return;
1182 }
1183
1184 if (!empty($this->all_permissions_are_loaded)) {
1185 // We already loaded all rights for this user, so we leave
1186 return;
1187 }
1188 }
1189
1190 // For avoid error
1191 if (!isset($this->rights) || !is_object($this->rights)) {
1192 $this->rights = new stdClass(); // For avoid error
1193 }
1194 if (!isset($this->rights->user) || !is_object($this->rights->user)) {
1195 $this->rights->user = new stdClass(); // For avoid error
1196 }
1197
1198 // Get permission of users + Get permissions of groups
1199
1200 // First user permissions
1201 $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1202 $sql .= " FROM ".$this->db->prefix()."user_rights as ur,";
1203 $sql .= " ".$this->db->prefix()."rights_def as r";
1204 $sql .= " WHERE r.id = ur.fk_id";
1205 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1206 // on old version, we use entity defined into table r only
1207 $sql .= " AND r.entity IN (0,".(isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') ? "1," : "").$conf->entity.")";
1208 } else {
1209 // On table r=rights_def, the unique key is (id, entity) because id is hard coded into module descriptor and insert during module activation.
1210 // So we must include the filter on entity on both table r. and ur.
1211 $sql .= " AND r.entity = ".((int) $conf->entity)." AND ur.entity = ".((int) $conf->entity);
1212 }
1213 $sql .= " AND ur.fk_user= ".((int) $this->id);
1214 $sql .= " AND r.perms IS NOT NULL";
1215 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1216 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1217 }
1218 if ($moduletag) {
1219 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1220 }
1221
1222 $resql = $this->db->query($sql);
1223 if ($resql) {
1224 $num = $this->db->num_rows($resql);
1225 $i = 0;
1226 while ($i < $num) {
1227 $obj = $this->db->fetch_object($resql);
1228
1229 if ($obj) {
1230 $module = $obj->module;
1231 $perms = $obj->perms;
1232 $subperms = $obj->subperms;
1233
1234 if (!empty($perms)) {
1235 if (!empty($module)) {
1236 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1237 $this->rights->$module = new stdClass();
1238 }
1239 if (!empty($subperms)) {
1240 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1241 $this->rights->$module->$perms = new stdClass();
1242 }
1243 if (empty($this->rights->$module->$perms->$subperms)) {
1244 $this->nb_rights++;
1245 }
1246 $this->rights->$module->$perms->$subperms = 1;
1247 } else {
1248 if (empty($this->rights->$module->$perms)) {
1249 $this->nb_rights++;
1250 }
1251 $this->rights->$module->$perms = 1;
1252 }
1253 }
1254 }
1255 }
1256 $i++;
1257 }
1258 $this->db->free($resql);
1259 }
1260
1261 // Now permissions of groups
1262 $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1263 $sql .= " FROM ".$this->db->prefix()."usergroup_rights as gr,";
1264 $sql .= " ".$this->db->prefix()."usergroup_user as gu,";
1265 $sql .= " ".$this->db->prefix()."rights_def as r";
1266 $sql .= " WHERE r.id = gr.fk_id";
1267 // A very strange business rules. Must be same than into user->getrights() user/perms.php and user/group/perms.php
1268 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1269 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1270 $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1271 } else {
1272 $sql .= " AND r.entity = ".((int) $conf->entity);
1273 }
1274 } else {
1275 $sql .= " AND gr.entity = ".((int) $conf->entity); // Only groups created in current entity
1276 // The entity on the table usergroup_user should be useless and should never be used because it is alreay into gr and r.
1277 // but when using MULTICOMPANY_TRANSVERSE_MODE, we may insert record that make rubbish result due to duplicate record of
1278 // other entities, so we are forced to add a filter here
1279 $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1280 $sql .= " AND r.entity = ".((int) $conf->entity); // Only permission of modules enabled in current entity
1281 }
1282 // End of strange business rule
1283 $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
1284 $sql .= " AND gu.fk_user = ".((int) $this->id);
1285 $sql .= " AND r.perms IS NOT NULL";
1286 if ($moduletag) {
1287 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1288 }
1289
1290 $resql = $this->db->query($sql);
1291 if ($resql) {
1292 $num = $this->db->num_rows($resql);
1293 $i = 0;
1294 while ($i < $num) {
1295 $obj = $this->db->fetch_object($resql);
1296
1297 if ($obj) {
1298 $module = $obj->module;
1299 $perms = $obj->perms;
1300 $subperms = $obj->subperms;
1301
1302 if (!empty($perms)) {
1303 if (!empty($module)) {
1304 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1305 $this->rights->$module = new stdClass();
1306 }
1307 if (!empty($subperms)) {
1308 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1309 $this->rights->$module->$perms = new stdClass();
1310 }
1311 if (empty($this->rights->$module->$perms->$subperms)) {
1312 $this->nb_rights++;
1313 }
1314 $this->rights->$module->$perms->$subperms = 1;
1315 } else {
1316 if (empty($this->rights->$module->$perms)) {
1317 $this->nb_rights++;
1318 }
1319 // 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
1320 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1321 $this->rights->$module->$perms = 1;
1322 }
1323 }
1324 }
1325 }
1326 }
1327 $i++;
1328 }
1329 $this->db->free($resql);
1330 }
1331
1332 // Force permission on user for admin
1333 if (!empty($this->admin)) {
1334 if (empty($this->rights->user->user)) {
1335 $this->rights->user->user = new stdClass();
1336 }
1337 $listofpermtotest = array('lire', 'creer', 'password', 'supprimer', 'export');
1338 foreach ($listofpermtotest as $permtotest) {
1339 if (empty($this->rights->user->user->$permtotest)) {
1340 $this->rights->user->user->$permtotest = 1;
1341 $this->nb_rights++;
1342 }
1343 }
1344 if (empty($this->rights->user->self)) {
1345 $this->rights->user->self = new stdClass();
1346 }
1347 $listofpermtotest = array('creer', 'password');
1348 foreach ($listofpermtotest as $permtotest) {
1349 if (empty($this->rights->user->self->$permtotest)) {
1350 $this->rights->user->self->$permtotest = 1;
1351 $this->nb_rights++;
1352 }
1353 }
1354 // Add test on advanced permissions
1355 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1356 if (empty($this->rights->user->user_advance)) {
1357 $this->rights->user->user_advance = new stdClass();
1358 }
1359 $listofpermtotest = array('readperms', 'write');
1360 foreach ($listofpermtotest as $permtotest) {
1361 if (empty($this->rights->user->user_advance->$permtotest)) {
1362 $this->rights->user->user_advance->$permtotest = 1;
1363 $this->nb_rights++;
1364 }
1365 }
1366 if (empty($this->rights->user->self_advance)) {
1367 $this->rights->user->self_advance = new stdClass();
1368 }
1369 $listofpermtotest = array('readperms', 'writeperms');
1370 foreach ($listofpermtotest as $permtotest) {
1371 if (empty($this->rights->user->self_advance->$permtotest)) {
1372 $this->rights->user->self_advance->$permtotest = 1;
1373 $this->nb_rights++;
1374 }
1375 }
1376 if (empty($this->rights->user->group_advance)) {
1377 $this->rights->user->group_advance = new stdClass();
1378 }
1379 $listofpermtotest = array('read', 'readperms', 'write', 'delete');
1380 foreach ($listofpermtotest as $permtotest) {
1381 if (empty($this->rights->user) || empty($this->rights->user->group_advance->$permtotest)) {
1382 $this->rights->user->group_advance->$permtotest = 1;
1383 $this->nb_rights++;
1384 }
1385 }
1386 }
1387 }
1388
1389 // For backward compatibility
1390 if (isset($this->rights->propale) && !isset($this->rights->propal)) {
1391 $this->rights->propal = $this->rights->propale;
1392 }
1393 if (isset($this->rights->propal) && !isset($this->rights->propale)) {
1394 $this->rights->propale = $this->rights->propal;
1395 }
1396
1397 if (!$moduletag) {
1398 // Si module etait non defini, alors on a tout charge, on peut donc considerer
1399 // que les droits sont en cache (car tous charges) pour cet instance de user
1400 $this->all_permissions_are_loaded = 1;
1401 } else {
1402 // If module defined, we flag it as loaded into cache
1403 $this->_tab_loaded[$moduletag] = 1;
1404 }
1405 }
1406
1413 public function setstatus($status)
1414 {
1415 global $conf, $langs, $user;
1416
1417 $error = 0;
1418
1419 // Check parameters
1420 if (isset($this->statut)) {
1421 if ($this->statut == $status) {
1422 return 0;
1423 }
1424 } elseif (isset($this->status) && $this->status == $status) {
1425 return 0;
1426 }
1427
1428 $this->db->begin();
1429
1430 // Save in database
1431 $sql = "UPDATE ".$this->db->prefix()."user";
1432 $sql .= " SET statut = ".((int) $status);
1433 $sql .= " WHERE rowid = ".((int) $this->id);
1434 $result = $this->db->query($sql);
1435
1436 dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1437 if ($result) {
1438 if ($status == 0) {
1439 $this->context['actionmsg'] = 'User '.$this->login.' disabled';
1440 } else {
1441 $this->context['actionmsg'] = 'User '.$this->login.' enabled';
1442 }
1443 // Call trigger
1444 $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
1445 if ($result < 0) {
1446 $error++;
1447 }
1448 // End call triggers
1449 }
1450
1451 if ($error) {
1452 $this->db->rollback();
1453 return -$error;
1454 } else {
1455 $this->status = $status;
1456 $this->statut = $status;
1457 $this->db->commit();
1458 return 1;
1459 }
1460 }
1461
1472 public function setCategories($categories)
1473 {
1474 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1475 return parent::setCategoriesCommon($categories, Categorie::TYPE_USER);
1476 }
1477
1484 public function delete(User $user)
1485 {
1486 global $conf, $langs;
1487
1488 $error = 0;
1489
1490 $this->db->begin();
1491
1492 $this->fetch($this->id);
1493
1494 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1495
1496 // Remove rights
1497 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1498
1499 if (!$error && !$this->db->query($sql)) {
1500 $error++;
1501 $this->error = $this->db->lasterror();
1502 }
1503
1504 // Remove group
1505 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1506 if (!$error && !$this->db->query($sql)) {
1507 $error++;
1508 $this->error = $this->db->lasterror();
1509 }
1510
1511 // Remove params
1512 $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1513 if (!$error && !$this->db->query($sql)) {
1514 $error++;
1515 $this->error = $this->db->lasterror();
1516 }
1517
1518 // If contact, remove link
1519 if ($this->contact_id > 0) {
1520 $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1521 if (!$error && !$this->db->query($sql)) {
1522 $error++;
1523 $this->error = $this->db->lasterror();
1524 }
1525 }
1526
1527 // Remove extrafields
1528 if (!$error) {
1529 $result = $this->deleteExtraFields();
1530 if ($result < 0) {
1531 $error++;
1532 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1533 }
1534 }
1535
1536 // Remove user
1537 if (!$error) {
1538 $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1539 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1540 if (!$this->db->query($sql)) {
1541 $error++;
1542 $this->error = $this->db->lasterror();
1543 }
1544 }
1545
1546 if (!$error) {
1547 // Call trigger
1548 $result = $this->call_trigger('USER_DELETE', $user);
1549 if ($result < 0) {
1550 $error++;
1551 $this->db->rollback();
1552 return -1;
1553 }
1554 // End call triggers
1555
1556 $this->db->commit();
1557 return 1;
1558 } else {
1559 $this->db->rollback();
1560 return -1;
1561 }
1562 }
1563
1571 public function create($user, $notrigger = 0)
1572 {
1573 global $conf, $langs;
1574 global $mysoc;
1575
1576 // Clean parameters
1577 $this->setUpperOrLowerCase();
1578
1579 $this->civility_code = trim((string) $this->civility_code);
1580 $this->login = trim((string) $this->login);
1581 if (!isset($this->entity)) {
1582 $this->entity = $conf->entity; // If not defined, we use default value
1583 }
1584
1585 dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1586
1587 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1588
1589 // Check parameters
1590 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEMail($this->email)) {
1591 $langs->load("errors");
1592 $this->error = $langs->trans("ErrorBadEMail", $this->email);
1593 return -1;
1594 }
1595 if (empty($this->login)) {
1596 $langs->load("errors");
1597 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1598 return -1;
1599 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1600 $langs->load("errors");
1601 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1602 return -1;
1603 }
1604
1605 $this->datec = dol_now();
1606
1607 $error = 0;
1608 $this->db->begin();
1609
1610 // Check if login already exists in same entity or into entity 0.
1611 if ($this->login) {
1612 $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)."'";
1613 $resqltochecklogin = $this->db->query($sqltochecklogin);
1614 if ($resqltochecklogin) {
1615 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1616 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1617 $langs->load("errors");
1618 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1619 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1620 $this->db->rollback();
1621 return -6;
1622 }
1623 $this->db->free($resqltochecklogin);
1624 }
1625 }
1626 if (!empty($this->email)) {
1627 $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)."'";
1628 $resqltochecklogin = $this->db->query($sqltochecklogin);
1629 if ($resqltochecklogin) {
1630 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1631 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1632 $langs->load("errors");
1633 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1634 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1635 $this->db->rollback();
1636 return -6;
1637 }
1638 $this->db->free($resqltochecklogin);
1639 }
1640 }
1641
1642 // Insert into database
1643 $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, entity)";
1644 $sql .= " VALUES('".$this->db->idate($this->datec)."', '".$this->db->escape($this->login)."', '".$this->db->escape($this->ldap_sid)."', ".((int) $this->entity).")";
1645 $result = $this->db->query($sql);
1646
1647 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1648 if ($result) {
1649 $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1650
1651 // Set default rights
1652 if ($this->set_default_rights() < 0) {
1653 $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1654 $this->db->rollback();
1655 return -5;
1656 }
1657
1658 if (getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && getDolGlobalString('STOCK_USERSTOCK_AUTOCREATE')) {
1659 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1660 $langs->load("stocks");
1661
1662 $entrepot = new Entrepot($this->db);
1663 $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1664 $entrepot->libelle = $entrepot->label; // For backward compatibility
1665 $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1666 $entrepot->statut = 1;
1667 $entrepot->country_id = $mysoc->country_id;
1668
1669 $warehouseid = $entrepot->create($user);
1670
1671 $this->fk_warehouse = $warehouseid;
1672 }
1673
1674 // Update minor fields
1675 $result = $this->update($user, 1, 1);
1676 if ($result < 0) {
1677 $this->db->rollback();
1678 return -4;
1679 }
1680
1681 if (!$notrigger) {
1682 // Call trigger
1683 $result = $this->call_trigger('USER_CREATE', $user);
1684 if ($result < 0) {
1685 $error++;
1686 }
1687 // End call triggers
1688 }
1689
1690 if (!$error) {
1691 $this->db->commit();
1692 return $this->id;
1693 } else {
1694 //$this->error=$interface->error;
1695 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1696 $this->db->rollback();
1697 return -3;
1698 }
1699 } else {
1700 $this->error = $this->db->lasterror();
1701 $this->db->rollback();
1702 return -2;
1703 }
1704 }
1705
1706
1707 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1716 public function create_from_contact($contact, $login = '', $password = '')
1717 {
1718 // phpcs:enable
1719 global $conf, $user, $langs;
1720
1721 $error = 0;
1722
1723 // Define parameters
1724 $this->admin = 0;
1725 $this->civility_code = $contact->civility_code;
1726 $this->lastname = $contact->lastname;
1727 $this->firstname = $contact->firstname;
1728 //$this->gender = $contact->gender; // contact ha sno gender
1729 $this->email = $contact->email;
1730 $this->socialnetworks = $contact->socialnetworks;
1731 $this->office_phone = $contact->phone_pro;
1732 $this->office_fax = $contact->fax;
1733 $this->user_mobile = $contact->phone_mobile;
1734 $this->address = $contact->address;
1735 $this->zip = $contact->zip;
1736 $this->town = $contact->town;
1737 $this->setUpperOrLowerCase();
1738 $this->state_id = $contact->state_id;
1739 $this->country_id = $contact->country_id;
1740 $this->employee = 0;
1741
1742 if (empty($login)) {
1743 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1744 $login = dol_buildlogin($contact->lastname, $contact->firstname);
1745 }
1746 $this->login = $login;
1747
1748 $this->db->begin();
1749
1750 // Create user and set $this->id. Trigger is disabled because executed later.
1751 $result = $this->create($user, 1);
1752 if ($result > 0) {
1753 $sql = "UPDATE ".$this->db->prefix()."user";
1754 $sql .= " SET fk_socpeople=".((int) $contact->id);
1755 $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
1756 if ($contact->socid > 0) {
1757 $sql .= ", fk_soc=".((int) $contact->socid);
1758 }
1759 $sql .= " WHERE rowid=".((int) $this->id);
1760
1761 $resql = $this->db->query($sql);
1762
1763 dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1764 if ($resql) {
1765 $this->context['createfromcontact'] = 'createfromcontact';
1766
1767 // Call trigger
1768 $result = $this->call_trigger('USER_CREATE', $user);
1769 if ($result < 0) {
1770 $error++;
1771 $this->db->rollback();
1772 return -1;
1773 }
1774 // End call triggers
1775
1776 $this->db->commit();
1777 return $this->id;
1778 } else {
1779 $this->error = $this->db->error();
1780
1781 $this->db->rollback();
1782 return -1;
1783 }
1784 } else {
1785 // $this->error deja positionne
1786 dol_syslog(get_class($this)."::create_from_contact - 0");
1787
1788 $this->db->rollback();
1789 return $result;
1790 }
1791 }
1792
1793 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1802 public function create_from_member($member, $login = '')
1803 {
1804 // phpcs:enable
1805 global $conf, $user, $langs;
1806
1807 // Set properties on new user
1808 $this->admin = 0;
1809 $this->civility_code = $member->civility_id;
1810 $this->lastname = $member->lastname;
1811 $this->firstname = $member->firstname;
1812 $this->gender = $member->gender;
1813 $this->email = $member->email;
1814 $this->fk_member = $member->id;
1815 $this->address = $member->address;
1816 $this->zip = $member->zip;
1817 $this->town = $member->town;
1818 $this->setUpperOrLowerCase();
1819 $this->state_id = $member->state_id;
1820 $this->country_id = $member->country_id;
1821 $this->socialnetworks = $member->socialnetworks;
1822
1823 $this->pass = $member->pass;
1824 $this->pass_crypted = $member->pass_indatabase_crypted;
1825
1826 if (empty($login)) {
1827 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1828 $login = dol_buildlogin($member->lastname, $member->firstname);
1829 }
1830 $this->login = $login;
1831
1832 $this->db->begin();
1833
1834 // Create and set $this->id
1835 $result = $this->create($user);
1836 if ($result > 0) {
1837 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
1838 $newpass = $this->setPassword($user, $this->pass);
1839 if (is_int($newpass) && $newpass < 0) {
1840 $result = -2;
1841 }
1842 } elseif (!empty($this->pass_crypted)) { // If a crypted password is already known, we save it directly into database because the previous create did not save it.
1843 $sql = "UPDATE ".$this->db->prefix()."user";
1844 $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
1845 $sql .= " WHERE rowid=".((int) $this->id);
1846
1847 $resql = $this->db->query($sql);
1848 if (!$resql) {
1849 $result = -1;
1850 }
1851 }
1852
1853 if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
1854 $sql = "UPDATE ".$this->db->prefix()."user";
1855 $sql .= " SET fk_soc=".((int) $member->socid);
1856 $sql .= " WHERE rowid=".((int) $this->id);
1857
1858 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
1859 $resql = $this->db->query($sql);
1860 if ($resql) {
1861 $this->db->commit();
1862 return $this->id;
1863 } else {
1864 $this->error = $this->db->lasterror();
1865
1866 $this->db->rollback();
1867 return -1;
1868 }
1869 }
1870 }
1871
1872 if ($result > 0) {
1873 $this->db->commit();
1874 return $this->id;
1875 } else {
1876 // $this->error deja positionne
1877 $this->db->rollback();
1878 return -2;
1879 }
1880 }
1881
1882 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1888 public function set_default_rights()
1889 {
1890 // phpcs:enable
1891 global $conf;
1892
1893 $rd = array();
1894 $num = 0;
1895 $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
1896 $sql .= " WHERE bydefault = 1";
1897 $sql .= " AND entity = ".((int) $conf->entity);
1898
1899 $resql = $this->db->query($sql);
1900 if ($resql) {
1901 $num = $this->db->num_rows($resql);
1902 $i = 0;
1903 while ($i < $num) {
1904 $row = $this->db->fetch_row($resql);
1905 $rd[$i] = $row[0];
1906 $i++;
1907 }
1908 $this->db->free($resql);
1909 }
1910 $i = 0;
1911 while ($i < $num) {
1912 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
1913 $result = $this->db->query($sql);
1914
1915 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
1916 $result = $this->db->query($sql);
1917 if (!$result) {
1918 return -1;
1919 }
1920 $i++;
1921 }
1922
1923 return $i;
1924 }
1925
1936 public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
1937 {
1938 global $conf, $langs;
1939
1940 $nbrowsaffected = 0;
1941 $error = 0;
1942
1943 dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
1944
1945 // Clean parameters
1946 $this->civility_code = trim((string) $this->civility_code);
1947 $this->lastname = trim((string) $this->lastname);
1948 $this->firstname = trim((string) $this->firstname);
1949 $this->ref_employee = trim((string) $this->ref_employee);
1950 $this->national_registration_number = trim((string) $this->national_registration_number);
1951 $this->employee = ($this->employee > 0 ? $this->employee : 0);
1952 $this->login = trim((string) $this->login);
1953 $this->gender = trim((string) $this->gender);
1954
1955 $this->pass = trim((string) $this->pass);
1956 $this->api_key = trim((string) $this->api_key);
1957 $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
1958 $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
1959
1960 $this->address = trim((string) $this->address);
1961 $this->zip = trim((string) $this->zip);
1962 $this->town = trim((string) $this->town);
1963
1964 $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
1965 $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
1966 $this->office_phone = trim((string) $this->office_phone);
1967 $this->office_fax = trim((string) $this->office_fax);
1968 $this->user_mobile = trim((string) $this->user_mobile);
1969 $this->personal_mobile = trim((string) $this->personal_mobile);
1970 $this->email = trim((string) $this->email);
1971 $this->personal_email = trim((string) $this->personal_email);
1972
1973 $this->job = trim((string) $this->job);
1974 $this->signature = trim((string) $this->signature);
1975 $this->note_public = trim((string) $this->note_public);
1976 $this->note_private = trim((string) $this->note_private);
1977 $this->openid = trim((string) $this->openid);
1978 $this->admin = ($this->admin > 0 ? $this->admin : 0);
1979
1980 $this->accountancy_code = trim((string) $this->accountancy_code);
1981 $this->color = trim((string) $this->color);
1982 $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
1983 $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
1984
1985 $this->birth = empty($this->birth) ? '' : $this->birth;
1986 $this->fk_warehouse = (int) $this->fk_warehouse;
1987
1988 $this->setUpperOrLowerCase();
1989
1990 // Check parameters
1991 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1992
1993 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEMail($this->email)) {
1994 $langs->load("errors");
1995 $this->error = $langs->trans("ErrorBadEMail", $this->email);
1996 return -1;
1997 }
1998 if (empty($this->login)) {
1999 $langs->load("errors");
2000 $this->error = $langs->trans("ErrorFieldRequired", 'Login');
2001 return -1;
2002 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
2003 $langs->load("errors");
2004 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
2005 return -1;
2006 }
2007
2008 $this->db->begin();
2009
2010 // Check if login already exists in same entity or into entity 0.
2011 if (!empty($this->oldcopy) && $this->oldcopy->login != $this->login) {
2012 $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)."'";
2013 $resqltochecklogin = $this->db->query($sqltochecklogin);
2014 if ($resqltochecklogin) {
2015 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2016 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2017 $langs->load("errors");
2018 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
2019 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2020 $this->db->rollback();
2021 return -1;
2022 }
2023 }
2024 }
2025 if (!empty($this->oldcopy) && !empty($this->email) && $this->oldcopy->email != $this->email) {
2026 $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)."'";
2027 $resqltochecklogin = $this->db->query($sqltochecklogin);
2028 if ($resqltochecklogin) {
2029 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2030 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2031 $langs->load("errors");
2032 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
2033 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2034 $this->db->rollback();
2035 return -1;
2036 }
2037 }
2038 }
2039
2040 // Update datas
2041 $sql = "UPDATE ".$this->db->prefix()."user SET";
2042 $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
2043 $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
2044 $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
2045 $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
2046 $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
2047 $sql .= ", employee = ".(int) $this->employee;
2048 $sql .= ", login = '".$this->db->escape($this->login)."'";
2049 $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
2050 $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman'
2051 $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
2052 if (!empty($user->admin)) {
2053 $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
2054 }
2055 $sql .= ", address = '".$this->db->escape($this->address)."'";
2056 $sql .= ", zip = '".$this->db->escape($this->zip)."'";
2057 $sql .= ", town = '".$this->db->escape($this->town)."'";
2058 $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".$this->db->escape($this->state_id)."'" : "null");
2059 $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".$this->db->escape($this->country_id)."'" : "null");
2060 $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
2061 $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
2062 $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
2063 $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
2064 $sql .= ", email = '".$this->db->escape($this->email)."'";
2065 $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
2066 $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
2067 $sql .= ", job = '".$this->db->escape($this->job)."'";
2068 $sql .= ", signature = '".$this->db->escape($this->signature)."'";
2069 $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
2070 $sql .= ", color = '".$this->db->escape($this->color)."'";
2071 $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
2072 $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
2073 $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2074 $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2075 $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2076 $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2077 $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2078 $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2079 $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".$this->db->escape($this->fk_user)."'" : "null");
2080 $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".$this->db->escape($this->fk_user_expense_validator)."'" : "null");
2081 $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".$this->db->escape($this->fk_user_holiday_validator)."'" : "null");
2082 if (isset($this->thm) || $this->thm != '') {
2083 $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2084 }
2085 if (isset($this->tjm) || $this->tjm != '') {
2086 $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2087 }
2088 if (isset($this->salary) || $this->salary != '') {
2089 $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2090 }
2091 if (isset($this->salaryextra) || $this->salaryextra != '') {
2092 $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2093 }
2094 $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2095 if (!empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2096 $sql .= ", entity = ".((int) $this->entity); // entity flag can be set/unset only by an another superadmin user
2097 }
2098 $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
2099 $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
2100 $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
2101 $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2102 $sql .= " WHERE rowid = ".((int) $this->id);
2103
2104 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2105 $resql = $this->db->query($sql);
2106 if ($resql) {
2107 $nbrowsaffected += $this->db->affected_rows($resql);
2108
2109 // Update password
2110 if (!empty($this->pass)) {
2111 if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2112 // If a new value for password is set and different than the one crypted into database
2113 $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2114 if (is_int($result) && $result < 0) {
2115 return -5;
2116 }
2117 }
2118 }
2119
2120 // If user is linked to a member, remove old link to this member
2121 if ($this->fk_member > 0) {
2122 dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2123 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2124 $resql = $this->db->query($sql);
2125 if (!$resql) {
2126 $this->error = $this->db->error();
2127 $this->db->rollback();
2128 return -5;
2129 }
2130 }
2131 // Set link to user
2132 dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2133 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2134 $resql = $this->db->query($sql);
2135 if (!$resql) {
2136 $this->error = $this->db->error();
2137 $this->db->rollback();
2138 return -5;
2139 }
2140
2141 if ($nbrowsaffected) { // If something has changed in data
2142 if ($this->fk_member > 0 && !$nosyncmember) {
2143 dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2144
2145 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2146
2147 // This user is linked with a member, so we also update member information
2148 // if this is an update.
2149 $adh = new Adherent($this->db);
2150 $result = $adh->fetch($this->fk_member);
2151
2152 if ($result > 0) {
2153 $adh->civility_code = $this->civility_code;
2154 $adh->firstname = $this->firstname;
2155 $adh->lastname = $this->lastname;
2156 $adh->login = $this->login;
2157 $adh->gender = $this->gender;
2158 $adh->birth = $this->birth;
2159
2160 $adh->pass = $this->pass;
2161
2162 $adh->address = $this->address;
2163 $adh->town = $this->town;
2164 $adh->zip = $this->zip;
2165 $adh->state_id = $this->state_id;
2166 $adh->country_id = $this->country_id;
2167
2168 $adh->email = $this->email;
2169
2170 $adh->socialnetworks = $this->socialnetworks;
2171
2172 $adh->phone = $this->office_phone;
2173 $adh->phone_mobile = $this->user_mobile;
2174
2175 $adh->default_lang = $this->lang;
2176
2177 $adh->user_id = $this->id;
2178 $adh->user_login = $this->login;
2179
2180 $result = $adh->update($user, 0, 1, 0);
2181 if ($result < 0) {
2182 $this->error = $adh->error;
2183 $this->errors = $adh->errors;
2184 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2185 $error++;
2186 }
2187 } elseif ($result < 0) {
2188 $this->error = $adh->error;
2189 $this->errors = $adh->errors;
2190 $error++;
2191 }
2192 }
2193
2194 if ($this->contact_id > 0 && !$nosynccontact) {
2195 dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2196
2197 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2198
2199 // This user is linked with a contact, so we also update contact information if this is an update.
2200 $tmpobj = new Contact($this->db);
2201 $result = $tmpobj->fetch($this->contact_id);
2202
2203 if ($result >= 0) {
2204 $tmpobj->civility_code = $this->civility_code;
2205 $tmpobj->firstname = $this->firstname;
2206 $tmpobj->lastname = $this->lastname;
2207 $tmpobj->login = $this->login;
2208 $tmpobj->gender = $this->gender;
2209 $tmpobj->birth = $this->birth;
2210
2211 //$tmpobj->pass=$this->pass;
2212
2213 $tmpobj->email = $this->email;
2214
2215 $tmpobj->socialnetworks = $this->socialnetworks;
2216
2217 $tmpobj->phone_pro = $this->office_phone;
2218 $tmpobj->phone_mobile = $this->user_mobile;
2219 $tmpobj->fax = $this->office_fax;
2220
2221 $tmpobj->default_lang = $this->lang;
2222
2223 $tmpobj->address = $this->address;
2224 $tmpobj->town = $this->town;
2225 $tmpobj->zip = $this->zip;
2226 $tmpobj->state_id = $this->state_id;
2227 $tmpobj->country_id = $this->country_id;
2228
2229 $tmpobj->user_id = $this->id;
2230 $tmpobj->user_login = $this->login;
2231
2232 $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2233 if ($result < 0) {
2234 $this->error = $tmpobj->error;
2235 $this->errors = $tmpobj->errors;
2236 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2237 $error++;
2238 }
2239 } else {
2240 $this->error = $tmpobj->error;
2241 $this->errors = $tmpobj->errors;
2242 $error++;
2243 }
2244 }
2245 }
2246
2247 $action = 'update';
2248
2249 // Actions on extra fields
2250 if (!$error) {
2251 $result = $this->insertExtraFields();
2252 if ($result < 0) {
2253 $error++;
2254 }
2255 }
2256
2257 if (!$error && !$notrigger) {
2258 // Call trigger
2259 $result = $this->call_trigger('USER_MODIFY', $user);
2260 if ($result < 0) {
2261 $error++;
2262 }
2263 // End call triggers
2264 }
2265
2266 if (!$error) {
2267 $this->db->commit();
2268 return $nbrowsaffected;
2269 } else {
2270 dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2271 $this->db->rollback();
2272 return -1;
2273 }
2274 } else {
2275 $this->error = $this->db->lasterror();
2276 $this->db->rollback();
2277 return -2;
2278 }
2279 }
2280
2281 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2288 public function update_last_login_date()
2289 {
2290 // phpcs:enable
2291 $now = dol_now();
2292
2293 $userremoteip = getUserRemoteIP();
2294
2295 $sql = "UPDATE ".$this->db->prefix()."user SET";
2296 $sql .= " datepreviouslogin = datelastlogin,";
2297 $sql .= " ippreviouslogin = iplastlogin,";
2298 $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2299 $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2300 $sql .= " tms = tms"; // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
2301 $sql .= " WHERE rowid = ".((int) $this->id);
2302
2303 dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2304 $resql = $this->db->query($sql);
2305 if ($resql) {
2306 $this->datepreviouslogin = $this->datelastlogin;
2307 $this->datelastlogin = $now;
2308 $this->ippreviouslogin = $this->iplastlogin;
2309 $this->iplastlogin = $userremoteip;
2310 return 1;
2311 } else {
2312 $this->error = $this->db->lasterror().' sql='.$sql;
2313 return -1;
2314 }
2315 }
2316
2317
2330 public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2331 {
2332 global $conf, $langs;
2333 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2334
2335 $error = 0;
2336
2337 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2338
2339 // If new password not provided, we generate one
2340 if (!$password) {
2341 $password = getRandomPassword(false);
2342 }
2343
2344 // Check and encrypt the password
2345 if (empty($passwordalreadycrypted)) {
2346 if (getDolGlobalString('USER_PASSWORD_GENERATED')) {
2347 // Add a check on rules for password syntax using the setup of the password generator
2348 $modGeneratePassClass = 'modGeneratePass'.ucfirst($conf->global->USER_PASSWORD_GENERATED);
2349
2350 include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2351 if (class_exists($modGeneratePassClass)) {
2352 $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2353
2354 // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2355 $modGeneratePass->WithoutAmbi = 0;
2356
2357 // Call to validatePassword($password) to check pass match rules
2358 $testpassword = $modGeneratePass->validatePassword($password);
2359 if (!$testpassword) {
2360 $this->error = $modGeneratePass->error;
2361 return -1;
2362 }
2363 }
2364 }
2365
2366
2367 // Now, we encrypt the new password
2368 $password_crypted = dol_hash($password);
2369 }
2370
2371 // Update password
2372 if (!$changelater) {
2373 if (!is_object($this->oldcopy)) {
2374 $this->oldcopy = clone $this;
2375 }
2376
2377 $this->db->begin();
2378
2379 $sql = "UPDATE ".$this->db->prefix()."user";
2380 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2381 $sql .= " pass_temp = null";
2382 if (!empty($flagdelsessionsbefore)) {
2383 $sql .= ", flagdelsessionsbefore = '".$this->db->idate(dol_now() - 5, 'gmt')."'";
2384 }
2385 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
2386 $sql .= ", pass = null";
2387 } else {
2388 $sql .= ", pass = '".$this->db->escape($password)."'";
2389 }
2390 $sql .= " WHERE rowid = ".((int) $this->id);
2391
2392 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2393 $result = $this->db->query($sql);
2394 if ($result) {
2395 if ($this->db->affected_rows($result)) {
2396 $this->pass = $password;
2397 $this->pass_indatabase = $password;
2398 $this->pass_indatabase_crypted = $password_crypted;
2399
2400 if ($this->fk_member && !$nosyncmember) {
2401 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2402
2403 // This user is linked with a member, so we also update members informations
2404 // if this is an update.
2405 $adh = new Adherent($this->db);
2406 $result = $adh->fetch($this->fk_member);
2407
2408 if ($result >= 0) {
2409 $result = $adh->setPassword($user, $this->pass, (!getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 0 : 1), 1); // Cryptage non gere dans module adherent
2410 if (is_int($result) && $result < 0) {
2411 $this->error = $adh->error;
2412 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2413 $error++;
2414 }
2415 } else {
2416 $this->error = $adh->error;
2417 $error++;
2418 }
2419 }
2420
2421 dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2422
2423 if (!$error && !$notrigger) {
2424 // Call trigger
2425 $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2426 if ($result < 0) {
2427 $error++;
2428 $this->db->rollback();
2429 return -1;
2430 }
2431 // End call triggers
2432 }
2433
2434 $this->db->commit();
2435 return $this->pass;
2436 } else {
2437 $this->db->rollback();
2438 return 0;
2439 }
2440 } else {
2441 $this->db->rollback();
2442 dol_print_error($this->db);
2443 return -1;
2444 }
2445 } else {
2446 // We store password in password temporary field.
2447 // After receiving confirmation link, we will erase and store it in pass_crypted
2448 $sql = "UPDATE ".$this->db->prefix()."user";
2449 $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2450 $sql .= " WHERE rowid = ".((int) $this->id);
2451
2452 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2453 $result = $this->db->query($sql);
2454 if ($result) {
2455 return $password;
2456 } else {
2457 dol_print_error($this->db);
2458 return -3;
2459 }
2460 }
2461 }
2462
2463 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2472 public function send_password($user, $password = '', $changelater = 0)
2473 {
2474 // phpcs:enable
2475 global $conf, $langs, $mysoc;
2476 global $dolibarr_main_url_root;
2477
2478 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2479
2480 $msgishtml = 0;
2481
2482 // Define $msg
2483 $mesg = '';
2484
2485 $outputlangs = new Translate("", $conf);
2486
2487 if (isset($this->conf->MAIN_LANG_DEFAULT)
2488 && $this->conf->MAIN_LANG_DEFAULT != 'auto') { // If user has defined its own language (rare because in most cases, auto is used)
2489 $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2490 }
2491
2492 if ($this->conf->MAIN_LANG_DEFAULT) {
2493 $outputlangs->setDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2494 } else { // If user has not defined its own language, we used current language
2495 $outputlangs = $langs;
2496 }
2497
2498 // Load translation files required by the page
2499 $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2500
2501 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', constant('DOL_APPLICATION_TITLE'));
2502
2503 $subject = '['.$appli.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2504
2505 // Define $urlwithroot
2506 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2507 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2508
2509 if (!$changelater) {
2510 $url = $urlwithroot.'/';
2511 if (getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD')) {
2512 $url = $conf->global->URL_REDIRECTION_AFTER_CHANGEPASSWORD;
2513 }
2514
2515 dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2516
2517 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2518 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2519 $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2520 $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2521 $mesg .= "\n";
2522
2523 $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2524 $mesg .= "--\n";
2525 $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2526 } else {
2527 //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2528 $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2529 $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2530 if (isModEnabled('multicompany')) {
2531 $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2532 }
2533
2534 dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2535
2536 $msgishtml = 1;
2537
2538 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2539 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2540 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2541 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2542 $mesg .= "<br>\n";
2543 $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2544 $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2545 $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2546 }
2547
2548 $trackid = 'use'.$this->id;
2549 $sendcontext = 'password';
2550
2551 $mailfile = new CMailFile(
2552 $subject,
2553 $this->email,
2554 $conf->global->MAIN_MAIL_EMAIL_FROM,
2555 $mesg,
2556 array(),
2557 array(),
2558 array(),
2559 '',
2560 '',
2561 0,
2562 $msgishtml,
2563 '',
2564 '',
2565 $trackid,
2566 '',
2567 $sendcontext
2568 );
2569
2570 if ($mailfile->sendfile()) {
2571 return 1;
2572 } else {
2573 $langs->trans("errors");
2574 $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2575 return -1;
2576 }
2577 }
2578
2584 public function error()
2585 {
2586 return $this->error;
2587 }
2588
2589
2590 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2596 public function fetch_clicktodial()
2597 {
2598 // phpcs:enable
2599 $sql = "SELECT url, login, pass, poste ";
2600 $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2601 $sql .= " WHERE u.fk_user = ".((int) $this->id);
2602
2603 $resql = $this->db->query($sql);
2604 if ($resql) {
2605 if ($this->db->num_rows($resql)) {
2606 $obj = $this->db->fetch_object($resql);
2607
2608 $this->clicktodial_url = $obj->url;
2609 $this->clicktodial_login = $obj->login;
2610 $this->clicktodial_password = $obj->pass;
2611 $this->clicktodial_poste = $obj->poste;
2612 }
2613
2614 $this->clicktodial_loaded = 1; // Data loaded (found or not)
2615
2616 $this->db->free($resql);
2617 return 1;
2618 } else {
2619 $this->error = $this->db->error();
2620 return -1;
2621 }
2622 }
2623
2624 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2630 public function update_clicktodial()
2631 {
2632 // phpcs:enable
2633 $this->db->begin();
2634
2635 $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2636 $sql .= " WHERE fk_user = ".((int) $this->id);
2637
2638 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2639 $result = $this->db->query($sql);
2640
2641 $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
2642 $sql .= " (fk_user,url,login,pass,poste)";
2643 $sql .= " VALUES (".$this->id;
2644 $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2645 $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2646 $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2647 $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2648
2649 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2650 $result = $this->db->query($sql);
2651 if ($result) {
2652 $this->db->commit();
2653 return 1;
2654 } else {
2655 $this->db->rollback();
2656 $this->error = $this->db->lasterror();
2657 return -1;
2658 }
2659 }
2660
2661
2662 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2671 public function SetInGroup($group, $entity, $notrigger = 0)
2672 {
2673 // phpcs:enable
2674 global $conf, $langs, $user;
2675
2676 $error = 0;
2677
2678 $this->db->begin();
2679
2680 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2681 $sql .= " WHERE fk_user = ".((int) $this->id);
2682 $sql .= " AND fk_usergroup = ".((int) $group);
2683 $sql .= " AND entity = ".((int) $entity);
2684
2685 $result = $this->db->query($sql);
2686
2687 $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
2688 $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
2689
2690 $result = $this->db->query($sql);
2691 if ($result) {
2692 if (!$error && !$notrigger) {
2693 $this->context = array('audit'=>$langs->trans("UserSetInGroup"), 'newgroupid'=>$group);
2694
2695 // Call trigger
2696 $result = $this->call_trigger('USER_MODIFY', $user);
2697 if ($result < 0) {
2698 $error++;
2699 }
2700 // End call triggers
2701 }
2702
2703 if (!$error) {
2704 $this->db->commit();
2705 return 1;
2706 } else {
2707 dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2708 $this->db->rollback();
2709 return -2;
2710 }
2711 } else {
2712 $this->error = $this->db->lasterror();
2713 $this->db->rollback();
2714 return -1;
2715 }
2716 }
2717
2718 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2727 public function RemoveFromGroup($group, $entity, $notrigger = 0)
2728 {
2729 // phpcs:enable
2730 global $conf, $langs, $user;
2731
2732 $error = 0;
2733
2734 $this->db->begin();
2735
2736 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2737 $sql .= " WHERE fk_user = ".((int) $this->id);
2738 $sql .= " AND fk_usergroup = ".((int) $group);
2739 if (empty($entity)) {
2740 $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
2741 } else {
2742 $sql .= " AND entity = ".((int) $entity);
2743 }
2744
2745 $result = $this->db->query($sql);
2746 if ($result) {
2747 if (!$error && !$notrigger) {
2748 $this->context = array('audit'=>$langs->trans("UserRemovedFromGroup"), 'oldgroupid'=>$group);
2749
2750 // Call trigger
2751 $result = $this->call_trigger('USER_MODIFY', $user);
2752 if ($result < 0) {
2753 $error++;
2754 }
2755 // End call triggers
2756 }
2757
2758 if (!$error) {
2759 $this->db->commit();
2760 return 1;
2761 } else {
2762 dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2763 $this->db->rollback();
2764 return -2;
2765 }
2766 } else {
2767 $this->error = $this->db->lasterror();
2768 $this->db->rollback();
2769 return -1;
2770 }
2771 }
2772
2773
2781 {
2782 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2783
2784 $now = dol_now();
2785
2786 //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
2787
2788 // Check date start validity
2789 if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
2790 return 1;
2791 }
2792 // Check date end validity
2793 if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
2794 return 1;
2795 }
2796
2797 return 0;
2798 }
2799
2800
2811 public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
2812 {
2813 $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2814 $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
2815 $result .= '</a>';
2816
2817 return $result;
2818 }
2819
2827 public function getTooltipContentArray($params)
2828 {
2829 global $conf, $langs, $menumanager;
2830 global $dolibarr_main_demo;
2831
2832 $infologin = $params['infologin'] ?? 0;
2833 $option = $params['option'] ?? '';
2834
2835 $datas = [];
2836 if (!empty($this->photo)) {
2837 $photo = '<div class="photointooltip floatright">';
2838 $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
2839 $photo .= '</div>';
2840 $datas['photo'] = $photo;
2841 //$label .= '<div style="clear: both;"></div>';
2842 }
2843
2844 // Info Login
2845 $datas['opendiv'] = '<div class="centpercent divtooltip">';
2846 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
2847 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs, ''));
2848 if (!empty($this->login)) {
2849 $datas['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
2850 }
2851 if (!empty($this->job)) {
2852 $datas['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
2853 }
2854 $datas['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
2855 if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
2856 $phonelist = array();
2857 if ($this->office_phone) {
2858 $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2859 }
2860 if ($this->office_fax) {
2861 $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2862 }
2863 if ($this->user_mobile) {
2864 $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
2865 }
2866 $datas['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
2867 }
2868 if (!empty($this->admin)) {
2869 $datas['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
2870 }
2871 if (!empty($this->accountancy_code) || $option == 'accountancy') {
2872 $langs->load("companies");
2873 $datas['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
2874 }
2875 $company = '';
2876 if (!empty($this->socid)) { // Add thirdparty for external users
2877 $thirdpartystatic = new Societe($this->db);
2878 $thirdpartystatic->fetch($this->socid);
2879 $companyimg = '';
2880 if (empty($params['hidethirdpartylogo'])) {
2881 $companyimg = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2882 }
2883 $company = ' ('.$langs->trans("Company").': '.($companyimg ? $companyimg : img_picto('', 'company')).' '.dol_string_nohtmltag($thirdpartystatic->name).')';
2884 }
2885 $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
2886 $datas['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
2887 $datas['closediv'] = '</div>';
2888
2889 if ($infologin > 0) {
2890 $datas['newlinelogin'] = '<br>';
2891 $datas['session'] = '<br><u>'.$langs->trans("Session").'</u>';
2892 $datas['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
2893 if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
2894 $datas['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
2895 }
2896 $datas['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
2897 $datas['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
2898 $datas['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
2899 $datas['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
2900 $datas['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
2901 $s = picto_from_langcode($langs->getDefaultLang());
2902 $datas['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
2903 $datas['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
2904 $datas['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
2905 $datas['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
2906 if ($conf->browser->layout == 'phone') {
2907 $datas['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
2908 }
2909 if (!empty($_SESSION["disablemodules"])) {
2910 $datas['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(join(', ', explode(',', $_SESSION["disablemodules"])));
2911 }
2912 }
2913
2914 return $datas;
2915 }
2916
2932 public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
2933 {
2934 global $langs, $conf, $db, $hookmanager, $user;
2935 global $dolibarr_main_authentication, $dolibarr_main_demo;
2936
2937 if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
2938 $option = 'nolink';
2939 }
2940
2941 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
2942 $withpictoimg = 0;
2943 }
2944
2945 $result = '';
2946 $params = [
2947 'id' => $this->id,
2948 'objecttype' => $this->element,
2949 'infologin' => $infologin,
2950 'option' => $option,
2951 ];
2952 $classfortooltip = 'classfortooltip';
2953 $dataparams = '';
2954 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2955 $classfortooltip = 'classforajaxtooltip';
2956 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2957 $label = '';
2958 } else {
2959 $label = implode($this->getTooltipContentArray($params));
2960 }
2961
2962 $companylink = '';
2963 if (!empty($this->socid)) { // Add thirdparty for external users
2964 $thirdpartystatic = new Societe($this->db);
2965 $thirdpartystatic->fetch($this->socid);
2966 if (empty($hidethirdpartylogo)) {
2967 $companylink = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2968 }
2969 }
2970
2971 if ($infologin < 0) {
2972 $label = '';
2973 }
2974
2975 $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id;
2976 if ($option == 'leave') {
2977 $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id;
2978 }
2979
2980 if ($option != 'nolink') {
2981 // Add param to save lastsearch_values or not
2982 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2983 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2984 $add_save_lastsearch_values = 1;
2985 }
2986 if ($add_save_lastsearch_values) {
2987 $url .= '&save_lastsearch_values=1';
2988 }
2989 }
2990
2991 $linkstart = '<a href="'.$url.'"';
2992 $linkclose = "";
2993 if (empty($notooltip)) {
2994 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2995 $langs->load("users");
2996 $label = $langs->trans("ShowUser");
2997 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2998 }
2999 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3000 $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
3001 } else {
3002 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
3003 }
3004
3005 $linkstart .= $linkclose.'>';
3006 $linkend = '</a>';
3007
3008 //if ($withpictoimg == -1) $result.='<div class="nowrap">';
3009 $result .= (($option == 'nolink') ? '' : $linkstart);
3010 if ($withpictoimg) {
3011 $paddafterimage = '';
3012 if (abs((int) $withpictoimg) == 1) {
3013 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3014 }
3015 // Only picto
3016 if ($withpictoimg > 0) {
3017 $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>';
3018 } else {
3019 // Picto must be a photo
3020 $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>';
3021 }
3022 $result .= $picto;
3023 }
3024 if ($withpictoimg > -2 && $withpictoimg != 2) {
3025 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3026 $result .= '<span class="nopadding usertext'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
3027 }
3028 if ($mode == 'login') {
3029 $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
3030 } else {
3031 $result .= dol_string_nohtmltag($this->getFullName($langs, '', ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
3032 }
3033 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3034 $result .= '</span>';
3035 }
3036 }
3037 $result .= (($option == 'nolink') ? '' : $linkend);
3038 //if ($withpictoimg == -1) $result.='</div>';
3039
3040 $result .= $companylink;
3041
3042 global $action;
3043 $hookmanager->initHooks(array('userdao'));
3044 $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
3045 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3046 if ($reshook > 0) {
3047 $result = $hookmanager->resPrint;
3048 } else {
3049 $result .= $hookmanager->resPrint;
3050 }
3051
3052 return $result;
3053 }
3054
3064 public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
3065 {
3066 global $langs, $user;
3067
3068 $result = '';
3069
3070 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3071 $linkend = '</a>';
3072
3073 //Check user's rights to see an other user
3074 if ((!$user->hasRight('user', 'user', 'lire') && $this->id != $user->id)) {
3075 $option = 'nolink';
3076 }
3077
3078 if ($option == 'xxx') {
3079 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3080 $linkend = '</a>';
3081 }
3082
3083 if ($option == 'nolink') {
3084 $linkstart = '';
3085 $linkend = '';
3086 }
3087
3088 $result .= $linkstart;
3089 if ($withpictoimg) {
3090 $paddafterimage = '';
3091 if (abs($withpictoimg) == 1) {
3092 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3093 }
3094 // Only picto
3095 if ($withpictoimg > 0) {
3096 $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3097 } else {
3098 // Picto must be a photo
3099 $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>';
3100 }
3101 $result .= $picto;
3102 }
3103 $result .= $this->login;
3104 $result .= $linkend;
3105
3106 return $result;
3107 }
3108
3115 public function getLibStatut($mode = 0)
3116 {
3117 return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3118 }
3119
3120 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3128 public function LibStatut($status, $mode = 0)
3129 {
3130 // phpcs:enable
3131 global $langs;
3132
3133 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3134 global $langs;
3135 //$langs->load("mymodule");
3136 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3137 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3138 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3139 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3140 }
3141
3142 $statusType = 'status5';
3143 if ($status == self::STATUS_ENABLED) {
3144 $statusType = 'status4';
3145 }
3146
3147 $label = $this->labelStatus[$status];
3148 $labelshort = $this->labelStatusShort[$status];
3149
3150 $now = dol_now();
3151 if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3152 $statusType = 'status3';
3153 $label .= ' ('.$langs->trans("UserNotYetValid").')';
3154 }
3155 if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3156 $statusType = 'status2';
3157 $label .= ' ('.$langs->trans("UserExpired").')';
3158 }
3159
3160 return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3161 }
3162
3163
3171 public function getKanbanView($option = '', $arraydata = null)
3172 {
3173 global $langs;
3174
3175 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3176
3177 $return = '<div class="box-flex-item box-flex-grow-zero">';
3178 $return .= '<div class="info-box info-box-sm">';
3179 $return .= '<span class="info-box-icon bg-infobox-action">';
3180
3181 $label = '';
3182 if (!empty($this->photo)) {
3183 //$label .= '<div class="photointooltip floatright">';
3184 $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
3185 //$label .= '</div>';
3186 //$label .= '<div style="clear: both;"></div>';
3187 $return .= $label;
3188 } else {
3189 $return .= img_picto('', $this->picto);
3190 }
3191
3192 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3193 $return .= '</span>';
3194 $return .= '<div class="info-box-content">';
3195 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3196 if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3197 $return .= img_picto($langs->trans("SuperAdministratorDesc"), 'redstar', 'class="valignmiddle paddingright paddingleft"');
3198 } elseif ($this->admin) {
3199 $return .= img_picto($langs->trans("AdministratorDesc"), 'star', 'class="valignmiddle paddingright paddingleft"');
3200 }
3201 $return .= '</span>';
3202 if ($selected >= 0) {
3203 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3204 }
3205 if (property_exists($this, 'label')) {
3206 $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3207 }
3208 if ($this->email) {
3209 $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3210 }
3211 if (method_exists($this, 'getLibStatut')) {
3212 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3213 }
3214 $return .= '</div>';
3215 $return .= '</div>';
3216 $return .= '</div>';
3217
3218 return $return;
3219 }
3220
3221
3222 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3223 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3233 public function _load_ldap_dn($info, $mode = 0)
3234 {
3235 // phpcs:enable
3236 global $conf;
3237 $dn = '';
3238 if ($mode == 0) {
3239 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')]."," . getDolGlobalString('LDAP_USER_DN');
3240 } elseif ($mode == 1) {
3241 $dn = $conf->global->LDAP_USER_DN;
3242 } elseif ($mode == 2) {
3243 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')];
3244 }
3245 return $dn;
3246 }
3247
3248 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3249 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3255 public function _load_ldap_info()
3256 {
3257 // phpcs:enable
3258 global $conf, $langs;
3259
3260 $info = array();
3261
3262 $socialnetworks = getArrayOfSocialNetworks();
3263
3264 $keymodified = false;
3265
3266 // Object classes
3267 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_USER_OBJECT_CLASS'));
3268
3269 $this->fullname = $this->getFullName($langs);
3270
3271 // Possible LDAP KEY (constname => varname)
3272 $ldapkey = array(
3273 'LDAP_FIELD_FULLNAME' => 'fullname',
3274 'LDAP_FIELD_NAME' => 'lastname',
3275 'LDAP_FIELD_FIRSTNAME' => 'firstname',
3276 'LDAP_FIELD_LOGIN' => 'login',
3277 'LDAP_FIELD_LOGIN_SAMBA'=> 'login',
3278 'LDAP_FIELD_PHONE' => 'office_phone',
3279 'LDAP_FIELD_MOBILE' => 'user_mobile',
3280 'LDAP_FIELD_FAX' => 'office_fax',
3281 'LDAP_FIELD_MAIL' => 'email',
3282 'LDAP_FIELD_SID' => 'ldap_sid',
3283 );
3284
3285 // Champs
3286 foreach ($ldapkey as $constname => $varname) {
3287 if (!empty($this->$varname) && getDolGlobalString($constname)) {
3288 $info[getDolGlobalString($constname)] = $this->$varname;
3289
3290 // Check if it is the LDAP key and if its value has been changed
3291 if (getDolGlobalString('LDAP_KEY_USERS') && $conf->global->LDAP_KEY_USERS == getDolGlobalString($constname)) {
3292 if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
3293 $keymodified = true; // For check if LDAP key has been modified
3294 }
3295 }
3296 }
3297 }
3298 foreach ($socialnetworks as $key => $value) {
3299 if (!empty($this->socialnetworks[$value['label']]) && getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))) {
3300 $info[getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3301 }
3302 }
3303 if ($this->address && getDolGlobalString('LDAP_FIELD_ADDRESS')) {
3304 $info[getDolGlobalString('LDAP_FIELD_ADDRESS')] = $this->address;
3305 }
3306 if ($this->zip && getDolGlobalString('LDAP_FIELD_ZIP')) {
3307 $info[getDolGlobalString('LDAP_FIELD_ZIP')] = $this->zip;
3308 }
3309 if ($this->town && getDolGlobalString('LDAP_FIELD_TOWN')) {
3310 $info[getDolGlobalString('LDAP_FIELD_TOWN')] = $this->town;
3311 }
3312 if ($this->note_public && getDolGlobalString('LDAP_FIELD_DESCRIPTION')) {
3313 $info[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_public, 2);
3314 }
3315 if ($this->socid > 0) {
3316 $soc = new Societe($this->db);
3317 $soc->fetch($this->socid);
3318
3319 $info[getDolGlobalString('LDAP_FIELD_COMPANY')] = $soc->name;
3320 if ($soc->client == 1) {
3321 $info["businessCategory"] = "Customers";
3322 }
3323 if ($soc->client == 2) {
3324 $info["businessCategory"] = "Prospects";
3325 }
3326 if ($soc->fournisseur == 1) {
3327 $info["businessCategory"] = "Suppliers";
3328 }
3329 }
3330
3331 // When password is modified
3332 if (!empty($this->pass)) {
3333 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3334 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass; // this->pass = mot de passe non crypte
3335 }
3336 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3337 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3338 }
3339 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3340 // Set LDAP password if possible
3341 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3342 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
3343 // Just for the default MD5 !
3344 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) {
3345 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3346 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3347 }
3348 }
3349 } elseif (!empty($this->pass_indatabase)) {
3350 // Use $this->pass_indatabase value if exists
3351 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3352 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte
3353 }
3354 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3355 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3356 }
3357 }
3358 }
3359
3360 if (getDolGlobalString('LDAP_SERVER_TYPE') == 'egroupware') {
3361 $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3362
3363 $info['uidnumber'] = $this->id;
3364
3365 $info['phpgwTz'] = 0;
3366 $info['phpgwMailType'] = 'INTERNET';
3367 $info['phpgwMailHomeType'] = 'INTERNET';
3368
3369 $info["phpgwContactTypeId"] = 'n';
3370 $info["phpgwContactCatId"] = 0;
3371 $info["phpgwContactAccess"] = "public";
3372
3373 if (dol_strlen($this->egroupware_id) == 0) {
3374 $this->egroupware_id = 1;
3375 }
3376
3377 $info["phpgwContactOwner"] = $this->egroupware_id;
3378
3379 if ($this->email) {
3380 $info["rfc822Mailbox"] = $this->email;
3381 }
3382 if ($this->user_mobile) {
3383 $info["phpgwCellTelephoneNumber"] = $this->user_mobile;
3384 }
3385 }
3386
3387 if (getDolGlobalString('LDAP_FIELD_USERID')) {
3388 $info[getDolGlobalString('LDAP_FIELD_USERID')] = $this->id;
3389 }
3390 if (getDolGlobalString('LDAP_FIELD_GROUPID')) {
3391 $usergroup = new UserGroup($this->db);
3392 $groupslist = $usergroup->listGroupsForUser($this->id);
3393 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = '65534';
3394 if (!empty($groupslist)) {
3395 foreach ($groupslist as $groupforuser) {
3396 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = $groupforuser->id; //Select first group in list
3397 break;
3398 }
3399 }
3400 }
3401 if (getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY') && getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')) {
3402 $info[getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY')] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->login";
3403 }
3404
3405 return $info;
3406 }
3407
3408
3416 public function initAsSpecimen()
3417 {
3418 global $user, $langs;
3419
3420 $now = dol_now();
3421
3422 // Initialise parametres
3423 $this->id = 0;
3424 $this->ref = 'SPECIMEN';
3425 $this->specimen = 1;
3426
3427 $this->lastname = 'DOLIBARR';
3428 $this->firstname = 'SPECIMEN';
3429 $this->gender = 'man';
3430 $this->note_public = 'This is a note public';
3431 $this->note_private = 'This is a note private';
3432 $this->email = 'email@specimen.com';
3433 $this->personal_email = 'personalemail@specimen.com';
3434 $this->socialnetworks = array(
3435 'skype' => 'skypepseudo',
3436 'twitter' => 'twitterpseudo',
3437 'facebook' => 'facebookpseudo',
3438 'linkedin' => 'linkedinpseudo',
3439 );
3440 $this->office_phone = '0999999999';
3441 $this->office_fax = '0999999998';
3442 $this->user_mobile = '0999999997';
3443 $this->personal_mobile = '0999999996';
3444 $this->admin = 0;
3445 $this->login = 'dolibspec';
3446 $this->pass = 'dolibSpec+@123';
3447 //$this->pass_indatabase='dolibspec'; Set after a fetch
3448 //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3449 $this->datec = $now;
3450 $this->datem = $now;
3451
3452 $this->datelastlogin = $now;
3453 $this->iplastlogin = '127.0.0.1';
3454 $this->datepreviouslogin = $now;
3455 $this->ippreviouslogin = '127.0.0.1';
3456 $this->statut = 1; // deprecated
3457 $this->status = 1;
3458
3459 $this->entity = 1;
3460 return 1;
3461 }
3462
3469 public function info($id)
3470 {
3471 $sql = "SELECT u.rowid, u.login as ref, u.datec,";
3472 $sql .= " u.tms as date_modification, u.entity";
3473 $sql .= " FROM ".$this->db->prefix()."user as u";
3474 $sql .= " WHERE u.rowid = ".((int) $id);
3475
3476 $result = $this->db->query($sql);
3477 if ($result) {
3478 if ($this->db->num_rows($result)) {
3479 $obj = $this->db->fetch_object($result);
3480
3481 $this->id = $obj->rowid;
3482
3483 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3484 $this->date_creation = $this->db->jdate($obj->datec);
3485 $this->date_modification = $this->db->jdate($obj->date_modification);
3486 $this->entity = $obj->entity;
3487 }
3488
3489 $this->db->free($result);
3490 } else {
3491 dol_print_error($this->db);
3492 }
3493 }
3494
3495
3501 public function getNbOfEMailings()
3502 {
3503 $sql = "SELECT count(mc.email) as nb";
3504 $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3505 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3506 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes
3507
3508 $resql = $this->db->query($sql);
3509 if ($resql) {
3510 $obj = $this->db->fetch_object($resql);
3511 $nb = $obj->nb;
3512
3513 $this->db->free($resql);
3514 return $nb;
3515 } else {
3516 $this->error = $this->db->error();
3517 return -1;
3518 }
3519 }
3520
3529 public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3530 {
3531 global $conf;
3532
3533 $sql = "SELECT count(rowid) as nb";
3534 $sql .= " FROM ".$this->db->prefix()."user";
3535 if ($option == 'superadmin') {
3536 $sql .= " WHERE entity = 0";
3537 } else {
3538 $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3539 if ($limitTo == 'active') {
3540 $sql .= " AND statut = 1";
3541 }
3542 }
3543 if ($admin >= 0) {
3544 $sql .= " AND admin = ".(int) $admin;
3545 }
3546
3547 $resql = $this->db->query($sql);
3548 if ($resql) {
3549 $obj = $this->db->fetch_object($resql);
3550 $nb = (int) $obj->nb;
3551
3552 $this->db->free($resql);
3553 return $nb;
3554 } else {
3555 $this->error = $this->db->lasterror();
3556 return -1;
3557 }
3558 }
3559
3560 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3567 public function update_ldap2dolibarr(&$ldapuser)
3568 {
3569 // phpcs:enable
3570 // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3571 global $user, $conf;
3572
3573 $socialnetworks = getArrayOfSocialNetworks();
3574
3575 $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3576 $this->firstname = $ldapuser->$tmpvar;
3577 $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3578 $this->lastname = $ldapuser->$tmpvar;
3579 $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3580 $this->login = $ldapuser->$tmpvar;
3581 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3582 $this->pass = $ldapuser->$tmpvar;
3583 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3584 $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3585
3586 $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3587 $this->office_phone = $ldapuser->$tmpvar;
3588 $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3589 $this->user_mobile = $ldapuser->$tmpvar;
3590 $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3591 $this->office_fax = $ldapuser->$tmpvar;
3592 $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3593 $this->email = $ldapuser->$tmpvar;
3594 foreach ($socialnetworks as $key => $value) {
3595 $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3596 $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3597 }
3598 $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3599 $this->ldap_sid = $ldapuser->$tmpvar;
3600
3601 $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3602 $this->job = $ldapuser->$tmpvar;
3603 $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3604 $this->note_public = $ldapuser->$tmpvar;
3605
3606 $result = $this->update($user);
3607
3608 dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3609
3610 return $result;
3611 }
3612
3613
3614 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3621 public function get_children()
3622 {
3623 // phpcs:enable
3624 $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3625 $sql .= " WHERE fk_user = ".((int) $this->id);
3626
3627 dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3628 $res = $this->db->query($sql);
3629 if ($res) {
3630 $users = array();
3631 while ($rec = $this->db->fetch_array($res)) {
3632 $user = new User($this->db);
3633 $user->fetch($rec['rowid']);
3634 $users[] = $user;
3635 }
3636 return $users;
3637 } else {
3638 dol_print_error($this->db);
3639 return -1;
3640 }
3641 }
3642
3643
3649 private function loadParentOf()
3650 {
3651 global $conf;
3652
3653 $this->parentof = array();
3654
3655 // Load array[child]=parent
3656 $sql = "SELECT fk_user as id_parent, rowid as id_son";
3657 $sql .= " FROM ".$this->db->prefix()."user";
3658 $sql .= " WHERE fk_user <> 0";
3659 $sql .= " AND entity IN (".getEntity('user').")";
3660
3661 dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3662 $resql = $this->db->query($sql);
3663 if ($resql) {
3664 while ($obj = $this->db->fetch_object($resql)) {
3665 $this->parentof[$obj->id_son] = $obj->id_parent;
3666 }
3667 return 1;
3668 } else {
3669 dol_print_error($this->db);
3670 return -1;
3671 }
3672 }
3673
3674 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3688 public function get_full_tree($deleteafterid = 0, $filter = '')
3689 {
3690 // phpcs:enable
3691 global $conf, $user;
3692 global $hookmanager;
3693
3694 // Actions hooked (by external module)
3695 $hookmanager->initHooks(array('userdao'));
3696
3697 $this->users = array();
3698
3699 // Init this->parentof that is array(id_son=>id_parent, ...)
3700 $this->loadParentOf();
3701
3702 // Init $this->users array
3703 $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
3704 $sql .= " FROM ".$this->db->prefix()."user as u";
3705 // Add fields from hooks
3706 $parameters = array();
3707 $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3708 if ($reshook > 0) {
3709 $sql .= $hookmanager->resPrint;
3710 } else {
3711 $sql .= " WHERE u.entity IN (".getEntity('user').")";
3712 }
3713 if ($filter) {
3714 $sql .= " AND ".$filter;
3715 }
3716
3717 dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3718 $resql = $this->db->query($sql);
3719 if ($resql) {
3720 $i = 0;
3721 while ($obj = $this->db->fetch_object($resql)) {
3722 $this->users[$obj->rowid]['rowid'] = $obj->rowid;
3723 $this->users[$obj->rowid]['id'] = $obj->rowid;
3724 $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
3725 $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
3726 $this->users[$obj->rowid]['firstname'] = $obj->firstname;
3727 $this->users[$obj->rowid]['lastname'] = $obj->lastname;
3728 $this->users[$obj->rowid]['login'] = $obj->login;
3729 $this->users[$obj->rowid]['statut'] = $obj->statut;
3730 $this->users[$obj->rowid]['entity'] = $obj->entity;
3731 $this->users[$obj->rowid]['email'] = $obj->email;
3732 $this->users[$obj->rowid]['gender'] = $obj->gender;
3733 $this->users[$obj->rowid]['admin'] = $obj->admin;
3734 $this->users[$obj->rowid]['photo'] = $obj->photo;
3735 $i++;
3736 }
3737 } else {
3738 dol_print_error($this->db);
3739 return -1;
3740 }
3741
3742 // We add the fullpath property to each elements of first level (no parent exists)
3743 dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3744 foreach ($this->users as $key => $val) {
3745 $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3746 if ($result < 0) {
3747 $this->error = 'ErrorLoopInHierarchy';
3748 return -1;
3749 }
3750 }
3751
3752 // Exclude leaf including $deleteafterid from tree
3753 if ($deleteafterid) {
3754 //print "Look to discard user ".$deleteafterid."\n";
3755 $keyfilter1 = '^'.$deleteafterid.'$';
3756 $keyfilter2 = '_'.$deleteafterid.'$';
3757 $keyfilter3 = '^'.$deleteafterid.'_';
3758 $keyfilter4 = '_'.$deleteafterid.'_';
3759 foreach ($this->users as $key => $val) {
3760 if (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath'])
3761 || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])) {
3762 unset($this->users[$key]);
3763 }
3764 }
3765 }
3766
3767 dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
3768 $this->users = dol_sort_array($this->users, 'fullname', 'asc', true, false, 1);
3769
3770 //var_dump($this->users);
3771
3772 return $this->users;
3773 }
3774
3783 public function getAllChildIds($addcurrentuser = 0)
3784 {
3785 $childids = array();
3786
3787 if (isset($this->cache_childids[$this->id])) {
3788 $childids = $this->cache_childids[$this->id];
3789 } else {
3790 // Init this->users
3791 $this->get_full_tree();
3792
3793 $idtoscan = $this->id;
3794
3795 dol_syslog("Build childid for id = ".$idtoscan);
3796 foreach ($this->users as $id => $val) {
3797 //var_dump($val['fullpath']);
3798 if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
3799 $childids[$val['id']] = $val['id'];
3800 }
3801 }
3802 }
3803 $this->cache_childids[$this->id] = $childids;
3804
3805 if ($addcurrentuser) {
3806 $childids[$this->id] = $this->id;
3807 }
3808
3809 return $childids;
3810 }
3811
3812 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3821 public function build_path_from_id_user($id_user, $protection = 0)
3822 {
3823 // phpcs:enable
3824 //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
3825
3826 if (!empty($this->users[$id_user]['fullpath'])) {
3827 // Already defined
3828 dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
3829 return 0;
3830 }
3831
3832 // Define fullpath and fullname
3833 $this->users[$id_user]['fullpath'] = '_'.$id_user;
3834 $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
3835 $i = 0;
3836 $cursor_user = $id_user;
3837
3838 $useridfound = array($id_user);
3839 while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) {
3840 if (in_array($this->parentof[$cursor_user], $useridfound)) {
3841 dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
3842 return -1; // Should not happen. Protection against looping hierarchy
3843 }
3844 $useridfound[] = $this->parentof[$cursor_user];
3845 $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
3846 $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
3847 $i++;
3848 $cursor_user = $this->parentof[$cursor_user];
3849 }
3850
3851 // We count number of _ to have level
3852 $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
3853
3854 return 1;
3855 }
3856
3865 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3866 {
3867 $tables = array(
3868 'user',
3869 );
3870
3871 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3872 }
3873
3874
3875 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3881 public function load_state_board()
3882 {
3883 // phpcs:enable
3884 global $conf;
3885
3886 $this->nb = array();
3887
3888 $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
3889 $sql .= " FROM ".$this->db->prefix()."user as u";
3890 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
3891 $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
3892 $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
3893 $sql .= " AND ug.fk_user = u.rowid";
3894 } else {
3895 $sql .= " WHERE u.entity IN (".getEntity('user').")";
3896 }
3897 $sql .= " AND u.statut > 0";
3898 //$sql.= " AND employee != 0";
3899
3900 $resql = $this->db->query($sql);
3901 if ($resql) {
3902 while ($obj = $this->db->fetch_object($resql)) {
3903 $this->nb["users"] = $obj->nb;
3904 }
3905 $this->db->free($resql);
3906 return 1;
3907 } else {
3908 dol_print_error($this->db);
3909 $this->error = $this->db->error();
3910 return -1;
3911 }
3912 }
3913
3925 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3926 {
3927 global $conf, $user, $langs;
3928
3929 $langs->load("user");
3930
3931 // Positionne le modele sur le nom du modele a utiliser
3932 if (!dol_strlen($modele)) {
3933 if (getDolGlobalString('USER_ADDON_PDF')) {
3934 $modele = $conf->global->USER_ADDON_PDF;
3935 } else {
3936 $modele = 'bluesky';
3937 }
3938 }
3939
3940 $modelpath = "core/modules/user/doc/";
3941
3942 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3943 }
3944
3945 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3953 public function user_get_property($rowid, $mode)
3954 {
3955 // phpcs:enable
3956 $user_property = '';
3957
3958 if (empty($rowid)) {
3959 return '';
3960 }
3961
3962 $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
3963 $sql .= " FROM ".$this->db->prefix()."user";
3964 $sql .= " WHERE rowid = ".((int) $rowid);
3965
3966 $resql = $this->db->query($sql);
3967 if ($resql) {
3968 $nump = $this->db->num_rows($resql);
3969
3970 if ($nump) {
3971 $obj = $this->db->fetch_object($resql);
3972
3973 if ($mode == 'email') {
3974 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
3975 } elseif ($mode == 'mobile') {
3976 $user_property = $obj->user_mobile;
3977 } elseif ($mode == 'name') {
3978 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname);
3979 }
3980 }
3981 return $user_property;
3982 } else {
3983 dol_print_error($this->db);
3984 }
3985
3986 return '';
3987 }
3988
3996 public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
3997 {
3998 global $dolibarr_main_url_root;
3999 global $conf;
4000
4001 $encodedsecurekey = dol_hash($conf->file->instance_unique_id.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
4002 if (isModEnabled('multicompany')) {
4003 $entity_qr = '&entity='.((int) $conf->entity);
4004 } else {
4005 $entity_qr = '';
4006 }
4007 // Define $urlwithroot
4008 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
4009 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
4010 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
4011
4012 if ($typeofurl == 'internal') {
4013 $urlwithroot = DOL_URL_ROOT;
4014 }
4015
4016 return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
4017 }
4018
4031 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = array(), $filtermode = 'AND', $entityfilter = false)
4032 {
4033 global $conf, $user;
4034
4035 $sql = "SELECT t.rowid";
4036 $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
4037
4038 if ($entityfilter) {
4039 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4040 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
4041 $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
4042 } else {
4043 $sql .= ",".$this->db->prefix()."usergroup_user as ug";
4044 $sql .= " WHERE ((ug.fk_user = t.rowid";
4045 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
4046 $sql .= " OR t.entity = 0)"; // Show always superadmin
4047 }
4048 } else {
4049 $sql .= " WHERE t.entity IN (".getEntity('user').")";
4050 }
4051 } else {
4052 $sql .= " WHERE 1 = 1";
4053 }
4054
4055 // Manage filter
4056 $sqlwhere = array();
4057 if (!empty($filter)) {
4058 foreach ($filter as $key => $value) {
4059 if ($key == 't.rowid') {
4060 $sqlwhere[] = $key." = ".((int) $value);
4061 } elseif (array_key_exists($key, $this->fields) && isset($this->fields[$key]['type']) && in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
4062 $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
4063 } elseif ($key == 'customsql') {
4064 $sqlwhere[] = $value;
4065 } else {
4066 $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
4067 }
4068 }
4069 }
4070 if (count($sqlwhere) > 0) {
4071 $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
4072 }
4073 $sql .= $this->db->order($sortfield, $sortorder);
4074 if ($limit) {
4075 $sql .= $this->db->plimit($limit + 1, $offset);
4076 }
4077
4078 dol_syslog(__METHOD__, LOG_DEBUG);
4079
4080 $resql = $this->db->query($sql);
4081 if ($resql) {
4082 $this->users = array();
4083 $num = $this->db->num_rows($resql);
4084 if ($num) {
4085 while ($obj = $this->db->fetch_object($resql)) {
4086 $line = new self($this->db);
4087 $result = $line->fetch($obj->rowid);
4088 if ($result > 0 && !empty($line->id)) {
4089 $this->users[$obj->rowid] = clone $line;
4090 }
4091 }
4092 $this->db->free($resql);
4093 }
4094 return $num;
4095 } else {
4096 $this->errors[] = $this->db->lasterror();
4097 return -1;
4098 }
4099 }
4100
4108 private $findUserIdByEmailCache;
4109
4120 public function findUserIdByEmail($email)
4121 {
4122 if (isset($this->findUserIdByEmailCache[$email])) {
4123 return $this->findUserIdByEmailCache[$email];
4124 }
4125
4126 $this->findUserIdByEmailCache[$email] = -1;
4127
4128 global $conf;
4129
4130 $sql = 'SELECT rowid';
4131 $sql .= ' FROM '.$this->db->prefix().'user';
4132 if (getDolGlobalString('AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR')) {
4133 $sql .= " WHERE email LIKE '%".$this->db->escape($email)."%'";
4134 } else {
4135 $sql .= " WHERE email = '".$this->db->escape($email)."'";
4136 }
4137 $sql .= ' LIMIT 1';
4138
4139 $resql = $this->db->query($sql);
4140 if (!$resql) {
4141 return -1;
4142 }
4143
4144 $obj = $this->db->fetch_object($resql);
4145 if (!$obj) {
4146 return -1;
4147 }
4148
4149 $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4150
4151 return $this->findUserIdByEmailCache[$email];
4152 }
4153}
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Definition security.php:604
$object ref
Definition info.php:79
Class to manage members of a foundation.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
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 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)
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)
get_children()
Return and array with all instanciated 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.
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()
Mise a jour en base de la date de derniere connexion d'un utilisateur Fonction appelee lors d'une nou...
__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.
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 (eventualy 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 childs available in this->users, define property fullpath and fullname.
error()
Renvoie la derniere erreur fonctionnelle de manipulation de l'objet.
getAllChildIds($addcurrentuser=0)
Return list of all child users id in herarchy (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 optionaly the picto) Use this->id,this->lastname,...
clearrights()
Clear all permissions array of user.
load_state_board()
Load metrics this->nb for dashboard.
update_clicktodial()
Update clicktodial info.
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.
$clicktodial_url
@string clicktodial url
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 user into object user.
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 clicable link of object (with eventually 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.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter=array(), $filtermode='AND', $entityfilter=false)
Load all objects into $this->users.
findUserIdByEmail($email)
Find a user by the given e-mail and return it's user id when found.
getTooltipContentArray($params)
Return array of data to show into tooltips.
trait CommonPeople
Superclass for thirdparties, contacts, members or users.
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:653
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:639
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0)
Format phone numbers according to country.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by second index function, which produces ascending (default) or descending output...
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
getArrayOfSocialNetworks()
Get array of social network dictionary.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
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.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getUserRemoteIP()
Return the IP of remote user.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
conf($dolibarr_main_document_root)
Load conf file (file must exists)
Definition inc.php:403
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall right right takeposterminal SELECT e e e e e statut
Definition invoice.php:1907
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dolEncrypt($chain, $key='', $ciphering='AES-256-CTR', $forceseed='')
Encode a string with a symetric encryption.
dol_verifyHash($chain, $hash, $type='0')
Compute a hash and compare it to the given one For backward compatibility reasons,...
dolGetLdapPasswordHash($password, $type='md5')
Returns a specific ldap hash of a password.
dolDecrypt($chain, $key='')
Decode a string with a symetric encryption.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.
Contact()
Old copy.
Definition index.php:572