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