dolibarr 20.0.5
user.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (c) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
4 * Copyright (c) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
7 * Copyright (C) 2005-2024 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2005 Lionel Cousteix <etm_ltd@tiscali.co.uk>
9 * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
10 * Copyright (C) 2013-2019 Philippe Grand <philippe.grand@atoo-net.com>
11 * Copyright (C) 2013-2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
12 * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
13 * Copyright (C) 2018 charlene Benke <charlie@patas-monkey.com>
14 * Copyright (C) 2018-2021 Nicolas ZABOURI <info@inovea-conseil.com>
15 * Copyright (C) 2019-2024 Frédéric France <frederic.france@free.fr>
16 * Copyright (C) 2019 Abbes Bahfir <dolipar@dolipar.org>
17 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
18 * Copyright (C) 2024 Lenin Rivas <lenin.rivas777@gmail.com>
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 3 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <https://www.gnu.org/licenses/>.
32 */
33
40require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
41require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
42require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
43require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
44
45
49class User extends CommonObject
50{
51 use CommonPeople;
52
56 public $element = 'user';
57
61 public $table_element = 'user';
62
66 public $fk_element = 'fk_user';
67
71 public $picto = 'user';
72
73 public $id = 0;
74
78 public $oldcopy;
79
85 public $statut;
86
87 public $status;
88
92 public $openid;
93
94 public $ldap_sid;
95 public $search_sid;
96 public $employee;
97 public $civility_code;
98
102 public $fullname;
103
107 public $gender;
108
109 public $birth;
110
114 public $email;
115
119 public $email_oauth2;
120
124 public $personal_email;
125
129 public $socialnetworks;
130
134 public $job;
135
139 public $signature;
140
144 public $office_phone;
145
149 public $office_fax;
150
154 public $user_mobile;
155
159 public $personal_mobile;
160
164 public $admin;
165
169 public $login;
170
174 public $api_key;
175
179 public $entity;
180
184 public $pass;
185
189 public $pass_crypted;
190
194 public $pass_indatabase;
195
199 public $pass_indatabase_crypted;
200
204 public $pass_temp;
205
211 public $datec;
212
218 public $datem;
219
223 public $socid;
224
228 public $contact_id;
229
233 public $fk_member;
234
238 public $fk_user;
239
243 public $fk_user_expense_validator;
244
248 public $fk_user_holiday_validator;
249
254
258 public $clicktodial_login;
259
263 public $clicktodial_password;
264
268 public $clicktodial_poste;
269
273 public $clicktodial_loaded;
274
275
276 public $datelastlogin;
277 public $datepreviouslogin;
278 public $flagdelsessionsbefore;
279 public $iplastlogin;
280 public $ippreviouslogin;
281 public $datestartvalidity;
282 public $dateendvalidity;
283
287 public $photo;
288
292 public $lang;
293
297 public $rights;
298
302 public $all_permissions_are_loaded;
303
307 public $nb_rights;
308
312 public $user_group_list;
313
317 private $_tab_loaded = array();
318
322 public $conf;
323
324 public $default_values; // To store default values for user. Loaded by loadDefaultValues().
325
326 public $lastsearch_values_tmp; // To store current search criteria for user
327 public $lastsearch_values; // To store last saved search criteria for user
328
332 public $users = array();
333 public $parentof; // To store an array of all parents for all ids.
334 private $cache_childids; // Cache array of already loaded children
335
336 public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
337
338 public $thm; // Average cost of employee - Used for valuation of time spent
339 public $tjm; // Average cost of employee
340
341 public $salary; // Monthly salary - Denormalized value from llx_user_employment
342 public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment
343 public $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment
344
348 public $color;
349
350 public $dateemployment; // Define date of employment by company
351 public $dateemploymentend; // Define date of employment end by company
352
353 public $default_c_exp_tax_cat;
354
358 public $ref_employee;
359
363 public $national_registration_number;
364
365 public $default_range;
366
370 public $fk_warehouse;
371
375 public $fk_establishment;
376
380 public $label_establishment;
381
385 //private $egroupware_id;
386
391 public $usergroup_entity;
392
393 public $fields = array(
394 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
395 'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 20, 'searchall' => 1),
396 'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1),
397 'ref_employee' => array('type' => 'varchar(50)', 'label' => 'RefEmployee', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 30, 'searchall' => 1),
398 'national_registration_number' => array('type' => 'varchar(50)', 'label' => 'NationalRegistrationNumber', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 40, 'searchall' => 1)
399 );
400
401 const STATUS_DISABLED = 0;
402 const STATUS_ENABLED = 1;
403
409 public function __construct($db)
410 {
411 $this->db = $db;
412
413 $this->ismultientitymanaged = 1;
414 $this->isextrafieldmanaged = 1;
415 // User preference
416 $this->clicktodial_loaded = 0;
417
418 // For cache usage
419 $this->all_permissions_are_loaded = 0;
420 $this->nb_rights = 0;
421
422 // Force some default values
423 $this->admin = 0;
424 $this->employee = 1;
425
426 $this->conf = new stdClass();
427 $this->rights = new stdClass();
428 $this->rights->user = new stdClass();
429 $this->rights->user->user = new stdClass();
430 $this->rights->user->self = new stdClass();
431 $this->rights->user->user_advance = new stdClass();
432 $this->rights->user->self_advance = new stdClass();
433 $this->rights->user->group_advance = new stdClass();
434 }
435
450 public function fetch($id = 0, $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1, $email = '', $fk_socpeople = 0, $use_email_oauth2 = 0)
451 {
452 global $conf, $user;
453
454 // Clean parameters
455 $login = trim($login);
456
457 // Get user
458 $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.civility as civility_code, u.birth, u.job,";
459 $sql .= " u.email, u.email_oauth2, u.personal_email,";
460 $sql .= " u.socialnetworks,";
461 $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile, u.personal_mobile,";
462 $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
463 $sql .= " u.admin, u.login, u.note_private, u.note_public,";
464 $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.api_key,";
465 $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,";
466 $sql .= " u.statut as status, u.lang, u.entity,";
467 $sql .= " u.datec as datec,";
468 $sql .= " u.tms as datem,";
469 $sql .= " u.datelastlogin as datel,";
470 $sql .= " u.datepreviouslogin as datep,";
471 $sql .= " u.flagdelsessionsbefore,";
472 $sql .= " u.iplastlogin,";
473 $sql .= " u.ippreviouslogin,";
474 $sql .= " u.datelastpassvalidation,";
475 $sql .= " u.datestartvalidity,";
476 $sql .= " u.dateendvalidity,";
477 $sql .= " u.photo as photo,";
478 $sql .= " u.openid as openid,";
479 $sql .= " u.accountancy_code,";
480 $sql .= " u.thm,";
481 $sql .= " u.tjm,";
482 $sql .= " u.salary,";
483 $sql .= " u.salaryextra,";
484 $sql .= " u.weeklyhours,";
485 $sql .= " u.color,";
486 $sql .= " u.dateemployment, u.dateemploymentend,";
487 $sql .= " u.fk_warehouse,";
488 $sql .= " u.ref_ext,";
489 $sql .= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode
490 $sql .= " u.national_registration_number,";
491 $sql .= " u.ref_employee,";
492 $sql .= " c.code as country_code, c.label as country,";
493 $sql .= " d.code_departement as state_code, d.nom as state,";
494 $sql .= " s.label as label_establishment, u.fk_establishment";
495 $sql .= " FROM ".$this->db->prefix()."user as u";
496 $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as c ON u.fk_country = c.rowid";
497 $sql .= " LEFT JOIN ".$this->db->prefix()."c_departements as d ON u.fk_state = d.rowid";
498 $sql .= " LEFT JOIN ".$this->db->prefix()."establishment as s ON u.fk_establishment = s.rowid";
499
500 if ($entity < 0) {
501 if ((!isModEnabled('multicompany') || !getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) && (!empty($user->entity))) {
502 $sql .= " WHERE u.entity IN (0, ".((int) $conf->entity).")";
503 } else {
504 $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
505 }
506 } else {
507 // The fetch was forced on an entity
508 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
509 $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
510 } else {
511 $sql .= " WHERE u.entity IN (0, ".((int) (($entity != '' && $entity >= 0) ? $entity : $conf->entity)).")"; // search in entity provided in parameter
512 }
513 }
514
515 if ($sid) {
516 // permet une recherche du user par son SID ActiveDirectory ou Samba
517 $sql .= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."')";
518 } elseif ($login) {
519 $sql .= " AND u.login = '".$this->db->escape($login)."'";
520 } elseif ($email) {
521 $sql .= " AND (u.email = '".$this->db->escape($email)."'";
522 if ($use_email_oauth2) {
523 $sql .= " OR u.email_oauth2 = '".$this->db->escape($email)."'";
524 }
525 $sql .= ")";
526 } elseif ($fk_socpeople > 0) {
527 $sql .= " AND u.fk_socpeople = ".((int) $fk_socpeople);
528 } else {
529 $sql .= " AND u.rowid = ".((int) $id);
530 }
531 $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
532
533 if ($sid) {
534 // permet une recherche du user par son SID ActiveDirectory ou Samba
535 $sql .= ' '.$this->db->plimit(1);
536 }
537
538 $resql = $this->db->query($sql);
539 if ($resql) {
540 $num = $this->db->num_rows($resql);
541 if ($num > 1) {
542 $this->error = "USERDUPLICATEFOUND";
543 dol_syslog(get_class($this)."::fetch more than 1 user found", LOG_WARNING);
544
545 $this->db->free($resql);
546 return 0;
547 }
548
549 $obj = $this->db->fetch_object($resql);
550 if ($obj) {
551 $this->id = $obj->rowid;
552 $this->ref = $obj->rowid;
553
554 $this->ref_ext = $obj->ref_ext;
555
556 $this->ldap_sid = $obj->ldap_sid;
557 $this->civility_code = $obj->civility_code;
558 $this->lastname = $obj->lastname;
559 $this->firstname = $obj->firstname;
560 $this->ref_employee = $obj->ref_employee;
561 $this->national_registration_number = $obj->national_registration_number;
562
563 $this->employee = $obj->employee;
564
565 $this->login = $obj->login;
566 $this->gender = $obj->gender;
567 $this->birth = $this->db->jdate($obj->birth);
568 $this->pass_indatabase = $obj->pass;
569 $this->pass_indatabase_crypted = $obj->pass_crypted;
570 $this->pass = $obj->pass;
571 $this->pass_temp = $obj->pass_temp;
572 $this->api_key = dolDecrypt($obj->api_key);
573
574 $this->address = $obj->address;
575 $this->zip = $obj->zip;
576 $this->town = $obj->town;
577
578 $this->country_id = $obj->country_id;
579 $this->country_code = $obj->country_id ? $obj->country_code : '';
580 //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
581
582 $this->state_id = $obj->state_id;
583 $this->state_code = $obj->state_code;
584 $this->state = ($obj->state != '-' ? $obj->state : '');
585
586 $this->office_phone = $obj->office_phone;
587 $this->office_fax = $obj->office_fax;
588 $this->user_mobile = $obj->user_mobile;
589 $this->personal_mobile = $obj->personal_mobile;
590 $this->email = $obj->email;
591 $this->email_oauth2 = $obj->email_oauth2;
592 $this->personal_email = $obj->personal_email;
593 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
594 $this->job = $obj->job;
595 $this->signature = $obj->signature;
596 $this->admin = $obj->admin;
597 $this->note_public = $obj->note_public;
598 $this->note_private = $obj->note_private;
599
600 $this->statut = $obj->status; // deprecated
601 $this->status = $obj->status;
602
603 $this->photo = $obj->photo;
604 $this->openid = $obj->openid;
605 $this->lang = $obj->lang;
606 $this->entity = $obj->entity;
607 $this->accountancy_code = $obj->accountancy_code;
608 $this->thm = $obj->thm;
609 $this->tjm = $obj->tjm;
610 $this->salary = $obj->salary;
611 $this->salaryextra = $obj->salaryextra;
612 $this->weeklyhours = $obj->weeklyhours;
613 $this->color = $obj->color;
614 $this->dateemployment = $this->db->jdate($obj->dateemployment);
615 $this->dateemploymentend = $this->db->jdate($obj->dateemploymentend);
616
617 $this->datec = $this->db->jdate($obj->datec);
618 $this->datem = $this->db->jdate($obj->datem);
619 $this->datelastlogin = $this->db->jdate($obj->datel);
620 $this->datepreviouslogin = $this->db->jdate($obj->datep);
621 $this->flagdelsessionsbefore = $this->db->jdate($obj->flagdelsessionsbefore, 'gmt');
622 $this->iplastlogin = $obj->iplastlogin;
623 $this->ippreviouslogin = $obj->ippreviouslogin;
624 $this->datestartvalidity = $this->db->jdate($obj->datestartvalidity);
625 $this->dateendvalidity = $this->db->jdate($obj->dateendvalidity);
626
627 $this->socid = $obj->fk_soc;
628 $this->contact_id = $obj->fk_socpeople;
629 $this->fk_member = $obj->fk_member;
630 $this->fk_user = $obj->fk_user;
631 $this->fk_user_expense_validator = $obj->fk_user_expense_validator;
632 $this->fk_user_holiday_validator = $obj->fk_user_holiday_validator;
633
634 $this->default_range = $obj->default_range;
635 $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
636 $this->fk_warehouse = $obj->fk_warehouse;
637 $this->fk_establishment = $obj->fk_establishment;
638 $this->label_establishment = $obj->label_establishment;
639
640 // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
641 // in such case, this admin user must be admin for ALL entities.
642 if (!isModEnabled('multicompany') && $this->admin && $this->entity == 1) {
643 $this->entity = 0;
644 }
645
646 // Retrieve all extrafield
647 // fetch optionals attributes and labels
648 $this->fetch_optionals();
649
650 $this->db->free($resql);
651 } else {
652 $this->error = "USERNOTFOUND";
653 dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
654
655 $this->db->free($resql);
656 return 0;
657 }
658 } else {
659 $this->error = $this->db->lasterror();
660 return -1;
661 }
662
663 // To get back the global configuration unique to the user
664 if ($loadpersonalconf) {
665 $result = $this->loadPersonalConf();
666
667 $result = $this->loadDefaultValues();
668
669 if ($result < 0) {
670 $this->error = $this->db->lasterror();
671 return -3;
672 }
673 }
674
675 return 1;
676 }
677
678
684 public function loadPersonalConf()
685 {
686 global $conf;
687
688 // Load user->conf for user
689 $sql = "SELECT param, value FROM ".$this->db->prefix()."user_param";
690 $sql .= " WHERE fk_user = ".((int) $this->id);
691 $sql .= " AND entity = ".((int) $conf->entity);
692 //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
693 $resql = $this->db->query($sql);
694 if ($resql) {
695 $num = $this->db->num_rows($resql);
696 $i = 0;
697 while ($i < $num) {
698 $obj = $this->db->fetch_object($resql);
699 $p = (!empty($obj->param) ? $obj->param : '');
700 if (!empty($p)) {
701 $this->conf->$p = $obj->value;
702 }
703 $i++;
704 }
705 $this->db->free($resql);
706
707 return $num;
708 } else {
709 $this->error = $this->db->lasterror();
710
711 return -2;
712 }
713 }
714
720 public function loadDefaultValues()
721 {
722 global $conf;
723
724 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
725 // Load user->default_values for user. TODO Save this in memcached ?
726 require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php';
727
728 $defaultValues = new DefaultValues($this->db);
729 $result = $defaultValues->fetchAll('', '', 0, 0, '(t.user_id:in:0,'.$this->id.') AND (entity:in:'.(isset($this->entity) ? $this->entity : $conf->entity).','.$conf->entity.')'); // User 0 (all) + me (if defined)
730 //$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)
731
732 if (!is_array($result) && $result < 0) {
733 setEventMessages($defaultValues->error, $defaultValues->errors, 'errors');
734 dol_print_error($this->db);
735 return -1;
736 } elseif (count($result) > 0) {
737 foreach ($result as $defval) {
738 if (!empty($defval->page) && !empty($defval->type) && !empty($defval->param)) {
739 $pagewithoutquerystring = $defval->page;
740 $pagequeries = '';
741 $reg = array();
742 if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
743 $pagewithoutquerystring = $reg[1];
744 $pagequeries = $reg[2];
745 }
746 $this->default_values[$pagewithoutquerystring][$defval->type][$pagequeries ? $pagequeries : '_noquery_'][$defval->param] = $defval->value;
747 }
748 }
749 }
750 if (!empty($this->default_values)) {
751 foreach ($this->default_values as $a => $b) {
752 foreach ($b as $c => $d) {
753 krsort($this->default_values[$a][$c]);
754 }
755 }
756 }
757 }
758 return 1;
759 }
760
772 public function hasRight($module, $permlevel1, $permlevel2 = '')
773 {
774 // For compatibility with bad naming permissions on module
775 $moduletomoduletouse = array(
776 'compta' => 'comptabilite',
777 'contract' => 'contrat',
778 'member' => 'adherent',
779 'mo' => 'mrp',
780 'order' => 'commande',
781 'produit' => 'product',
782 'productlot' => 'product',
783 'project' => 'projet',
784 'propale' => 'propal',
785 'shipping' => 'expedition',
786 'task' => 'task@projet',
787 'fichinter' => 'ficheinter',
788 'inventory' => 'stock',
789 'invoice' => 'facture',
790 'invoice_supplier' => 'fournisseur',
791 'order_supplier' => 'fournisseur',
792 'knowledgerecord' => 'knowledgerecord@knowledgemanagement',
793 'skill@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
794 'job@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
795 'position@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all"
796 'facturerec' => 'facture',
797 'margins' => 'margin',
798 );
799
800 if (!empty($moduletomoduletouse[$module])) {
801 $module = $moduletomoduletouse[$module];
802 }
803
804 $moduleRightsMapping = array(
805 'product' => 'produit',
806 'margin' => 'margins',
807 'comptabilite' => 'compta'
808 );
809
810 $rightsPath = $module;
811 if (!empty($moduleRightsMapping[$rightsPath])) {
812 $rightsPath = $moduleRightsMapping[$rightsPath];
813 }
814
815 // If module is abc@module, we check permission user->hasRight(module, abc, permlevel1)
816 $tmp = explode('@', $rightsPath, 2);
817 if (!empty($tmp[1])) {
818 if (strpos($module, '@') !== false) {
819 $module = $tmp[1];
820 }
821 if ($tmp[0] != $tmp[1]) {
822 // If $module = 'myobject@mymodule'
823 $rightsPath = $tmp[1];
824 $permlevel2 = $permlevel1;
825 $permlevel1 = $tmp[0];
826 } else {
827 // If $module = 'abc@abc'
828 $rightsPath = $tmp[1];
829 }
830 }
831
832 // In $conf->modules, we have 'accounting', 'product', 'facture', ...
833 // In $user->rights, we have 'accounting', 'produit', 'facture', ...
834 //var_dump($this->rights->$rightsPath);
835 //var_dump($conf->modules);
836 //var_dump($module.' '.isModEnabled($module).' '.$rightsPath.' '.$permlevel1.' '.$permlevel2);
837 if (!isModEnabled($module)) {
838 return 0;
839 }
840
841 // Special case for external user
842 if (!empty($this->socid)) {
843 if ($module == 'societe' && ($permlevel1 == 'creer' || $permlevel1 == 'write')) {
844 return 0; // An external user never has the permission ->societe->write to see all thirdparties (always restricted to himself)
845 }
846 if ($module == 'societe' && $permlevel1 == 'client' && $permlevel2 == 'voir') {
847 return 0; // An external user never has the permission ->societe->client->voir to see all thirdparties (always restricted to himself)
848 }
849 if ($module == 'societe' && $permlevel1 == 'export') {
850 return 0; // An external user never has the permission ->societe->export to see all thirdparties (always restricted to himself)
851 }
852 if ($module == 'societe' && ($permlevel1 == 'supprimer' || $permlevel1 == 'delete')) {
853 return 0; // An external user never has the permission ->societe->delete to see all thirdparties (always restricted to himself)
854 }
855 }
856
857 // For compatibility with bad naming permissions on permlevel1
858 if ($permlevel1 == 'propale') {
859 $permlevel1 = 'propal';
860 }
861 if ($permlevel1 == 'member') {
862 $permlevel1 = 'adherent';
863 }
864 if ($permlevel1 == 'recruitmentcandidature') {
865 $permlevel1 = 'recruitmentjobposition';
866 }
867
868 //var_dump($this->rights);
869 //var_dump($rightsPath.' '.$permlevel1.' '.$permlevel2);
870 if (empty($rightsPath) || empty($this->rights) || empty($this->rights->$rightsPath) || empty($permlevel1)) {
871 return 0;
872 }
873
874 if ($permlevel2) {
875 if (!empty($this->rights->$rightsPath->$permlevel1)) {
876 if (!empty($this->rights->$rightsPath->$permlevel1->$permlevel2)) {
877 return $this->rights->$rightsPath->$permlevel1->$permlevel2;
878 }
879 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
880 // instead of "read", "write", "delete"
881 if ($permlevel2 == 'read' && !empty($this->rights->$rightsPath->$permlevel1->lire)) {
882 return $this->rights->$rightsPath->$permlevel1->lire;
883 }
884 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->creer)) {
885 return $this->rights->$rightsPath->$permlevel1->creer;
886 }
887 if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->create)) {
888 return $this->rights->$rightsPath->$permlevel1->create;
889 }
890 if ($permlevel2 == 'delete' && !empty($this->rights->$rightsPath->$permlevel1->supprimer)) {
891 return $this->rights->$rightsPath->$permlevel1->supprimer;
892 }
893 }
894 } else {
895 if (!empty($this->rights->$rightsPath->$permlevel1)) {
896 return $this->rights->$rightsPath->$permlevel1;
897 }
898 // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer"
899 // instead of "read", "write", "delete"
900 if ($permlevel1 == 'read' && !empty($this->rights->$rightsPath->lire)) {
901 return $this->rights->$rightsPath->lire;
902 }
903 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->creer)) {
904 return $this->rights->$rightsPath->creer;
905 }
906 if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->create)) {
907 return $this->rights->$rightsPath->create;
908 }
909 if ($permlevel1 == 'delete' && !empty($this->rights->$rightsPath->supprimer)) {
910 return $this->rights->$rightsPath->supprimer;
911 }
912 }
913
914 return 0;
915 }
916
928 public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
929 {
930 global $conf, $user, $langs;
931
932 $entity = (empty($entity) ? $conf->entity : $entity);
933
934 dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity, $notrigger for user id=".$this->id);
935
936 if (empty($this->id)) {
937 $this->error = 'Try to call addrights on an object user with an empty id';
938 return -1;
939 }
940
941 $error = 0;
942 $whereforadd = '';
943
944 $this->db->begin();
945
946 if (!empty($rid)) {
947 $module = $perms = $subperms = '';
948
949 // If we ask to add a given permission, we first load properties of this permission (module, perms and subperms).
950 $sql = "SELECT module, perms, subperms";
951 $sql .= " FROM ".$this->db->prefix()."rights_def";
952 $sql .= " WHERE id = ".((int) $rid);
953 $sql .= " AND entity = ".((int) $entity);
954
955 $result = $this->db->query($sql);
956 if ($result) {
957 $obj = $this->db->fetch_object($result);
958
959 if ($obj) {
960 $module = $obj->module;
961 $perms = $obj->perms;
962 $subperms = $obj->subperms;
963 }
964 } else {
965 $error++;
966 dol_print_error($this->db);
967 }
968
969 // Define the where for the permission to add
970 $whereforadd = "id=".((int) $rid);
971 // Add also inherited permissions
972 if (!empty($subperms)) {
973 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))";
974 } elseif (!empty($perms)) {
975 $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND (subperms IS NULL or subperms = ''))";
976 }
977 } else {
978 // A list of permission was requested (not a single specific permission)
979 // based on the name of a module of permissions
980 // Used in the where clause to determine the list of permissions to add.
981 if (!empty($allmodule)) {
982 if ($allmodule == 'allmodules') {
983 $whereforadd = 'allmodules';
984 } else {
985 $whereforadd = "module='".$this->db->escape($allmodule)."'";
986 if (!empty($allperms)) {
987 $whereforadd .= " AND perms='".$this->db->escape($allperms)."'";
988 }
989 }
990 }
991 }
992
993 // Add automatically other permission using the criteria whereforadd
994 // $whereforadd can be a SQL filter or the string 'allmodules'
995 if (!empty($whereforadd)) {
996 //print "$module-$perms-$subperms";
997 $sql = "SELECT id";
998 $sql .= " FROM ".$this->db->prefix()."rights_def";
999 $sql .= " WHERE entity = ".((int) $entity);
1000 if (!empty($whereforadd) && $whereforadd != 'allmodules') {
1001 $sql .= " AND (".$whereforadd.")"; // Note: parenthesis are important because whereforadd can contains OR. Also note that $whereforadd is already sanitized
1002 }
1003
1004 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1005 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1006 $sqldelete .= $sql;
1007 $sqldelete .= ") AND entity = ".((int) $entity);
1008 if (!$this->db->query($sqldelete)) {
1009 $error++;
1010 }
1011
1012 if (!$error) {
1013 $resql = $this->db->query($sql);
1014 if ($resql) {
1015 $num = $this->db->num_rows($resql);
1016 $i = 0;
1017 while ($i < $num) {
1018 $obj = $this->db->fetch_object($resql);
1019
1020 if ($obj) {
1021 $nid = $obj->id;
1022
1023 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id) VALUES (".((int) $entity).", ".((int) $this->id).", ".((int) $nid).")";
1024 if (!$this->db->query($sql)) {
1025 $error++;
1026 }
1027 }
1028
1029 $i++;
1030 }
1031 } else {
1032 $error++;
1033 dol_print_error($this->db);
1034 }
1035 }
1036 }
1037
1038 if (!$error && !$notrigger) {
1039 $langs->load("other");
1040 $this->context = array('audit' => $langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : ''));
1041
1042 // Call trigger
1043 $result = $this->call_trigger('USER_MODIFY', $user);
1044 if ($result < 0) {
1045 $error++;
1046 }
1047 // End call triggers
1048 }
1049
1050 if ($error) {
1051 $this->db->rollback();
1052 return -$error;
1053 } else {
1054 $this->db->commit();
1055 return 1;
1056 }
1057 }
1058
1059
1071 public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
1072 {
1073 global $conf, $user, $langs;
1074
1075 $error = 0;
1076 $wherefordel = '';
1077 $entity = (!empty($entity) ? $entity : $conf->entity);
1078
1079 $this->db->begin();
1080
1081 if (!empty($rid)) {
1082 $module = $perms = $subperms = '';
1083
1084 // When the request is to delete a specific permissions, this gets the
1085 // les charactis for the module, permissions and sub-permission of this permission.
1086 $sql = "SELECT module, perms, subperms";
1087 $sql .= " FROM ".$this->db->prefix()."rights_def";
1088 $sql .= " WHERE id = '".$this->db->escape($rid)."'";
1089 $sql .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1090
1091 $result = $this->db->query($sql);
1092 if ($result) {
1093 $obj = $this->db->fetch_object($result);
1094
1095 if ($obj) {
1096 $module = $obj->module;
1097 $perms = $obj->perms;
1098 $subperms = $obj->subperms;
1099 }
1100 } else {
1101 $error++;
1102 dol_print_error($this->db);
1103 }
1104
1105 // Where clause for the list of permissions to delete
1106 $wherefordel = "id=".((int) $rid);
1107 // Suppression des droits induits
1108 if ($subperms == 'lire' || $subperms == 'read') {
1109 $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)";
1110 }
1111 if ($perms == 'lire' || $perms == 'read') {
1112 $wherefordel .= " OR (module='".$this->db->escape($module)."')";
1113 }
1114 } else {
1115 // The deletion of the permissions concerns the name of a module or
1116 // list of permissions.
1117 // Used in the Where clause to determine the list of permission to delete
1118 if (!empty($allmodule)) {
1119 if ($allmodule == 'allmodules') {
1120 $wherefordel = 'allmodules';
1121 } else {
1122 $wherefordel = "module='".$this->db->escape($allmodule)."'";
1123 if (!empty($allperms)) {
1124 $wherefordel .= " AND perms='".$this->db->escape($allperms)."'";
1125 }
1126 }
1127 }
1128 }
1129
1130 // Delete permission according to a criteria set into $wherefordel
1131 if (!empty($wherefordel)) {
1132 //print "$module-$perms-$subperms";
1133 $sql = "SELECT id";
1134 $sql .= " FROM ".$this->db->prefix()."rights_def";
1135 $sql .= " WHERE entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1136 if (!empty($wherefordel) && $wherefordel != 'allmodules') {
1137 $sql .= " AND (".$wherefordel.")"; // Note: parenthesis are important because wherefordel can contains OR. Also note that $wherefordel is already sanitized
1138 }
1139
1140 // avoid admin to remove his own important rights
1141 if ($this->admin == 1) {
1142 $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
1143 $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
1144 $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
1145 $sql .= " AND id NOT IN (358)"; // user export
1146 }
1147
1148 $sqldelete = "DELETE FROM ".$this->db->prefix()."user_rights";
1149 $sqldelete .= " WHERE fk_user = ".((int) $this->id)." AND fk_id IN (";
1150 $sqldelete .= $sql;
1151 $sqldelete .= ")";
1152 $sqldelete .= " AND entity IN (".$this->db->sanitize($entity, 0, 0, 0, 0).")";
1153
1154 $resql = $this->db->query($sqldelete);
1155 if (!$resql) {
1156 $error++;
1157 dol_print_error($this->db);
1158 }
1159 }
1160
1161 if (!$error && !$notrigger) {
1162 $langs->load("other");
1163 $this->context = array('audit' => $langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : ''));
1164
1165 // Call trigger
1166 $result = $this->call_trigger('USER_MODIFY', $user);
1167 if ($result < 0) {
1168 $error++;
1169 }
1170 // End call triggers
1171 }
1172
1173 if ($error) {
1174 $this->db->rollback();
1175 return -$error;
1176 } else {
1177 $this->db->commit();
1178 return 1;
1179 }
1180 }
1181
1182
1189 public function clearrights()
1190 {
1191 dol_syslog(get_class($this)."::clearrights reset user->rights");
1192 $this->rights = new stdClass();
1193 $this->nb_rights = 0;
1194 $this->all_permissions_are_loaded = 0;
1195 $this->_tab_loaded = array();
1196 }
1197
1198
1207 public function loadRights($moduletag = '', $forcereload = 0)
1208 {
1209 global $conf;
1210
1211 $alreadyloaded = false;
1212
1213 if (empty($forcereload)) {
1214 if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
1215 // Rights for this module are already loaded, so we leave
1216 $alreadyloaded = true;
1217 }
1218
1219 if (!empty($this->all_permissions_are_loaded)) {
1220 // We already loaded all rights for this user, so we leave
1221 $alreadyloaded = true;
1222 }
1223 }
1224
1225 // More init to avoid warnings/errors
1226 if (!isset($this->rights) || !is_object($this->rights)) {
1227 $this->rights = new stdClass();
1228 }
1229 if (!isset($this->rights->user) || !is_object($this->rights->user)) {
1230 $this->rights->user = new stdClass();
1231 }
1232
1233 // Get permission of users + Get permissions of groups
1234
1235 if (!$alreadyloaded) {
1236 // First user permissions
1237 $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
1238 $sql .= " FROM ".$this->db->prefix()."user_rights as ur,";
1239 $sql .= " ".$this->db->prefix()."rights_def as r";
1240 $sql .= " WHERE r.id = ur.fk_id";
1241 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1242 // On old version, we used entity defined into table r only
1243 // @FIXME Test on MULTICOMPANY_BACKWARD_COMPATIBILITY is a very strange business rules because the select should be always the
1244 // same than into user->loadRights() in user/perms.php and user/group/perms.php
1245 // We should never use and remove this case.
1246 $sql .= " AND r.entity IN (0,".(isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') ? "1," : "").$conf->entity.")";
1247 } else {
1248 // On table r=rights_def, the unique key is (id, entity) because id is hard coded into module descriptor and inserted during module activation.
1249 // So we must include the filter on entity on both table r. and ur.
1250 $sql .= " AND r.entity = ".((int) $conf->entity)." AND ur.entity = ".((int) $conf->entity);
1251 }
1252 $sql .= " AND ur.fk_user = ".((int) $this->id);
1253 $sql .= " AND r.perms IS NOT NULL";
1254 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1255 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1256 }
1257 if ($moduletag) {
1258 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1259 }
1260
1261 $resql = $this->db->query($sql);
1262 if ($resql) {
1263 $num = $this->db->num_rows($resql);
1264 $i = 0;
1265 while ($i < $num) {
1266 $obj = $this->db->fetch_object($resql);
1267
1268 if ($obj) {
1269 $module = $obj->module;
1270 $perms = $obj->perms;
1271 $subperms = $obj->subperms;
1272
1273 if (!empty($perms)) {
1274 if (!empty($module)) {
1275 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1276 $this->rights->$module = new stdClass();
1277 }
1278 if (!empty($subperms)) {
1279 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1280 $this->rights->$module->$perms = new stdClass();
1281 }
1282 if (empty($this->rights->$module->$perms->$subperms)) { // if not already counted
1283 $this->nb_rights++;
1284 }
1285 $this->rights->$module->$perms->$subperms = 1;
1286 } else {
1287 if (empty($this->rights->$module->$perms)) { // if not already counted
1288 $this->nb_rights++;
1289 }
1290 $this->rights->$module->$perms = 1;
1291 }
1292 }
1293 }
1294 }
1295 $i++;
1296 }
1297 $this->db->free($resql);
1298 }
1299
1300 // Now permissions of groups
1301 $sql = "SELECT DISTINCT r.module, r.perms, r.subperms, r.entity";
1302 $sql .= " FROM ".$this->db->prefix()."usergroup_rights as gr,";
1303 $sql .= " ".$this->db->prefix()."usergroup_user as gu,";
1304 $sql .= " ".$this->db->prefix()."rights_def as r";
1305 $sql .= " WHERE r.id = gr.fk_id";
1306 if (getDolGlobalString('MULTICOMPANY_BACKWARD_COMPATIBILITY')) {
1307 // @FIXME Test on MULTICOMPANY_BACKWARD_COMPATIBILITY is a very strange business rules because the select should be always the
1308 // same than into user->loadRights() in user/perms.php and user/group/perms.php
1309 // We should never use and remove this case.
1310 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1311 $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1312 } else {
1313 $sql .= " AND r.entity = ".((int) $conf->entity);
1314 }
1315 } else {
1316 $sql .= " AND gr.entity = ".((int) $conf->entity); // Only groups created in current entity
1317 // The entity on the table gu=usergroup_user should be useless and should never be used because it is already into gr and r.
1318 // but when using MULTICOMPANY_TRANSVERSE_MODE, we may have inserted record that make rubbish result here due to the duplicate record of
1319 // other entities, so we are forced to add a filter on gu here
1320 $sql .= " AND gu.entity IN (0,".$conf->entity.")";
1321 $sql .= " AND r.entity = ".((int) $conf->entity); // Only permission of modules enabled in current entity
1322 }
1323 // End of strange business rule
1324 $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
1325 $sql .= " AND gu.fk_user = ".((int) $this->id);
1326 $sql .= " AND r.perms IS NOT NULL";
1327 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1328 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
1329 }
1330 if ($moduletag) {
1331 $sql .= " AND r.module = '".$this->db->escape($moduletag)."'";
1332 }
1333
1334 $resql = $this->db->query($sql);
1335 if ($resql) {
1336 $num = $this->db->num_rows($resql);
1337 $i = 0;
1338 while ($i < $num) {
1339 $obj = $this->db->fetch_object($resql);
1340
1341 if ($obj) {
1342 $module = $obj->module;
1343 $perms = $obj->perms;
1344 $subperms = $obj->subperms;
1345
1346 if (!empty($perms)) {
1347 if (!empty($module)) {
1348 if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
1349 $this->rights->$module = new stdClass();
1350 }
1351 if (!empty($subperms)) {
1352 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1353 $this->rights->$module->$perms = new stdClass();
1354 }
1355 if (empty($this->rights->$module->$perms->$subperms)) { // if not already counted
1356 $this->nb_rights++;
1357 }
1358 $this->rights->$module->$perms->$subperms = 1;
1359 } else {
1360 // 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
1361 if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
1362 if (empty($this->rights->$module->$perms)) { // if not already counted
1363 $this->nb_rights++;
1364 }
1365 $this->rights->$module->$perms = 1;
1366 }
1367 }
1368 }
1369 }
1370 }
1371 $i++;
1372 }
1373 $this->db->free($resql);
1374 }
1375
1376 // Force permission on user for admin
1377 if (!empty($this->admin)) {
1378 if (empty($this->rights->user->user)) {
1379 $this->rights->user->user = new stdClass();
1380 }
1381 $listofpermtotest = array('lire', 'creer', 'password', 'supprimer', 'export');
1382 foreach ($listofpermtotest as $permtotest) {
1383 if (empty($this->rights->user->user->$permtotest)) {
1384 $this->rights->user->user->$permtotest = 1;
1385 $this->nb_rights++;
1386 }
1387 }
1388 if (empty($this->rights->user->self)) {
1389 $this->rights->user->self = new stdClass();
1390 }
1391 $listofpermtotest = array('creer', 'password');
1392 foreach ($listofpermtotest as $permtotest) {
1393 if (empty($this->rights->user->self->$permtotest)) {
1394 $this->rights->user->self->$permtotest = 1;
1395 $this->nb_rights++;
1396 }
1397 }
1398 // Add test on advanced permissions
1399 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1400 if (empty($this->rights->user->user_advance)) {
1401 $this->rights->user->user_advance = new stdClass();
1402 }
1403 $listofpermtotest = array('readperms', 'write');
1404 foreach ($listofpermtotest as $permtotest) {
1405 if (empty($this->rights->user->user_advance->$permtotest)) {
1406 $this->rights->user->user_advance->$permtotest = 1;
1407 $this->nb_rights++;
1408 }
1409 }
1410 if (empty($this->rights->user->self_advance)) {
1411 $this->rights->user->self_advance = new stdClass();
1412 }
1413 $listofpermtotest = array('readperms', 'writeperms');
1414 foreach ($listofpermtotest as $permtotest) {
1415 if (empty($this->rights->user->self_advance->$permtotest)) {
1416 $this->rights->user->self_advance->$permtotest = 1;
1417 $this->nb_rights++;
1418 }
1419 }
1420 if (empty($this->rights->user->group_advance)) {
1421 $this->rights->user->group_advance = new stdClass();
1422 }
1423 $listofpermtotest = array('read', 'readperms', 'write', 'delete');
1424 foreach ($listofpermtotest as $permtotest) {
1425 if (empty($this->rights->user) || empty($this->rights->user->group_advance->$permtotest)) {
1426 $this->rights->user->group_advance->$permtotest = 1;
1427 $this->nb_rights++;
1428 }
1429 }
1430 }
1431 }
1432
1433 // For backward compatibility
1434 if (isset($this->rights->propale) && !isset($this->rights->propal)) {
1435 $this->rights->propal = $this->rights->propale;
1436 }
1437 if (isset($this->rights->propal) && !isset($this->rights->propale)) {
1438 $this->rights->propale = $this->rights->propal;
1439 }
1440
1441 if (!$moduletag) {
1442 // If the module was not define, then everything is loaded.
1443 // Therefore, we can consider that the permissions are cached
1444 // because they were all loaded for this user instance.
1445 $this->all_permissions_are_loaded = 1;
1446 } else {
1447 // If the module is defined, we flag it as loaded into cache
1448 $this->_tab_loaded[$moduletag] = 1;
1449 }
1450 }
1451 }
1452
1464 public function getrights($moduletag = '', $forcereload = 0)
1465 {
1466 $this->loadRights($moduletag, $forcereload);
1467 }
1468
1475 public function setstatus($status)
1476 {
1477 global $conf, $langs, $user;
1478
1479 $error = 0;
1480
1481 // Check parameters
1482 if (isset($this->statut)) {
1483 if ($this->statut == $status) {
1484 return 0;
1485 }
1486 } elseif (isset($this->status) && $this->status == $status) {
1487 return 0;
1488 }
1489
1490 $this->db->begin();
1491
1492 // Save in database
1493 $sql = "UPDATE ".$this->db->prefix()."user";
1494 $sql .= " SET statut = ".((int) $status);
1495 $sql .= " WHERE rowid = ".((int) $this->id);
1496 $result = $this->db->query($sql);
1497
1498 dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1499 if ($result) {
1500 if ($status == 0) {
1501 $this->context['actionmsg'] = 'User '.$this->login.' disabled';
1502 } else {
1503 $this->context['actionmsg'] = 'User '.$this->login.' enabled';
1504 }
1505 // Call trigger
1506 $result = $this->call_trigger('USER_ENABLEDISABLE', $user);
1507 if ($result < 0) {
1508 $error++;
1509 }
1510 // End call triggers
1511 }
1512
1513 if ($error) {
1514 $this->db->rollback();
1515 return -$error;
1516 } else {
1517 $this->status = $status;
1518 $this->statut = $status;
1519 $this->db->commit();
1520 return 1;
1521 }
1522 }
1523
1534 public function setCategories($categories)
1535 {
1536 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1537 return parent::setCategoriesCommon($categories, Categorie::TYPE_USER);
1538 }
1539
1546 public function delete(User $user)
1547 {
1548 global $conf, $langs;
1549
1550 $error = 0;
1551
1552 $this->db->begin();
1553
1554 $this->fetch($this->id);
1555
1556 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1557
1558 // Remove rights
1559 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1560
1561 if (!$error && !$this->db->query($sql)) {
1562 $error++;
1563 $this->error = $this->db->lasterror();
1564 }
1565
1566 // Remove group
1567 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1568 if (!$error && !$this->db->query($sql)) {
1569 $error++;
1570 $this->error = $this->db->lasterror();
1571 }
1572
1573 // Remove params
1574 $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1575 if (!$error && !$this->db->query($sql)) {
1576 $error++;
1577 $this->error = $this->db->lasterror();
1578 }
1579
1580 // If contact, remove link
1581 if ($this->contact_id > 0) {
1582 $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1583 if (!$error && !$this->db->query($sql)) {
1584 $error++;
1585 $this->error = $this->db->lasterror();
1586 }
1587 }
1588
1589 // Remove extrafields
1590 if (!$error) {
1591 $result = $this->deleteExtraFields();
1592 if ($result < 0) {
1593 $error++;
1594 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1595 }
1596 }
1597
1598 // Remove user
1599 if (!$error) {
1600 $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1601 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1602 if (!$this->db->query($sql)) {
1603 $error++;
1604 $this->error = $this->db->lasterror();
1605 }
1606 }
1607
1608 if (!$error) {
1609 // Call trigger
1610 $result = $this->call_trigger('USER_DELETE', $user);
1611 if ($result < 0) {
1612 $error++;
1613 $this->db->rollback();
1614 return -1;
1615 }
1616 // End call triggers
1617
1618 $this->db->commit();
1619 return 1;
1620 } else {
1621 $this->db->rollback();
1622 return -1;
1623 }
1624 }
1625
1633 public function create($user, $notrigger = 0)
1634 {
1635 global $conf, $langs;
1636 global $mysoc;
1637
1638 // Clean parameters
1639 $this->setUpperOrLowerCase();
1640
1641 $this->civility_code = trim((string) $this->civility_code);
1642 $this->login = trim((string) $this->login);
1643 if (!isset($this->entity)) {
1644 $this->entity = $conf->entity; // If not defined, we use default value
1645 }
1646
1647 dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1648
1649 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1650
1651 // Check parameters
1652 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
1653 $langs->load("errors");
1654 $this->error = $langs->trans("ErrorBadEMail", $this->email);
1655 return -1;
1656 }
1657 if (empty($this->login)) {
1658 $langs->load("errors");
1659 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1660 return -1;
1661 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1662 $langs->load("errors");
1663 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1664 return -1;
1665 }
1666
1667 $this->datec = dol_now();
1668
1669 $error = 0;
1670 $this->db->begin();
1671
1672 // Check if login already exists in same entity or into entity 0.
1673 if ($this->login) {
1674 $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)."'";
1675 $resqltochecklogin = $this->db->query($sqltochecklogin);
1676 if ($resqltochecklogin) {
1677 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1678 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1679 $langs->load("errors");
1680 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1681 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1682 $this->db->rollback();
1683 return -6;
1684 }
1685 $this->db->free($resqltochecklogin);
1686 }
1687 }
1688 if (!empty($this->email)) {
1689 $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)."'";
1690 $resqltochecklogin = $this->db->query($sqltochecklogin);
1691 if ($resqltochecklogin) {
1692 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1693 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1694 $langs->load("errors");
1695 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1696 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1697 $this->db->rollback();
1698 return -6;
1699 }
1700 $this->db->free($resqltochecklogin);
1701 }
1702 }
1703
1704 // Insert into database
1705 $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, entity)";
1706 $sql .= " VALUES('".$this->db->idate($this->datec)."', '".$this->db->escape($this->login)."', '".$this->db->escape($this->ldap_sid)."', ".((int) $this->entity).")";
1707 $result = $this->db->query($sql);
1708
1709 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1710 if ($result) {
1711 $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1712
1713 // Set default rights
1714 if ($this->set_default_rights() < 0) {
1715 $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1716 $this->db->rollback();
1717 return -5;
1718 }
1719
1720 if (getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && getDolGlobalString('STOCK_USERSTOCK_AUTOCREATE')) {
1721 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1722 $langs->load("stocks");
1723
1724 $entrepot = new Entrepot($this->db);
1725 $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1726 $entrepot->libelle = $entrepot->label; // For backward compatibility
1727 $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1728 $entrepot->statut = 1;
1729 $entrepot->country_id = $mysoc->country_id;
1730
1731 $warehouseid = $entrepot->create($user);
1732
1733 $this->fk_warehouse = $warehouseid;
1734 }
1735
1736 // Update minor fields
1737 $result = $this->update($user, 1, 1);
1738 if ($result < 0) {
1739 $this->db->rollback();
1740 return -4;
1741 }
1742
1743 if (!$notrigger) {
1744 // Call trigger
1745 $result = $this->call_trigger('USER_CREATE', $user);
1746 if ($result < 0) {
1747 $error++;
1748 }
1749 // End call triggers
1750 }
1751
1752 if (!$error) {
1753 $this->db->commit();
1754 return $this->id;
1755 } else {
1756 //$this->error=$interface->error;
1757 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1758 $this->db->rollback();
1759 return -3;
1760 }
1761 } else {
1762 $this->error = $this->db->lasterror();
1763 $this->db->rollback();
1764 return -2;
1765 }
1766 }
1767
1768
1769 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1778 public function create_from_contact($contact, $login = '', $password = '')
1779 {
1780 // phpcs:enable
1781 global $conf, $user, $langs;
1782
1783 $error = 0;
1784
1785 // Define parameters
1786 $this->admin = 0;
1787 $this->civility_code = $contact->civility_code;
1788 $this->lastname = $contact->lastname;
1789 $this->firstname = $contact->firstname;
1790 //$this->gender = $contact->gender; // contact has no gender
1791 $this->email = $contact->email;
1792 $this->socialnetworks = $contact->socialnetworks;
1793 $this->office_phone = $contact->phone_pro;
1794 $this->office_fax = $contact->fax;
1795 $this->user_mobile = $contact->phone_mobile;
1796 $this->address = $contact->address;
1797 $this->zip = $contact->zip;
1798 $this->town = $contact->town;
1799 $this->setUpperOrLowerCase();
1800 $this->state_id = $contact->state_id;
1801 $this->country_id = $contact->country_id;
1802 $this->employee = 0;
1803
1804 if (empty($login)) {
1805 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1806 $login = dol_buildlogin($contact->lastname, $contact->firstname);
1807 }
1808 $this->login = $login;
1809
1810 $this->db->begin();
1811
1812 // Create user and set $this->id. Trigger is disabled because executed later.
1813 $result = $this->create($user, 1);
1814 if ($result > 0) {
1815 $sql = "UPDATE ".$this->db->prefix()."user";
1816 $sql .= " SET fk_socpeople=".((int) $contact->id);
1817 $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
1818 if ($contact->socid > 0) {
1819 $sql .= ", fk_soc=".((int) $contact->socid);
1820 }
1821 $sql .= " WHERE rowid=".((int) $this->id);
1822
1823 $resql = $this->db->query($sql);
1824
1825 dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1826 if ($resql) {
1827 $this->context['createfromcontact'] = 'createfromcontact';
1828
1829 // Call trigger
1830 $result = $this->call_trigger('USER_CREATE', $user);
1831 if ($result < 0) {
1832 $error++;
1833 $this->db->rollback();
1834 return -1;
1835 }
1836 // End call triggers
1837
1838 $this->db->commit();
1839 return $this->id;
1840 } else {
1841 $this->error = $this->db->error();
1842
1843 $this->db->rollback();
1844 return -1;
1845 }
1846 } else {
1847 // $this->error deja positionne
1848 dol_syslog(get_class($this)."::create_from_contact - 0");
1849
1850 $this->db->rollback();
1851 return $result;
1852 }
1853 }
1854
1855 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1864 public function create_from_member($member, $login = '')
1865 {
1866 // phpcs:enable
1867 global $user;
1868
1869 // Set properties on new user
1870 $this->admin = 0;
1871 $this->civility_code = $member->civility_code;
1872 $this->lastname = $member->lastname;
1873 $this->firstname = $member->firstname;
1874 $this->gender = $member->gender;
1875 $this->email = $member->email;
1876 $this->fk_member = $member->id;
1877 $this->address = $member->address;
1878 $this->zip = $member->zip;
1879 $this->town = $member->town;
1880 $this->setUpperOrLowerCase();
1881 $this->state_id = $member->state_id;
1882 $this->country_id = $member->country_id;
1883 $this->socialnetworks = $member->socialnetworks;
1884
1885 $this->pass = $member->pass;
1886 $this->pass_crypted = $member->pass_indatabase_crypted;
1887
1888 if (empty($login)) {
1889 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1890 $login = dol_buildlogin($member->lastname, $member->firstname);
1891 }
1892 $this->login = $login;
1893
1894 $this->db->begin();
1895
1896 // Create and set $this->id
1897 $result = $this->create($user);
1898 if ($result > 0) {
1899 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
1900 $newpass = $this->setPassword($user, $this->pass);
1901 if (is_int($newpass) && $newpass < 0) {
1902 $result = -2;
1903 }
1904 } elseif (!empty($this->pass_crypted)) { // If an encrypted password is already known, we save it directly into database because the previous create did not save it.
1905 $sql = "UPDATE ".$this->db->prefix()."user";
1906 $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
1907 $sql .= " WHERE rowid=".((int) $this->id);
1908
1909 $resql = $this->db->query($sql);
1910 if (!$resql) {
1911 $result = -1;
1912 }
1913 }
1914
1915 if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
1916 $sql = "UPDATE ".$this->db->prefix()."user";
1917 $sql .= " SET fk_soc=".((int) $member->socid);
1918 $sql .= " WHERE rowid=".((int) $this->id);
1919
1920 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
1921 $resql = $this->db->query($sql);
1922 if ($resql) {
1923 $this->db->commit();
1924 return $this->id;
1925 } else {
1926 $this->error = $this->db->lasterror();
1927
1928 $this->db->rollback();
1929 return -1;
1930 }
1931 }
1932 }
1933
1934 if ($result > 0) {
1935 $this->db->commit();
1936 return $this->id;
1937 } else {
1938 // $this->error deja positionne
1939 $this->db->rollback();
1940 return -2;
1941 }
1942 }
1943
1944 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1950 public function set_default_rights()
1951 {
1952 // phpcs:enable
1953 global $conf;
1954
1955 $rd = array();
1956 $num = 0;
1957 $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
1958 $sql .= " WHERE bydefault = 1";
1959 $sql .= " AND entity = ".((int) $conf->entity);
1960
1961 $resql = $this->db->query($sql);
1962 if ($resql) {
1963 $num = $this->db->num_rows($resql);
1964 $i = 0;
1965 while ($i < $num) {
1966 $row = $this->db->fetch_row($resql);
1967 $rd[$i] = $row[0];
1968 $i++;
1969 }
1970 $this->db->free($resql);
1971 }
1972 $i = 0;
1973 while ($i < $num) {
1974 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
1975 $result = $this->db->query($sql);
1976
1977 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
1978 $result = $this->db->query($sql);
1979 if (!$result) {
1980 return -1;
1981 }
1982 $i++;
1983 }
1984
1985 return $i;
1986 }
1987
1998 public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
1999 {
2000 global $conf, $langs;
2001
2002 $nbrowsaffected = 0;
2003 $error = 0;
2004
2005 dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
2006
2007 // Clean parameters
2008 $this->civility_code = trim((string) $this->civility_code);
2009 $this->lastname = trim((string) $this->lastname);
2010 $this->firstname = trim((string) $this->firstname);
2011 $this->ref_employee = trim((string) $this->ref_employee);
2012 $this->national_registration_number = trim((string) $this->national_registration_number);
2013 $this->employee = ($this->employee > 0 ? $this->employee : 0);
2014 $this->login = trim((string) $this->login);
2015 $this->gender = trim((string) $this->gender);
2016
2017 $this->pass = trim((string) $this->pass);
2018 $this->api_key = trim((string) $this->api_key);
2019 $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
2020 $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
2021
2022 $this->address = trim((string) $this->address);
2023 $this->zip = trim((string) $this->zip);
2024 $this->town = trim((string) $this->town);
2025
2026 $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
2027 $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
2028 $this->office_phone = trim((string) $this->office_phone);
2029 $this->office_fax = trim((string) $this->office_fax);
2030 $this->user_mobile = trim((string) $this->user_mobile);
2031 $this->personal_mobile = trim((string) $this->personal_mobile);
2032 $this->email = trim((string) $this->email);
2033 $this->personal_email = trim((string) $this->personal_email);
2034
2035 $this->job = trim((string) $this->job);
2036 $this->signature = trim((string) $this->signature);
2037 $this->note_public = trim((string) $this->note_public);
2038 $this->note_private = trim((string) $this->note_private);
2039 $this->openid = trim((string) $this->openid);
2040 $this->admin = ($this->admin > 0 ? $this->admin : 0);
2041
2042 $this->accountancy_code = trim((string) $this->accountancy_code);
2043 $this->color = trim((string) $this->color);
2044 $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
2045 $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
2046
2047 $this->birth = empty($this->birth) ? '' : $this->birth;
2048 $this->fk_warehouse = (int) $this->fk_warehouse;
2049 $this->fk_establishment = (int) $this->fk_establishment;
2050
2051 $this->setUpperOrLowerCase();
2052
2053 // Check parameters
2054 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
2055
2056 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
2057 $langs->load("errors");
2058 $this->error = $langs->trans("ErrorBadEMail", $this->email);
2059 return -1;
2060 }
2061 if (empty($this->login)) {
2062 $langs->load("errors");
2063 $this->error = $langs->trans("ErrorFieldRequired", 'Login');
2064 return -1;
2065 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
2066 $langs->load("errors");
2067 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
2068 return -1;
2069 }
2070
2071 $this->db->begin();
2072
2073 // Check if login already exists in same entity or into entity 0.
2074 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->oldcopy->login != $this->login) {
2075 $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)."'";
2076 $resqltochecklogin = $this->db->query($sqltochecklogin);
2077 if ($resqltochecklogin) {
2078 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2079 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2080 $langs->load("errors");
2081 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
2082 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2083 $this->db->rollback();
2084 return -1;
2085 }
2086 }
2087 }
2088 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && !empty($this->email) && $this->oldcopy->email != $this->email) {
2089 $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)."'";
2090 $resqltochecklogin = $this->db->query($sqltochecklogin);
2091 if ($resqltochecklogin) {
2092 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2093 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2094 $langs->load("errors");
2095 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
2096 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2097 $this->db->rollback();
2098 return -1;
2099 }
2100 }
2101 }
2102
2103 // Update data
2104 $sql = "UPDATE ".$this->db->prefix()."user SET";
2105 $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
2106 $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
2107 $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
2108 $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
2109 $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
2110 $sql .= ", employee = ".(int) $this->employee;
2111 $sql .= ", login = '".$this->db->escape($this->login)."'";
2112 $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
2113 $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' or 'other'
2114 $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
2115 if (!empty($user->admin)) {
2116 $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
2117 }
2118 $sql .= ", address = '".$this->db->escape($this->address)."'";
2119 $sql .= ", zip = '".$this->db->escape($this->zip)."'";
2120 $sql .= ", town = '".$this->db->escape($this->town)."'";
2121 $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".$this->db->escape($this->state_id)."'" : "null");
2122 $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".$this->db->escape($this->country_id)."'" : "null");
2123 $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
2124 $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
2125 $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
2126 $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
2127 $sql .= ", email = '".$this->db->escape($this->email)."'";
2128 $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
2129 $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
2130 $sql .= ", job = '".$this->db->escape($this->job)."'";
2131 $sql .= ", signature = '".$this->db->escape($this->signature)."'";
2132 $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
2133 $sql .= ", color = '".$this->db->escape($this->color)."'";
2134 $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
2135 $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
2136 $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2137 $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2138 $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2139 $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2140 $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2141 $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2142 $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".$this->db->escape($this->fk_user)."'" : "null");
2143 $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".$this->db->escape($this->fk_user_expense_validator)."'" : "null");
2144 $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".$this->db->escape($this->fk_user_holiday_validator)."'" : "null");
2145 if (isset($this->thm) || $this->thm != '') {
2146 $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2147 }
2148 if (isset($this->tjm) || $this->tjm != '') {
2149 $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2150 }
2151 if (isset($this->salary) || $this->salary != '') {
2152 $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2153 }
2154 if (isset($this->salaryextra) || $this->salaryextra != '') {
2155 $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2156 }
2157 $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2158 if (!empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2159 $sql .= ", entity = ".((int) $this->entity); // entity flag can be set/unset only by an another superadmin user
2160 }
2161 $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
2162 $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
2163 $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "null");
2164 $sql .= ", fk_establishment = ".($this->fk_establishment > 0 ? $this->fk_establishment : "null");
2165 $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2166 $sql .= " WHERE rowid = ".((int) $this->id);
2167
2168 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2169 $resql = $this->db->query($sql);
2170 if ($resql) {
2171 $nbrowsaffected += $this->db->affected_rows($resql);
2172
2173 // Update password
2174 if (!empty($this->pass)) {
2175 if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2176 // If a new value for password is set and different than the one encrypted into database
2177 $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2178 if (is_int($result) && $result < 0) {
2179 return -5;
2180 }
2181 }
2182 }
2183
2184 // If user is linked to a member, remove old link to this member
2185 if ($this->fk_member > 0) {
2186 dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2187 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2188 $resql = $this->db->query($sql);
2189 if (!$resql) {
2190 $this->error = $this->db->error();
2191 $this->db->rollback();
2192 return -5;
2193 }
2194 }
2195 // Set link to user
2196 dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2197 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2198 $resql = $this->db->query($sql);
2199 if (!$resql) {
2200 $this->error = $this->db->error();
2201 $this->db->rollback();
2202 return -5;
2203 }
2204
2205 if ($nbrowsaffected) { // If something has changed in data
2206 if ($this->fk_member > 0 && !$nosyncmember) {
2207 dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2208
2209 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2210
2211 // This user is linked with a member, so we also update member information
2212 // if this is an update.
2213 $adh = new Adherent($this->db);
2214 $result = $adh->fetch($this->fk_member);
2215
2216 if ($result > 0) {
2217 $adh->civility_code = $this->civility_code;
2218 $adh->firstname = $this->firstname;
2219 $adh->lastname = $this->lastname;
2220 $adh->login = $this->login;
2221 $adh->gender = $this->gender;
2222 $adh->birth = $this->birth;
2223
2224 $adh->pass = $this->pass;
2225
2226 $adh->address = $this->address;
2227 $adh->town = $this->town;
2228 $adh->zip = $this->zip;
2229 $adh->state_id = $this->state_id;
2230 $adh->country_id = $this->country_id;
2231
2232 $adh->email = $this->email;
2233
2234 $adh->socialnetworks = $this->socialnetworks;
2235
2236 $adh->phone = $this->office_phone;
2237 $adh->phone_mobile = $this->user_mobile;
2238
2239 $adh->default_lang = $this->lang;
2240
2241 $adh->user_id = $this->id;
2242 $adh->user_login = $this->login;
2243
2244 $result = $adh->update($user, 0, 1, 0);
2245 if ($result < 0) {
2246 $this->error = $adh->error;
2247 $this->errors = $adh->errors;
2248 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2249 $error++;
2250 }
2251 } elseif ($result < 0) {
2252 $this->error = $adh->error;
2253 $this->errors = $adh->errors;
2254 $error++;
2255 }
2256 }
2257
2258 if ($this->contact_id > 0 && !$nosynccontact) {
2259 dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2260
2261 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2262
2263 // This user is linked with a contact, so we also update contact information if this is an update.
2264 $tmpobj = new Contact($this->db);
2265 $result = $tmpobj->fetch($this->contact_id);
2266
2267 if ($result >= 0) {
2268 $tmpobj->civility_code = $this->civility_code;
2269 $tmpobj->firstname = $this->firstname;
2270 $tmpobj->lastname = $this->lastname;
2271 $tmpobj->login = $this->login;
2272 $tmpobj->gender = $this->gender;
2273 $tmpobj->birth = $this->birth;
2274
2275 //$tmpobj->pass=$this->pass;
2276
2277 $tmpobj->email = $this->email;
2278
2279 $tmpobj->socialnetworks = $this->socialnetworks;
2280
2281 $tmpobj->phone_pro = $this->office_phone;
2282 $tmpobj->phone_mobile = $this->user_mobile;
2283 $tmpobj->fax = $this->office_fax;
2284
2285 $tmpobj->default_lang = $this->lang;
2286
2287 $tmpobj->address = $this->address;
2288 $tmpobj->town = $this->town;
2289 $tmpobj->zip = $this->zip;
2290 $tmpobj->state_id = $this->state_id;
2291 $tmpobj->country_id = $this->country_id;
2292
2293 $tmpobj->user_id = $this->id;
2294 $tmpobj->user_login = $this->login;
2295
2296 $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2297 if ($result < 0) {
2298 $this->error = $tmpobj->error;
2299 $this->errors = $tmpobj->errors;
2300 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2301 $error++;
2302 }
2303 } else {
2304 $this->error = $tmpobj->error;
2305 $this->errors = $tmpobj->errors;
2306 $error++;
2307 }
2308 }
2309 }
2310
2311 $action = 'update';
2312
2313 // Actions on extra fields
2314 if (!$error) {
2315 $result = $this->insertExtraFields();
2316 if ($result < 0) {
2317 $error++;
2318 }
2319 }
2320
2321 if (!$error && !$notrigger) {
2322 // Call trigger
2323 $result = $this->call_trigger('USER_MODIFY', $user);
2324 if ($result < 0) {
2325 $error++;
2326 }
2327 // End call triggers
2328 }
2329
2330 if (!$error) {
2331 $this->db->commit();
2332 return $nbrowsaffected;
2333 } else {
2334 dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2335 $this->db->rollback();
2336 return -1;
2337 }
2338 } else {
2339 $this->error = $this->db->lasterror();
2340 $this->db->rollback();
2341 return -2;
2342 }
2343 }
2344
2345 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2352 public function update_last_login_date()
2353 {
2354 // phpcs:enable
2355 $now = dol_now();
2356
2357 $userremoteip = getUserRemoteIP();
2358
2359 $sql = "UPDATE ".$this->db->prefix()."user SET";
2360 $sql .= " datepreviouslogin = datelastlogin,";
2361 $sql .= " ippreviouslogin = iplastlogin,";
2362 $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2363 $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2364 $sql .= " tms = tms"; // The last update date must change because the last login date is updated
2365 $sql .= " WHERE rowid = ".((int) $this->id);
2366
2367 dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2368 $resql = $this->db->query($sql);
2369 if ($resql) {
2370 $this->datepreviouslogin = $this->datelastlogin;
2371 $this->datelastlogin = $now;
2372 $this->ippreviouslogin = $this->iplastlogin;
2373 $this->iplastlogin = $userremoteip;
2374 return 1;
2375 } else {
2376 $this->error = $this->db->lasterror().' sql='.$sql;
2377 return -1;
2378 }
2379 }
2380
2381
2394 public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2395 {
2396 global $conf, $langs;
2397 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2398
2399 $error = 0;
2400
2401 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2402
2403 // If new password not provided, we generate one
2404 if (!$password) {
2405 $password = getRandomPassword(false);
2406 }
2407
2408 // Check and encrypt the password
2409 if (empty($passwordalreadycrypted)) {
2410 if (getDolGlobalString('USER_PASSWORD_GENERATED')) {
2411 // Add a check on rules for password syntax using the setup of the password generator
2412 $modGeneratePassClass = 'modGeneratePass'.ucfirst($conf->global->USER_PASSWORD_GENERATED);
2413
2414 include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2415 if (class_exists($modGeneratePassClass)) {
2416 $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2417
2418 // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2419 $modGeneratePass->WithoutAmbi = 0;
2420
2421 // Call to validatePassword($password) to check pass match rules
2422 $testpassword = $modGeneratePass->validatePassword($password);
2423 if (!$testpassword) {
2424 $this->error = $modGeneratePass->error;
2425 return -1;
2426 }
2427 }
2428 }
2429
2430
2431 // Now, we encrypt the new password
2432 $password_crypted = dol_hash($password);
2433 }
2434
2435 // Update password
2436 if (!$changelater) {
2437 if (!is_object($this->oldcopy)) {
2438 $this->oldcopy = clone $this;
2439 }
2440
2441 $this->db->begin();
2442
2443 $sql = "UPDATE ".$this->db->prefix()."user";
2444 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2445 $sql .= " pass_temp = null";
2446 if (!empty($flagdelsessionsbefore)) {
2447 $sql .= ", flagdelsessionsbefore = '".$this->db->idate(dol_now() - 5, 'gmt')."'";
2448 }
2449 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
2450 $sql .= ", pass = null";
2451 } else {
2452 $sql .= ", pass = '".$this->db->escape($password)."'";
2453 }
2454 $sql .= " WHERE rowid = ".((int) $this->id);
2455
2456 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2457 $result = $this->db->query($sql);
2458 if ($result) {
2459 if ($this->db->affected_rows($result)) {
2460 $this->pass = $password;
2461 $this->pass_indatabase = $password;
2462 $this->pass_indatabase_crypted = $password_crypted;
2463
2464 if ($this->fk_member && !$nosyncmember) {
2465 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2466
2467 // This user is linked with a member, so we also update members information
2468 // if this is an update.
2469 $adh = new Adherent($this->db);
2470 $result = $adh->fetch($this->fk_member);
2471
2472 if ($result >= 0) {
2473 $result = $adh->setPassword($user, $this->pass, (!getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 0 : 1), 1); // The encryption is not managed in the 'adherent' module
2474 if (is_int($result) && $result < 0) {
2475 $this->error = $adh->error;
2476 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2477 $error++;
2478 }
2479 } else {
2480 $this->error = $adh->error;
2481 $error++;
2482 }
2483 }
2484
2485 dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2486
2487 if (!$error && !$notrigger) {
2488 // Call trigger
2489 $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2490 if ($result < 0) {
2491 $error++;
2492 $this->db->rollback();
2493 return -1;
2494 }
2495 // End call triggers
2496 }
2497
2498 $this->db->commit();
2499 return $this->pass;
2500 } else {
2501 $this->db->rollback();
2502 return 0;
2503 }
2504 } else {
2505 $this->db->rollback();
2506 dol_print_error($this->db);
2507 return -1;
2508 }
2509 } else {
2510 // We store password in password temporary field.
2511 // After receiving confirmation link, we will erase and store it in pass_crypted
2512 $sql = "UPDATE ".$this->db->prefix()."user";
2513 $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2514 $sql .= " WHERE rowid = ".((int) $this->id);
2515
2516 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2517 $result = $this->db->query($sql);
2518 if ($result) {
2519 return $password;
2520 } else {
2521 dol_print_error($this->db);
2522 return -3;
2523 }
2524 }
2525 }
2526
2527 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2536 public function send_password($user, $password = '', $changelater = 0)
2537 {
2538 // phpcs:enable
2539 global $conf, $langs, $mysoc;
2540 global $dolibarr_main_url_root;
2541
2542 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2543
2544 $msgishtml = 0;
2545
2546 // Define $msg
2547 $mesg = '';
2548
2549 $outputlangs = new Translate("", $conf);
2550
2551 if (isset($this->conf->MAIN_LANG_DEFAULT)
2552 && $this->conf->MAIN_LANG_DEFAULT != 'auto') { // If user has defined its own language (rare because in most cases, auto is used)
2553 $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2554 }
2555
2556 if ($this->conf->MAIN_LANG_DEFAULT) {
2557 $outputlangs->setDefaultLang($this->conf->MAIN_LANG_DEFAULT);
2558 } else { // If user has not defined its own language, we used current language
2559 $outputlangs = $langs;
2560 }
2561
2562 // Load translation files required by the page
2563 $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2564
2565 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', constant('DOL_APPLICATION_TITLE'));
2566
2567 $subject = '['.$appli.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2568
2569 // Define $urlwithroot
2570 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2571 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2572
2573 if (!$changelater) {
2574 $url = $urlwithroot.'/';
2575 if (getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD')) {
2576 $url = getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD');
2577 }
2578
2579 dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2580
2581 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2582 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2583 $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2584 $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2585 $mesg .= "\n";
2586
2587 $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2588 $mesg .= "--\n";
2589 $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2590 } else {
2591 //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2592 $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2593 $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2594 if (isModEnabled('multicompany')) {
2595 $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2596 }
2597
2598 dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2599
2600 $msgishtml = 1;
2601
2602 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2603 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2604 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2605 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2606 $mesg .= "<br>\n";
2607 $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2608 $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2609 $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2610 }
2611
2612 $trackid = 'use'.$this->id;
2613 $sendcontext = 'password';
2614
2615 $mailfile = new CMailFile(
2616 $subject,
2617 $this->email,
2618 $conf->global->MAIN_MAIL_EMAIL_FROM,
2619 $mesg,
2620 array(),
2621 array(),
2622 array(),
2623 '',
2624 '',
2625 0,
2626 $msgishtml,
2627 '',
2628 '',
2629 $trackid,
2630 '',
2631 $sendcontext
2632 );
2633
2634 if ($mailfile->sendfile()) {
2635 return 1;
2636 } else {
2637 $langs->trans("errors");
2638 $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2639 return -1;
2640 }
2641 }
2642
2648 public function error()
2649 {
2650 return $this->error;
2651 }
2652
2653
2654 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2660 public function fetch_clicktodial()
2661 {
2662 // phpcs:enable
2663 $sql = "SELECT url, login, pass, poste ";
2664 $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2665 $sql .= " WHERE u.fk_user = ".((int) $this->id);
2666
2667 $resql = $this->db->query($sql);
2668 if ($resql) {
2669 if ($this->db->num_rows($resql)) {
2670 $obj = $this->db->fetch_object($resql);
2671
2672 $this->clicktodial_url = $obj->url;
2673 $this->clicktodial_login = $obj->login;
2674 $this->clicktodial_password = $obj->pass;
2675 $this->clicktodial_poste = $obj->poste;
2676 }
2677
2678 $this->clicktodial_loaded = 1; // Data loaded (found or not)
2679
2680 $this->db->free($resql);
2681 return 1;
2682 } else {
2683 $this->error = $this->db->error();
2684 return -1;
2685 }
2686 }
2687
2688 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2694 public function update_clicktodial()
2695 {
2696 // phpcs:enable
2697 $this->db->begin();
2698
2699 $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2700 $sql .= " WHERE fk_user = ".((int) $this->id);
2701
2702 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2703 $result = $this->db->query($sql);
2704
2705 $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
2706 $sql .= " (fk_user,url,login,pass,poste)";
2707 $sql .= " VALUES (".$this->id;
2708 $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2709 $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2710 $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2711 $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2712
2713 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2714 $result = $this->db->query($sql);
2715 if ($result) {
2716 $this->db->commit();
2717 return 1;
2718 } else {
2719 $this->db->rollback();
2720 $this->error = $this->db->lasterror();
2721 return -1;
2722 }
2723 }
2724
2725
2726 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2735 public function SetInGroup($group, $entity, $notrigger = 0)
2736 {
2737 // phpcs:enable
2738 global $conf, $langs, $user;
2739
2740 $error = 0;
2741
2742 $this->db->begin();
2743
2744 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2745 $sql .= " WHERE fk_user = ".((int) $this->id);
2746 $sql .= " AND fk_usergroup = ".((int) $group);
2747 $sql .= " AND entity = ".((int) $entity);
2748
2749 $result = $this->db->query($sql);
2750
2751 $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
2752 $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
2753
2754 $result = $this->db->query($sql);
2755 if ($result) {
2756 if (!$error && !$notrigger) {
2757 $this->context = array('audit' => $langs->trans("UserSetInGroup"), 'newgroupid' => $group);
2758
2759 // Call trigger
2760 $result = $this->call_trigger('USER_MODIFY', $user);
2761 if ($result < 0) {
2762 $error++;
2763 }
2764 // End call triggers
2765 }
2766
2767 if (!$error) {
2768 $this->db->commit();
2769 return 1;
2770 } else {
2771 dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2772 $this->db->rollback();
2773 return -2;
2774 }
2775 } else {
2776 $this->error = $this->db->lasterror();
2777 $this->db->rollback();
2778 return -1;
2779 }
2780 }
2781
2782 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2791 public function RemoveFromGroup($group, $entity, $notrigger = 0)
2792 {
2793 // phpcs:enable
2794 global $conf, $langs, $user;
2795
2796 $error = 0;
2797
2798 $this->db->begin();
2799
2800 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2801 $sql .= " WHERE fk_user = ".((int) $this->id);
2802 $sql .= " AND fk_usergroup = ".((int) $group);
2803 if (empty($entity)) {
2804 $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
2805 } else {
2806 $sql .= " AND entity = ".((int) $entity);
2807 }
2808
2809 $result = $this->db->query($sql);
2810 if ($result) {
2811 if (!$error && !$notrigger) {
2812 $this->context = array('audit' => $langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
2813
2814 // Call trigger
2815 $result = $this->call_trigger('USER_MODIFY', $user);
2816 if ($result < 0) {
2817 $error++;
2818 }
2819 // End call triggers
2820 }
2821
2822 if (!$error) {
2823 $this->db->commit();
2824 return 1;
2825 } else {
2826 dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2827 $this->db->rollback();
2828 return -2;
2829 }
2830 } else {
2831 $this->error = $this->db->lasterror();
2832 $this->db->rollback();
2833 return -1;
2834 }
2835 }
2836
2837
2845 {
2846 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2847
2848 $now = dol_now();
2849
2850 //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
2851
2852 // Check date start validity
2853 if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
2854 return 1;
2855 }
2856 // Check date end validity
2857 if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
2858 return 1;
2859 }
2860
2861 return 0;
2862 }
2863
2864
2876 public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
2877 {
2878 $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2879 $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
2880 $result .= '</a>';
2881
2882 return $result;
2883 }
2884
2892 public function getTooltipContentArray($params)
2893 {
2894 global $conf, $langs, $menumanager;
2895 global $dolibarr_main_demo;
2896
2897 $infologin = $params['infologin'] ?? 0;
2898 $option = $params['option'] ?? '';
2899
2900 $data = [];
2901 if (!empty($this->photo)) {
2902 $photo = '<div class="photointooltip floatright">';
2903 $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
2904 $photo .= '</div>';
2905 $data['photo'] = $photo;
2906 //$label .= '<div style="clear: both;"></div>';
2907 }
2908
2909 // Info Login
2910 $data['opendiv'] = '<div class="centpercent divtooltip">';
2911 $data['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
2912 $data['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs, ''));
2913 if (!empty($this->login)) {
2914 $data['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
2915 }
2916 if (!empty($this->job)) {
2917 $data['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
2918 }
2919 $data['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
2920 if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
2921 $phonelist = array();
2922 if ($this->office_phone) {
2923 $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2924 }
2925 if ($this->office_fax) {
2926 $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2927 }
2928 if ($this->user_mobile) {
2929 $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
2930 }
2931 $data['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
2932 }
2933 if (!empty($this->admin)) {
2934 $data['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
2935 }
2936 if (!empty($this->accountancy_code) || $option == 'accountancy') {
2937 $langs->load("companies");
2938 $data['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
2939 }
2940 $company = '';
2941 if (!empty($this->socid)) { // Add thirdparty for external users
2942 $thirdpartystatic = new Societe($this->db);
2943 $thirdpartystatic->fetch($this->socid);
2944 $companyimg = '';
2945 if (empty($params['hidethirdpartylogo'])) {
2946 $companyimg = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
2947 }
2948 $company = ' ('.$langs->trans("Company").': '.($companyimg ? $companyimg : img_picto('', 'company')).' '.dol_string_nohtmltag($thirdpartystatic->name).')';
2949 }
2950 $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
2951 $data['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
2952 $data['closediv'] = '</div>';
2953
2954 if ($infologin > 0) {
2955 $data['newlinelogin'] = '<br>';
2956 $data['session'] = '<br><u>'.$langs->trans("Session").'</u>';
2957 $data['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
2958 if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
2959 $data['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
2960 }
2961 $data['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
2962 $data['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
2963 $data['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
2964 $data['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
2965 $data['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
2966 $s = picto_from_langcode($langs->getDefaultLang());
2967 $data['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
2968 $data['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
2969 $data['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
2970 $data['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
2971 if ($conf->browser->layout == 'phone') {
2972 $data['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
2973 }
2974 if (!empty($_SESSION["disablemodules"])) {
2975 $data['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(implode(', ', explode(',', $_SESSION["disablemodules"])));
2976 }
2977 }
2978
2979 return $data;
2980 }
2981
2997 public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
2998 {
2999 global $langs, $hookmanager, $user;
3000
3001 if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
3002 $option = 'nolink';
3003 }
3004
3005 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
3006 $withpictoimg = 0;
3007 }
3008
3009 $result = '';
3010 $params = [
3011 'id' => $this->id,
3012 'objecttype' => $this->element,
3013 'infologin' => $infologin,
3014 'option' => $option,
3015 'hidethirdpartylogo' => $hidethirdpartylogo,
3016 ];
3017 $classfortooltip = 'classfortooltip';
3018 $dataparams = '';
3019 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3020 $classfortooltip = 'classforajaxtooltip';
3021 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3022 $label = '';
3023 } else {
3024 $label = implode($this->getTooltipContentArray($params));
3025 }
3026
3027 $companylink = '';
3028 if (!empty($this->socid)) { // Add thirdparty for external users
3029 $thirdpartystatic = new Societe($this->db);
3030 $thirdpartystatic->fetch($this->socid);
3031 if (empty($hidethirdpartylogo)) {
3032 $companylink = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3033 }
3034 }
3035
3036 if ($infologin < 0) {
3037 $label = '';
3038 }
3039
3040 $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id;
3041 if ($option == 'leave') {
3042 $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id;
3043 }
3044
3045 if ($option != 'nolink') {
3046 // Add param to save lastsearch_values or not
3047 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3048 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3049 $add_save_lastsearch_values = 1;
3050 }
3051 if ($add_save_lastsearch_values) {
3052 $url .= '&save_lastsearch_values=1';
3053 }
3054 }
3055
3056 $linkstart = '<a href="'.$url.'"';
3057 $linkclose = "";
3058 if (empty($notooltip)) {
3059 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3060 $langs->load("users");
3061 $label = $langs->trans("ShowUser");
3062 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
3063 }
3064 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3065 $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
3066 } else {
3067 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
3068 }
3069
3070 $linkstart .= $linkclose.'>';
3071 $linkend = '</a>';
3072
3073 //if ($withpictoimg == -1) $result.='<div class="nowrap">';
3074 $result .= (($option == 'nolink') ? '' : $linkstart);
3075 if ($withpictoimg) {
3076 $paddafterimage = '';
3077 if (abs((int) $withpictoimg) == 1) {
3078 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3079 }
3080 // Only picto
3081 if ($withpictoimg > 0) {
3082 $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>';
3083 } else {
3084 // Picto must be a photo
3085 $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>';
3086 }
3087 $result .= $picto;
3088 }
3089 if ($withpictoimg > -2 && $withpictoimg != 2) {
3090 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3091 $result .= '<span class="nopadding usertext'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
3092 }
3093 if ($mode == 'login') {
3094 $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
3095 } else {
3096 $result .= dol_string_nohtmltag($this->getFullName($langs, '', ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
3097 }
3098 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3099 $result .= '</span>';
3100 }
3101 }
3102 $result .= (($option == 'nolink') ? '' : $linkend);
3103 //if ($withpictoimg == -1) $result.='</div>';
3104
3105 $result .= $companylink;
3106
3107 global $action;
3108 $hookmanager->initHooks(array('userdao'));
3109 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
3110 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3111 if ($reshook > 0) {
3112 $result = $hookmanager->resPrint;
3113 } else {
3114 $result .= $hookmanager->resPrint;
3115 }
3116
3117 return $result;
3118 }
3119
3129 public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
3130 {
3131 global $langs, $user;
3132
3133 $result = '';
3134
3135 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3136 $linkend = '</a>';
3137
3138 //Check user's rights to see an other user
3139 if ((!$user->hasRight('user', 'user', 'lire') && $this->id != $user->id)) {
3140 $option = 'nolink';
3141 }
3142
3143 if ($option == 'xxx') {
3144 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3145 $linkend = '</a>';
3146 }
3147
3148 if ($option == 'nolink') {
3149 $linkstart = '';
3150 $linkend = '';
3151 }
3152
3153 $result .= $linkstart;
3154 if ($withpictoimg) {
3155 $paddafterimage = '';
3156 if (abs($withpictoimg) == 1) {
3157 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3158 }
3159 // Only picto
3160 if ($withpictoimg > 0) {
3161 $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3162 } else {
3163 // Picto must be a photo
3164 $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>';
3165 }
3166 $result .= $picto;
3167 }
3168 $result .= $this->login;
3169 $result .= $linkend;
3170
3171 return $result;
3172 }
3173
3180 public function getLibStatut($mode = 0)
3181 {
3182 return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3183 }
3184
3185 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3193 public function LibStatut($status, $mode = 0)
3194 {
3195 // phpcs:enable
3196 global $langs;
3197
3198 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3199 global $langs;
3200 //$langs->load("mymodule");
3201 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3202 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3203 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3204 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3205 }
3206
3207 $statusType = 'status5';
3208 if ($status == self::STATUS_ENABLED) {
3209 $statusType = 'status4';
3210 }
3211
3212 $label = $this->labelStatus[$status];
3213 $labelshort = $this->labelStatusShort[$status];
3214
3215 $now = dol_now();
3216 if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3217 $statusType = 'status3';
3218 $label .= ' ('.$langs->trans("UserNotYetValid").')';
3219 }
3220 if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3221 $statusType = 'status2';
3222 $label .= ' ('.$langs->trans("UserExpired").')';
3223 }
3224
3225 return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3226 }
3227
3228
3236 public function getKanbanView($option = '', $arraydata = null)
3237 {
3238 global $langs;
3239
3240 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3241
3242 $return = '<div class="box-flex-item box-flex-grow-zero">';
3243 $return .= '<div class="info-box info-box-sm">';
3244 $return .= '<span class="info-box-icon bg-infobox-action">';
3245
3246 $label = '';
3247 if (!empty($this->photo)) {
3248 //$label .= '<div class="photointooltip floatright">';
3249 $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
3250 //$label .= '</div>';
3251 //$label .= '<div style="clear: both;"></div>';
3252 $return .= $label;
3253 } else {
3254 $return .= img_picto('', $this->picto);
3255 }
3256
3257 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3258 $return .= '</span>';
3259 $return .= '<div class="info-box-content">';
3260 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3261 if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3262 $return .= img_picto($langs->trans("SuperAdministratorDesc"), 'redstar', 'class="valignmiddle paddingright paddingleft"');
3263 } elseif ($this->admin) {
3264 $return .= img_picto($langs->trans("AdministratorDesc"), 'star', 'class="valignmiddle paddingright paddingleft"');
3265 }
3266 $return .= '</span>';
3267 if ($selected >= 0) {
3268 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3269 }
3270 if (property_exists($this, 'label')) {
3271 $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3272 }
3273 if ($this->email) {
3274 $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3275 }
3276 if (method_exists($this, 'getLibStatut')) {
3277 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3278 }
3279 $return .= '</div>';
3280 $return .= '</div>';
3281 $return .= '</div>';
3282
3283 return $return;
3284 }
3285
3286
3287 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3288 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3298 public function _load_ldap_dn($info, $mode = 0)
3299 {
3300 // phpcs:enable
3301 global $conf;
3302 $dn = '';
3303 if ($mode == 0) {
3304 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')]."," . getDolGlobalString('LDAP_USER_DN');
3305 } elseif ($mode == 1) {
3306 $dn = getDolGlobalString('LDAP_USER_DN');
3307 } elseif ($mode == 2) {
3308 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')];
3309 }
3310 return $dn;
3311 }
3312
3313 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3314 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3320 public function _load_ldap_info()
3321 {
3322 // phpcs:enable
3323 global $conf, $langs;
3324
3325 $info = array();
3326
3327 $socialnetworks = getArrayOfSocialNetworks();
3328
3329 $keymodified = false;
3330
3331 // Object classes
3332 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_USER_OBJECT_CLASS'));
3333
3334 $this->fullname = $this->getFullName($langs);
3335
3336 // Possible LDAP KEY (constname => varname)
3337 $ldapkey = array(
3338 'LDAP_FIELD_FULLNAME' => 'fullname',
3339 'LDAP_FIELD_NAME' => 'lastname',
3340 'LDAP_FIELD_FIRSTNAME' => 'firstname',
3341 'LDAP_FIELD_LOGIN' => 'login',
3342 'LDAP_FIELD_LOGIN_SAMBA' => 'login',
3343 'LDAP_FIELD_PHONE' => 'office_phone',
3344 'LDAP_FIELD_MOBILE' => 'user_mobile',
3345 'LDAP_FIELD_FAX' => 'office_fax',
3346 'LDAP_FIELD_MAIL' => 'email',
3347 'LDAP_FIELD_SID' => 'ldap_sid',
3348 );
3349
3350 // Champs
3351 foreach ($ldapkey as $constname => $varname) {
3352 if (!empty($this->$varname) && getDolGlobalString($constname)) {
3353 $info[getDolGlobalString($constname)] = $this->$varname;
3354
3355 // Check if it is the LDAP key and if its value has been changed
3356 if (getDolGlobalString('LDAP_KEY_USERS') && $conf->global->LDAP_KEY_USERS == getDolGlobalString($constname)) {
3357 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->$varname != $this->oldcopy->$varname) {
3358 $keymodified = true; // For check if LDAP key has been modified
3359 }
3360 }
3361 }
3362 }
3363 foreach ($socialnetworks as $key => $value) {
3364 if (!empty($this->socialnetworks[$value['label']]) && getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))) {
3365 $info[getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3366 }
3367 }
3368 if ($this->address && getDolGlobalString('LDAP_FIELD_ADDRESS')) {
3369 $info[getDolGlobalString('LDAP_FIELD_ADDRESS')] = $this->address;
3370 }
3371 if ($this->zip && getDolGlobalString('LDAP_FIELD_ZIP')) {
3372 $info[getDolGlobalString('LDAP_FIELD_ZIP')] = $this->zip;
3373 }
3374 if ($this->town && getDolGlobalString('LDAP_FIELD_TOWN')) {
3375 $info[getDolGlobalString('LDAP_FIELD_TOWN')] = $this->town;
3376 }
3377 if ($this->note_public && getDolGlobalString('LDAP_FIELD_DESCRIPTION')) {
3378 $info[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_public, 2);
3379 }
3380 if ($this->socid > 0) {
3381 $soc = new Societe($this->db);
3382 $soc->fetch($this->socid);
3383
3384 $info[getDolGlobalString('LDAP_FIELD_COMPANY')] = $soc->name;
3385 if ($soc->client == 1) {
3386 $info["businessCategory"] = "Customers";
3387 }
3388 if ($soc->client == 2) {
3389 $info["businessCategory"] = "Prospects";
3390 }
3391 if ($soc->fournisseur == 1) {
3392 $info["businessCategory"] = "Suppliers";
3393 }
3394 }
3395
3396 // When password is modified
3397 if (!empty($this->pass)) {
3398 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3399 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass; // this->pass = unencrypted password
3400 }
3401 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3402 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3403 }
3404 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3405 // Set LDAP password if possible
3406 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3407 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
3408 // Just for the default MD5 !
3409 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) {
3410 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3411 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3412 }
3413 }
3414 } elseif (!empty($this->pass_indatabase)) {
3415 // Use $this->pass_indatabase value if exists
3416 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3417 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = unencrypted password
3418 }
3419 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3420 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3421 }
3422 }
3423 }
3424
3425 if (getDolGlobalString('LDAP_SERVER_TYPE') == 'egroupware') {
3426 $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3427
3428 $info['uidnumber'] = $this->id;
3429
3430 $info['phpgwTz'] = 0;
3431 $info['phpgwMailType'] = 'INTERNET';
3432 $info['phpgwMailHomeType'] = 'INTERNET';
3433
3434 $info["phpgwContactTypeId"] = 'n';
3435 $info["phpgwContactCatId"] = 0;
3436 $info["phpgwContactAccess"] = "public";
3437
3438 /*
3439 if (dol_strlen($this->egroupware_id) == 0) {
3440 $this->egroupware_id = 1;
3441 }
3442 $info["phpgwContactOwner"] = $this->egroupware_id;
3443 */
3444 $info["phpgwContactOwner"] = 1;
3445
3446 if ($this->email) {
3447 $info["rfc822Mailbox"] = $this->email;
3448 }
3449 if ($this->user_mobile) {
3450 $info["phpgwCellTelephoneNumber"] = $this->user_mobile;
3451 }
3452 }
3453
3454 if (getDolGlobalString('LDAP_FIELD_USERID')) {
3455 $info[getDolGlobalString('LDAP_FIELD_USERID')] = $this->id;
3456 }
3457 if (getDolGlobalString('LDAP_FIELD_GROUPID')) {
3458 $usergroup = new UserGroup($this->db);
3459 $groupslist = $usergroup->listGroupsForUser($this->id);
3460 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = '65534';
3461 if (!empty($groupslist)) {
3462 foreach ($groupslist as $groupforuser) {
3463 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = $groupforuser->id; //Select first group in list
3464 break;
3465 }
3466 }
3467 }
3468 if (getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY') && getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')) {
3469 $info[getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY')] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->login";
3470 }
3471
3472 return $info;
3473 }
3474
3475
3483 public function initAsSpecimen()
3484 {
3485 global $user, $langs;
3486
3487 $now = dol_now();
3488
3489 // Initialise parameters
3490 $this->id = 0;
3491 $this->ref = 'SPECIMEN';
3492 $this->specimen = 1;
3493
3494 $this->lastname = 'DOLIBARR';
3495 $this->firstname = 'SPECIMEN';
3496 $this->gender = 'man';
3497 $this->note_public = 'This is a note public';
3498 $this->note_private = 'This is a note private';
3499 $this->email = 'email@specimen.com';
3500 $this->personal_email = 'personalemail@specimen.com';
3501 $this->socialnetworks = array(
3502 'skype' => 'skypepseudo',
3503 'twitter' => 'twitterpseudo',
3504 'facebook' => 'facebookpseudo',
3505 'linkedin' => 'linkedinpseudo',
3506 );
3507 $this->office_phone = '0999999999';
3508 $this->office_fax = '0999999998';
3509 $this->user_mobile = '0999999997';
3510 $this->personal_mobile = '0999999996';
3511 $this->admin = 0;
3512 $this->login = 'dolibspec';
3513 $this->pass = 'dolibSpec+@123';
3514 //$this->pass_indatabase='dolibspec'; Set after a fetch
3515 //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3516 $this->datec = $now;
3517 $this->datem = $now;
3518
3519 $this->datelastlogin = $now;
3520 $this->iplastlogin = '127.0.0.1';
3521 $this->datepreviouslogin = $now;
3522 $this->ippreviouslogin = '127.0.0.1';
3523 $this->statut = 1; // deprecated
3524 $this->status = 1;
3525
3526 $this->entity = 1;
3527
3528 return 1;
3529 }
3530
3537 public function info($id)
3538 {
3539 $sql = "SELECT u.rowid, u.login as ref, u.datec,";
3540 $sql .= " u.tms as date_modification, u.entity";
3541 $sql .= " FROM ".$this->db->prefix()."user as u";
3542 $sql .= " WHERE u.rowid = ".((int) $id);
3543
3544 $result = $this->db->query($sql);
3545 if ($result) {
3546 if ($this->db->num_rows($result)) {
3547 $obj = $this->db->fetch_object($result);
3548
3549 $this->id = $obj->rowid;
3550
3551 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3552 $this->date_creation = $this->db->jdate($obj->datec);
3553 $this->date_modification = $this->db->jdate($obj->date_modification);
3554 $this->entity = $obj->entity;
3555 }
3556
3557 $this->db->free($result);
3558 } else {
3559 dol_print_error($this->db);
3560 }
3561 }
3562
3563
3569 public function getNbOfEMailings()
3570 {
3571 $sql = "SELECT count(mc.email) as nb";
3572 $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3573 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3574 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
3575
3576 $resql = $this->db->query($sql);
3577 if ($resql) {
3578 $obj = $this->db->fetch_object($resql);
3579 $nb = $obj->nb;
3580
3581 $this->db->free($resql);
3582 return $nb;
3583 } else {
3584 $this->error = $this->db->error();
3585 return -1;
3586 }
3587 }
3588
3597 public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3598 {
3599 global $conf;
3600
3601 $sql = "SELECT count(rowid) as nb";
3602 $sql .= " FROM ".$this->db->prefix()."user";
3603 if ($option == 'superadmin') {
3604 $sql .= " WHERE entity = 0";
3605 } else {
3606 $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3607 if ($limitTo == 'active') {
3608 $sql .= " AND statut = 1";
3609 }
3610 }
3611 if ($admin >= 0) {
3612 $sql .= " AND admin = ".(int) $admin;
3613 }
3614
3615 $resql = $this->db->query($sql);
3616 if ($resql) {
3617 $obj = $this->db->fetch_object($resql);
3618 $nb = (int) $obj->nb;
3619
3620 $this->db->free($resql);
3621 return $nb;
3622 } else {
3623 $this->error = $this->db->lasterror();
3624 return -1;
3625 }
3626 }
3627
3628 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3635 public function update_ldap2dolibarr(&$ldapuser)
3636 {
3637 // phpcs:enable
3638 // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3639 global $user, $conf;
3640
3641 $socialnetworks = getArrayOfSocialNetworks();
3642
3643 $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3644 $this->firstname = $ldapuser->$tmpvar;
3645 $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3646 $this->lastname = $ldapuser->$tmpvar;
3647 $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3648 $this->login = $ldapuser->$tmpvar;
3649 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3650 $this->pass = $ldapuser->$tmpvar;
3651 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3652 $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3653
3654 $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3655 $this->office_phone = $ldapuser->$tmpvar;
3656 $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3657 $this->user_mobile = $ldapuser->$tmpvar;
3658 $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3659 $this->office_fax = $ldapuser->$tmpvar;
3660 $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3661 $this->email = $ldapuser->$tmpvar;
3662 foreach ($socialnetworks as $key => $value) {
3663 $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3664 $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3665 }
3666 $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3667 $this->ldap_sid = $ldapuser->$tmpvar;
3668
3669 $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3670 $this->job = $ldapuser->$tmpvar;
3671 $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3672 $this->note_public = $ldapuser->$tmpvar;
3673
3674 $result = $this->update($user);
3675
3676 dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3677
3678 return $result;
3679 }
3680
3681
3682 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3689 public function get_children()
3690 {
3691 // phpcs:enable
3692 $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3693 $sql .= " WHERE fk_user = ".((int) $this->id);
3694
3695 dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3696 $res = $this->db->query($sql);
3697 if ($res) {
3698 $users = array();
3699 while ($rec = $this->db->fetch_array($res)) {
3700 $user = new User($this->db);
3701 $user->fetch($rec['rowid']);
3702 $users[] = $user;
3703 }
3704 return $users;
3705 } else {
3706 dol_print_error($this->db);
3707 return -1;
3708 }
3709 }
3710
3711
3717 private function loadParentOf()
3718 {
3719 global $conf;
3720
3721 $this->parentof = array();
3722
3723 // Load array[child]=parent
3724 $sql = "SELECT fk_user as id_parent, rowid as id_son";
3725 $sql .= " FROM ".$this->db->prefix()."user";
3726 $sql .= " WHERE fk_user <> 0";
3727 $sql .= " AND entity IN (".getEntity('user').")";
3728
3729 dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3730 $resql = $this->db->query($sql);
3731 if ($resql) {
3732 while ($obj = $this->db->fetch_object($resql)) {
3733 $this->parentof[$obj->id_son] = $obj->id_parent;
3734 }
3735 return 1;
3736 } else {
3737 dol_print_error($this->db);
3738 return -1;
3739 }
3740 }
3741
3742 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3756 public function get_full_tree($deleteafterid = 0, $filter = '')
3757 {
3758 // phpcs:enable
3759 global $conf, $user;
3760 global $hookmanager;
3761
3762 // Actions hooked (by external module)
3763 $hookmanager->initHooks(array('userdao'));
3764
3765 $this->users = array();
3766
3767 // Init this->parentof that is array(id_son=>id_parent, ...)
3768 $this->loadParentOf();
3769
3770 // Init $this->users array
3771 $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
3772 $sql .= " FROM ".$this->db->prefix()."user as u";
3773 // Add fields from hooks
3774 $parameters = array();
3775 $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3776 if ($reshook > 0) {
3777 $sql .= $hookmanager->resPrint;
3778 } else {
3779 $sql .= " WHERE u.entity IN (".getEntity('user').")";
3780 }
3781 if ($filter) {
3782 $sql .= " AND ".$filter;
3783 }
3784
3785 dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3786 $resql = $this->db->query($sql);
3787 if ($resql) {
3788 $i = 0;
3789 while ($obj = $this->db->fetch_object($resql)) {
3790 $this->users[$obj->rowid]['rowid'] = $obj->rowid;
3791 $this->users[$obj->rowid]['id'] = $obj->rowid;
3792 $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
3793 $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
3794 $this->users[$obj->rowid]['firstname'] = $obj->firstname;
3795 $this->users[$obj->rowid]['lastname'] = $obj->lastname;
3796 $this->users[$obj->rowid]['login'] = $obj->login;
3797 $this->users[$obj->rowid]['statut'] = $obj->statut;
3798 $this->users[$obj->rowid]['entity'] = $obj->entity;
3799 $this->users[$obj->rowid]['email'] = $obj->email;
3800 $this->users[$obj->rowid]['gender'] = $obj->gender;
3801 $this->users[$obj->rowid]['admin'] = $obj->admin;
3802 $this->users[$obj->rowid]['photo'] = $obj->photo;
3803 // fields are filled with build_path_from_id_user
3804 $this->users[$obj->rowid]['fullpath'] = '';
3805 $this->users[$obj->rowid]['fullname'] = '';
3806 $this->users[$obj->rowid]['level'] = 0;
3807 $i++;
3808 }
3809 } else {
3810 dol_print_error($this->db);
3811 return -1;
3812 }
3813
3814 // We add the fullpath property to each element of the first level (no parent exists)
3815 dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3816 foreach ($this->users as $key => $val) {
3817 $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3818 if ($result < 0) {
3819 $this->error = 'ErrorLoopInHierarchy';
3820 return -1;
3821 }
3822 }
3823
3824 // Exclude leaf including $deleteafterid from tree
3825 if ($deleteafterid) {
3826 //print "Look to discard user ".$deleteafterid."\n";
3827 $keyfilter1 = '^'.$deleteafterid.'$';
3828 $keyfilter2 = '_'.$deleteafterid.'$';
3829 $keyfilter3 = '^'.$deleteafterid.'_';
3830 $keyfilter4 = '_'.$deleteafterid.'_';
3831 foreach (array_keys($this->users) as $key) {
3832 $fullpath = (string) $this->users[$key]['fullpath'];
3833 if (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
3834 || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath)) {
3835 unset($this->users[$key]);
3836 }
3837 }
3838 }
3839
3840 dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
3841 $this->users = dol_sort_array($this->users, 'fullname', 'asc', true, false, 1);
3842
3843 //var_dump($this->users);
3844
3845 return $this->users;
3846 }
3847
3856 public function getAllChildIds($addcurrentuser = 0)
3857 {
3858 $childids = array();
3859
3860 if (isset($this->cache_childids[$this->id])) {
3861 $childids = $this->cache_childids[$this->id];
3862 } else {
3863 // Init this->users
3864 $this->get_full_tree();
3865
3866 $idtoscan = $this->id;
3867
3868 dol_syslog("Build childid for id = ".$idtoscan);
3869 foreach ($this->users as $id => $val) {
3870 //var_dump($val['fullpath']);
3871 if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
3872 $childids[$val['id']] = $val['id'];
3873 }
3874 }
3875 }
3876 $this->cache_childids[$this->id] = $childids;
3877
3878 if ($addcurrentuser) {
3879 $childids[$this->id] = $this->id;
3880 }
3881
3882 return $childids;
3883 }
3884
3885 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3894 public function build_path_from_id_user($id_user, $protection = 0)
3895 {
3896 // phpcs:enable
3897 //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
3898
3899 if (!empty($this->users[$id_user]['fullpath'])) {
3900 // Already defined
3901 dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
3902 return 0;
3903 }
3904
3905 // Define fullpath and fullname
3906 $this->users[$id_user]['fullpath'] = '_'.$id_user;
3907 $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
3908 $i = 0;
3909 $cursor_user = $id_user;
3910
3911 $useridfound = array($id_user);
3912 while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) {
3913 if (in_array($this->parentof[$cursor_user], $useridfound)) {
3914 dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
3915 return -1; // Should not happen. Protection against looping hierarchy
3916 }
3917 $useridfound[] = $this->parentof[$cursor_user];
3918 $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
3919 $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
3920 $i++;
3921 $cursor_user = $this->parentof[$cursor_user];
3922 }
3923
3924 // We count number of _ to have level
3925 $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
3926
3927 return 1;
3928 }
3929
3938 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3939 {
3940 $tables = array(
3941 'user',
3942 );
3943
3944 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3945 }
3946
3947
3953 public function loadStateBoard()
3954 {
3955 global $conf;
3956
3957 $this->nb = array();
3958
3959 $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
3960 $sql .= " FROM ".$this->db->prefix()."user as u";
3961 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
3962 $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
3963 $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
3964 $sql .= " AND ug.fk_user = u.rowid";
3965 } else {
3966 $sql .= " WHERE u.entity IN (".getEntity('user').")";
3967 }
3968 $sql .= " AND u.statut > 0";
3969 //$sql.= " AND employee != 0";
3970
3971 $resql = $this->db->query($sql);
3972 if ($resql) {
3973 while ($obj = $this->db->fetch_object($resql)) {
3974 $this->nb["users"] = $obj->nb;
3975 }
3976 $this->db->free($resql);
3977 return 1;
3978 } else {
3979 dol_print_error($this->db);
3980 $this->error = $this->db->error();
3981 return -1;
3982 }
3983 }
3984
3996 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3997 {
3998 global $conf, $user, $langs;
3999
4000 $langs->load("user");
4001
4002 // Set the '$modele' to the name of the document template (model) to use
4003 if (!dol_strlen($modele)) {
4004 if (getDolGlobalString('USER_ADDON_PDF')) {
4005 $modele = getDolGlobalString('USER_ADDON_PDF');
4006 } else {
4007 $modele = 'bluesky';
4008 }
4009 }
4010
4011 $modelpath = "core/modules/user/doc/";
4012
4013 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4014 }
4015
4016 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4024 public function user_get_property($rowid, $mode)
4025 {
4026 // phpcs:enable
4027 $user_property = '';
4028
4029 if (empty($rowid)) {
4030 return '';
4031 }
4032
4033 $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
4034 $sql .= " FROM ".$this->db->prefix()."user";
4035 $sql .= " WHERE rowid = ".((int) $rowid);
4036
4037 $resql = $this->db->query($sql);
4038 if ($resql) {
4039 $nump = $this->db->num_rows($resql);
4040
4041 if ($nump) {
4042 $obj = $this->db->fetch_object($resql);
4043
4044 if ($mode == 'email') {
4045 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
4046 } elseif ($mode == 'mobile') {
4047 $user_property = $obj->user_mobile;
4048 } elseif ($mode == 'name') {
4049 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname);
4050 }
4051 }
4052 return $user_property;
4053 } else {
4054 dol_print_error($this->db);
4055 }
4056
4057 return '';
4058 }
4059
4067 public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
4068 {
4069 global $dolibarr_main_url_root;
4070 global $conf;
4071
4072 $encodedsecurekey = dol_hash($conf->file->instance_unique_id.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
4073 if (isModEnabled('multicompany')) {
4074 $entity_qr = '&entity='.((int) $conf->entity);
4075 } else {
4076 $entity_qr = '';
4077 }
4078 // Define $urlwithroot
4079 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
4080 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
4081 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
4082
4083 if ($typeofurl == 'internal') {
4084 $urlwithroot = DOL_URL_ROOT;
4085 }
4086
4087 return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
4088 }
4089
4103 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND', $entityfilter = false)
4104 {
4105 global $conf, $user;
4106
4107 $sql = "SELECT t.rowid";
4108 $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
4109
4110 if ($entityfilter) {
4111 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4112 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
4113 $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
4114 } else {
4115 $sql .= ",".$this->db->prefix()."usergroup_user as ug";
4116 $sql .= " WHERE ((ug.fk_user = t.rowid";
4117 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
4118 $sql .= " OR t.entity = 0)"; // Show always superadmin
4119 }
4120 } else {
4121 $sql .= " WHERE t.entity IN (".getEntity('user').")";
4122 }
4123 } else {
4124 $sql .= " WHERE 1 = 1";
4125 }
4126
4127 // Manage filter
4128 $errormessage = '';
4129 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
4130 if ($errormessage) {
4131 $this->errors[] = $errormessage;
4132 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
4133 return -1;
4134 }
4135
4136 $sql .= $this->db->order($sortfield, $sortorder);
4137 if ($limit) {
4138 $sql .= $this->db->plimit($limit + 1, $offset);
4139 }
4140
4141 dol_syslog(__METHOD__, LOG_DEBUG);
4142
4143 $resql = $this->db->query($sql);
4144 if ($resql) {
4145 $this->users = array();
4146 $num = $this->db->num_rows($resql);
4147 if ($num) {
4148 while ($obj = $this->db->fetch_object($resql)) {
4149 $line = new self($this->db);
4150 $result = $line->fetch($obj->rowid);
4151 if ($result > 0 && !empty($line->id)) {
4152 $this->users[$obj->rowid] = clone $line;
4153 }
4154 }
4155 $this->db->free($resql);
4156 }
4157 return $num;
4158 } else {
4159 $this->errors[] = $this->db->lasterror();
4160 return -1;
4161 }
4162 }
4163
4171 private $findUserIdByEmailCache;
4172
4183 public function findUserIdByEmail($email)
4184 {
4185 if (isset($this->findUserIdByEmailCache[$email])) {
4186 return $this->findUserIdByEmailCache[$email];
4187 }
4188
4189 $this->findUserIdByEmailCache[$email] = -1;
4190
4191 $sql = 'SELECT rowid';
4192 $sql .= ' FROM '.$this->db->prefix().'user';
4193 if (getDolGlobalString('AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR')) {
4194 $sql .= " WHERE email LIKE '%".$this->db->escape($this->db->escapeforlike($email))."%'";
4195 } else {
4196 $sql .= " WHERE email = '".$this->db->escape($email)."'";
4197 }
4198 $sql .= ' LIMIT 1';
4199
4200 $resql = $this->db->query($sql);
4201 if (!$resql) {
4202 return -1;
4203 }
4204
4205 $obj = $this->db->fetch_object($resql);
4206 if (!$obj) {
4207 return -1;
4208 }
4209
4210 $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4211
4212 return $this->findUserIdByEmailCache[$email];
4213 }
4214}
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition security.php:637
$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 to manage contact/addresses.
Class for MyObject.
Class to manage Dolibarr database access.
Class to manage warehouses.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage user groups.
Class to manage Dolibarr users.
fetch($id=0, $login='', $sid='', $loadpersonalconf=0, $entity=-1, $email='', $fk_socpeople=0, $use_email_oauth2=0)
Load a user from database with its id or ref (login).
SetInGroup($group, $entity, $notrigger=0)
Add user into a group.
LibStatut($status, $mode=0)
Return the label of a status of user (active, inactive)
loadRights($moduletag='', $forcereload=0)
Load permissions granted to a user->id into object user->rights.
get_children()
Return and array with all instantiated first level children users of current user.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
loadStateBoard()
Load metrics this->nb for dashboard.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
info($id)
Load info of user object.
create_from_contact($contact, $login='', $password='')
Create a user from a contact object.
setstatus($status)
Change status of a user.
get_full_tree($deleteafterid=0, $filter='')
Build the hierarchy/tree of users into an array.
_load_ldap_info()
Initialize the info array (array of LDAP values) that will be used to call LDAP functions.
delrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0)
Remove a right to the user.
update_last_login_date()
Update the user's last login date in the database.
__construct($db)
Constructor of the class.
RemoveFromGroup($group, $entity, $notrigger=0)
Remove a user from a group.
isNotIntoValidityDateRange()
Return a link with photo Use this->id,this->photo.
getNbOfUsers($limitTo, $option='', $admin=-1)
Return number of existing users.
set_default_rights()
Assign rights by default.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND', $entityfilter=false)
Load all objects into $this->users.
getOnlineVirtualCardUrl($mode='', $typeofurl='external')
Return string with full Url to virtual card.
update($user, $notrigger=0, $nosyncmember=0, $nosyncmemberpass=0, $nosynccontact=0)
Update a user into database (and also password if this->pass is defined)
getLoginUrl($withpictoimg=0, $option='', $notooltip=0, $morecss='')
Return clickable link of login (optionally with picto)
setCategories($categories)
Sets object to supplied categories.
loadParentOf()
Load this->parentof that is array(id_son=>id_parent, ...)
fetch_clicktodial()
Read clicktodial information for user.
build_path_from_id_user($id_user, $protection=0)
For user id_user and its children available in this->users, define property fullpath and fullname.
error()
Renvoie la derniere erreur fonctionnelle de manipulation de l'objet.
getAllChildIds($addcurrentuser=0)
Return list of all child user ids in hierarchy (all sublevels).
initAsSpecimen()
Initialise an instance with random values.
setPassword($user, $password='', $changelater=0, $notrigger=0, $nosyncmember=0, $passwordalreadycrypted=0, $flagdelsessionsbefore=1)
Change password of a user.
getNomUrl($withpictoimg=0, $option='', $infologin=0, $notooltip=0, $maxlen=24, $hidethirdpartylogo=0, $mode='', $morecss='', $save_lastsearch_value=-1)
Return a HTML link to the user card (with optionally the picto) Use this->id,this->lastname,...
clearrights()
Clear all permissions array of user.
update_clicktodial()
Update clicktodial info.
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 a user->id into object user->rights TODO Remove this method.
user_get_property($rowid, $mode)
Return property of user from its id.
send_password($user, $password='', $changelater=0)
Send a new password (or instructions to reset it) by email.
getKanbanView($option='', $arraydata=null)
Return clicable link of object (optionally with picto)
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
addrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0)
Add a right to the user.
create($user, $notrigger=0)
Create a user into database.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
findUserIdByEmail($email)
Find a user by the given e-mail and return it's user id when found.
getTooltipContentArray($params)
Return array of data to show into tooltips.
trait CommonPeople
Support class for thirdparties, contacts, members, users or resources.
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:655
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:641
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='')
Format phone numbers according to country.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
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_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
getArrayOfSocialNetworks()
Get array of social network dictionary.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return 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:420
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 symmetric 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 symmetric encryption.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall TAKEPOS_SHOW_SUBPRICE right right right takeposterminal SELECT e e e e e statut
Definition invoice.php:2010