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