dolibarr 23.0.4
user.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (c) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
4 * Copyright (c) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
7 * Copyright (C) 2005-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-2026 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, COALESCE(uef.tms, u.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 = $this->db->jdate($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 // A user that still has HRM data (competency assessments, job positions, skills) must not be deleted
1683 if (isModEnabled('hrm')) {
1684 global $langs;
1685
1686 $hrmtables = array(
1687 'hrm_evaluation' => array('label' => 'EvaluationCard', 'filter' => "fk_user = ".((int) $this->id)),
1688 'hrm_job_user' => array('label' => 'EmployeePosition', 'filter' => "fk_user = ".((int) $this->id)),
1689 'hrm_skillrank' => array('label' => 'Skill', 'filter' => "objecttype = 'user' AND fk_object = ".((int) $this->id)),
1690 );
1691 foreach ($hrmtables as $hrmtable => $hrminfo) {
1692 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$hrmtable." WHERE ".$hrminfo['filter'];
1693 $resql = $this->db->query($sql);
1694 if ($resql) {
1695 $obj = $this->db->fetch_object($resql);
1696 if ($obj && $obj->nb > 0) {
1697 $langs->loadLangs(array('errors', 'hrm'));
1698 $this->error = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $this->login, $langs->transnoentitiesnoconv($hrminfo['label']));
1699 $this->errors[] = $this->error;
1700 $this->db->rollback();
1701 return -1;
1702 }
1703 }
1704 }
1705 }
1706
1707 // Remove rights
1708 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = ".((int) $this->id);
1709
1710 if (!$error && !$this->db->query($sql)) {
1711 $error++;
1712 $this->error = $this->db->lasterror();
1713 }
1714
1715 // Remove group
1716 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user WHERE fk_user = ".((int) $this->id);
1717 if (!$error && !$this->db->query($sql)) {
1718 $error++;
1719 $this->error = $this->db->lasterror();
1720 }
1721
1722 // Remove params
1723 $sql = "DELETE FROM ".$this->db->prefix()."user_param WHERE fk_user = ".((int) $this->id);
1724 if (!$error && !$this->db->query($sql)) {
1725 $error++;
1726 $this->error = $this->db->lasterror();
1727 }
1728
1729 // Remove the private bookmarks of the user (the public ones have no owner and are kept)
1730 $sql = "DELETE FROM ".$this->db->prefix()."bookmark WHERE fk_user = ".((int) $this->id);
1731 if (!$error && !$this->db->query($sql)) {
1732 $error++;
1733 $this->error = $this->db->lasterror();
1734 }
1735
1736 // If contact, remove link
1737 if ($this->contact_id > 0) {
1738 $sql = "UPDATE ".$this->db->prefix()."socpeople SET fk_user_creat = null WHERE rowid = ".((int) $this->contact_id);
1739 if (!$error && !$this->db->query($sql)) {
1740 $error++;
1741 $this->error = $this->db->lasterror();
1742 }
1743 }
1744
1745 // Remove extrafields
1746 if (!$error) {
1747 $result = $this->deleteExtraFields();
1748 if ($result < 0) {
1749 $error++;
1750 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1751 }
1752 }
1753
1754 // Remove user
1755 if (!$error) {
1756 $sql = "DELETE FROM ".$this->db->prefix()."user WHERE rowid = ".((int) $this->id);
1757 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1758 if (!$this->db->query($sql)) {
1759 $error++;
1760 $this->error = $this->db->lasterror();
1761 }
1762 }
1763
1764 if (!$error) {
1765 // Call trigger
1766 $result = $this->call_trigger('USER_DELETE', $user);
1767 if ($result < 0) {
1768 $error++;
1769 $this->db->rollback();
1770 return -1;
1771 }
1772 // End call triggers
1773
1774 $this->db->commit();
1775 return 1;
1776 } else {
1777 $this->db->rollback();
1778 return -1;
1779 }
1780 }
1781
1789 public function create($user, $notrigger = 0)
1790 {
1791 global $conf, $langs;
1792 global $mysoc;
1793
1794 // Clean parameters
1795 $this->setUpperOrLowerCase();
1796
1797 $this->civility_code = trim((string) $this->civility_code);
1798 $this->login = trim((string) $this->login);
1799 $this->user_creation_id = (int) $user->id;
1800 if (!isset($this->entity)) {
1801 $this->entity = $conf->entity; // If not defined, we use default value
1802 }
1803 dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG);
1804
1805 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
1806
1807 // Check parameters
1808 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
1809 $langs->load("errors");
1810 $this->error = $langs->trans("ErrorBadEMail", $this->email);
1811 return -1;
1812 }
1813 if (empty($this->login)) {
1814 $langs->load("errors");
1815 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"));
1816 return -1;
1817 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
1818 $langs->load("errors");
1819 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
1820 return -1;
1821 }
1822
1823 $this->datec = dol_now();
1824
1825 $error = 0;
1826 $this->db->begin();
1827
1828 // Check if login already exists in same entity or into entity 0.
1829 if ($this->login) {
1830 $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)."'";
1831 $resqltochecklogin = $this->db->query($sqltochecklogin);
1832 if ($resqltochecklogin) {
1833 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1834 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1835 $langs->load("errors");
1836 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
1837 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1838 $this->db->rollback();
1839 return -6;
1840 }
1841 $this->db->free($resqltochecklogin);
1842 }
1843 }
1844 if (!empty($this->email)) {
1845 $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)."'";
1846 $resqltochecklogin = $this->db->query($sqltochecklogin);
1847 if ($resqltochecklogin) {
1848 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
1849 if ($objtochecklogin && $objtochecklogin->nb > 0) {
1850 $langs->load("errors");
1851 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
1852 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
1853 $this->db->rollback();
1854 return -6;
1855 }
1856 $this->db->free($resqltochecklogin);
1857 }
1858 }
1859
1860 // Insert into database
1861 $sql = "INSERT INTO ".$this->db->prefix()."user (datec, login, ldap_sid, fk_user_creat, entity)";
1862 $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).")";
1863 $result = $this->db->query($sql);
1864
1865 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1866 if ($result) {
1867 $this->id = $this->db->last_insert_id($this->db->prefix()."user");
1868
1869 // Set default rights
1870 if ($this->set_default_rights() < 0) {
1871 $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1872 $this->db->rollback();
1873 return -5;
1874 }
1875
1876 if (getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && getDolGlobalString('STOCK_USERSTOCK_AUTOCREATE')) {
1877 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1878 $langs->load("stocks");
1879
1880 $entrepot = new Entrepot($this->db);
1881 $entrepot->label = $langs->trans("PersonalStock", $this->getFullName($langs));
1882 $entrepot->libelle = $entrepot->label; // For backward compatibility
1883 $entrepot->description = $langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName($langs));
1884 $entrepot->statut = 1;
1885 $entrepot->country_id = $mysoc->country_id;
1886
1887 $warehouseid = $entrepot->create($user);
1888
1889 $this->fk_warehouse = $warehouseid;
1890 }
1891
1892 // Update minor fields
1893 $result = $this->update($user, 1, 1);
1894 if ($result < 0) {
1895 $this->db->rollback();
1896 return -4;
1897 }
1898
1899 if (!$notrigger) {
1900 // Call trigger
1901 $result = $this->call_trigger('USER_CREATE', $user);
1902 if ($result < 0) {
1903 $error++;
1904 }
1905 // End call triggers
1906 }
1907
1908 if (!$error) {
1909 $this->db->commit();
1910 return $this->id;
1911 } else {
1912 //$this->error=$interface->error;
1913 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1914 $this->db->rollback();
1915 return -3;
1916 }
1917 } else {
1918 $this->error = $this->db->lasterror();
1919 $this->db->rollback();
1920 return -2;
1921 }
1922 }
1923
1924
1925 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1934 public function create_from_contact($contact, $login = '', $password = '')
1935 {
1936 // phpcs:enable
1937 global $user;
1938
1939 $error = 0;
1940
1941 // Define parameters
1942 $this->admin = 0;
1943 $this->civility_code = $contact->civility_code;
1944 $this->lastname = $contact->lastname;
1945 $this->firstname = $contact->firstname;
1946 //$this->gender = $contact->gender; // contact has no gender
1947 $this->email = $contact->email;
1948 $this->socialnetworks = $contact->socialnetworks;
1949 $this->office_phone = $contact->phone_pro;
1950 $this->office_fax = $contact->fax;
1951 $this->user_mobile = $contact->phone_mobile;
1952 $this->address = $contact->address;
1953 $this->zip = $contact->zip;
1954 $this->town = $contact->town;
1955 $this->setUpperOrLowerCase();
1956 $this->state_id = $contact->state_id;
1957 $this->country_id = $contact->country_id;
1958 $this->employee = 0;
1959
1960 if (empty($login)) {
1961 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1962 $login = dol_buildlogin($contact->lastname, $contact->firstname);
1963 }
1964 $this->login = $login;
1965
1966 $this->db->begin();
1967
1968 // Create user and set $this->id. Trigger is disabled because executed later.
1969 $result = $this->create($user, 1);
1970 if ($result > 0) {
1971 $sql = "UPDATE ".$this->db->prefix()."user";
1972 $sql .= " SET fk_socpeople=".((int) $contact->id);
1973 $sql .= ", civility='".$this->db->escape($contact->civility_code)."'";
1974 if ($contact->socid > 0) {
1975 $sql .= ", fk_soc=".((int) $contact->socid);
1976 }
1977 $sql .= " WHERE rowid=".((int) $this->id);
1978
1979 $resql = $this->db->query($sql);
1980
1981 dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1982 if ($resql) {
1983 $this->context['createfromcontact'] = 'createfromcontact';
1984
1985 // Call trigger
1986 $result = $this->call_trigger('USER_CREATE', $user);
1987 if ($result < 0) {
1988 $error++;
1989 $this->db->rollback();
1990 return -1;
1991 }
1992 // End call triggers
1993
1994 $this->db->commit();
1995 return $this->id;
1996 } else {
1997 $this->error = $this->db->error();
1998
1999 $this->db->rollback();
2000 return -1;
2001 }
2002 } else {
2003 // $this->error deja positionne
2004 dol_syslog(get_class($this)."::create_from_contact - 0");
2005
2006 $this->db->rollback();
2007 return $result;
2008 }
2009 }
2010
2011 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2020 public function create_from_member($member, $login = '')
2021 {
2022 // phpcs:enable
2023 global $user;
2024
2025 // Set properties on new user
2026 $this->admin = 0;
2027 $this->civility_code = $member->civility_code;
2028 $this->lastname = $member->lastname;
2029 $this->firstname = $member->firstname;
2030 $this->gender = $member->gender;
2031 $this->email = $member->email;
2032 $this->fk_member = $member->id;
2033 $this->address = $member->address;
2034 $this->zip = $member->zip;
2035 $this->town = $member->town;
2036 $this->setUpperOrLowerCase();
2037 $this->state_id = $member->state_id;
2038 $this->country_id = $member->country_id;
2039 $this->socialnetworks = $member->socialnetworks;
2040
2041 $this->pass = $member->pass;
2042 $this->pass_crypted = $member->pass_indatabase_crypted;
2043
2044 if (empty($login)) {
2045 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2046 $login = dol_buildlogin($member->lastname, $member->firstname);
2047 }
2048 $this->login = $login;
2049
2050 $this->db->begin();
2051
2052 // Create and set $this->id
2053 $result = $this->create($user);
2054 if ($result > 0) {
2055 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
2056 $newpass = $this->setPassword($user, $this->pass);
2057 if (is_int($newpass) && $newpass < 0) {
2058 $result = -2;
2059 }
2060 } 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.
2061 $sql = "UPDATE ".$this->db->prefix()."user";
2062 $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'";
2063 $sql .= " WHERE rowid=".((int) $this->id);
2064
2065 $resql = $this->db->query($sql);
2066 if (!$resql) {
2067 $result = -1;
2068 }
2069 }
2070
2071 if ($result > 0 && $member->socid) { // If member is linked to a thirdparty
2072 $sql = "UPDATE ".$this->db->prefix()."user";
2073 $sql .= " SET fk_soc=".((int) $member->socid);
2074 $sql .= " WHERE rowid=".((int) $this->id);
2075
2076 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
2077 $resql = $this->db->query($sql);
2078 if ($resql) {
2079 $this->db->commit();
2080 return $this->id;
2081 } else {
2082 $this->error = $this->db->lasterror();
2083
2084 $this->db->rollback();
2085 return -1;
2086 }
2087 }
2088 }
2089
2090 if ($result > 0) {
2091 $this->db->commit();
2092 return $this->id;
2093 } else {
2094 // $this->error was already set
2095 $this->db->rollback();
2096 return -2;
2097 }
2098 }
2099
2100 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2106 public function set_default_rights()
2107 {
2108 // phpcs:enable
2109 global $conf;
2110
2111 $rd = array();
2112 $num = 0;
2113 $sql = "SELECT id FROM ".$this->db->prefix()."rights_def";
2114 $sql .= " WHERE bydefault = 1";
2115 $sql .= " AND entity = ".((int) $conf->entity);
2116
2117 $resql = $this->db->query($sql);
2118 if ($resql) {
2119 $num = $this->db->num_rows($resql);
2120 $i = 0;
2121 while ($i < $num) {
2122 $row = $this->db->fetch_row($resql);
2123 $rd[$i] = $row[0];
2124 $i++;
2125 }
2126 $this->db->free($resql);
2127 }
2128 $i = 0;
2129 while ($i < $num) {
2130 $sql = "DELETE FROM ".$this->db->prefix()."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
2131 $result = $this->db->query($sql);
2132
2133 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
2134 $result = $this->db->query($sql);
2135 if (!$result) {
2136 return -1;
2137 }
2138 $i++;
2139 }
2140
2141 return $i;
2142 }
2143
2154 public function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
2155 {
2156 global $langs;
2157
2158 if (empty($this->country_id) && !empty($this->country_code)) {
2159 $country_id = getCountry($this->country_code, '3');
2160 $this->country_id = is_int($country_id) ? $country_id : 0;
2161 }
2162
2163 $nbrowsaffected = 0;
2164 $error = 0;
2165
2166 dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
2167
2168 // Clean parameters
2169 $this->civility_code = trim((string) $this->civility_code);
2170 $this->lastname = trim((string) $this->lastname);
2171 $this->firstname = trim((string) $this->firstname);
2172 $this->ref_employee = trim((string) $this->ref_employee);
2173 $this->national_registration_number = trim((string) $this->national_registration_number);
2174 $this->employee = ($this->employee > 0 ? $this->employee : 0);
2175 $this->login = trim((string) $this->login);
2176 $this->gender = trim((string) $this->gender);
2177
2178 $this->pass = trim((string) $this->pass);
2179 $this->api_key = trim((string) $this->api_key);
2180 $this->datestartvalidity = empty($this->datestartvalidity) ? '' : $this->datestartvalidity;
2181 $this->dateendvalidity = empty($this->dateendvalidity) ? '' : $this->dateendvalidity;
2182
2183 $this->address = trim((string) $this->address);
2184 $this->zip = trim((string) $this->zip);
2185 $this->town = trim((string) $this->town);
2186
2187 $this->state_id = ($this->state_id > 0 ? $this->state_id : 0);
2188 $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
2189 $this->office_phone = trim((string) $this->office_phone);
2190 $this->office_fax = trim((string) $this->office_fax);
2191 $this->user_mobile = trim((string) $this->user_mobile);
2192 $this->personal_mobile = trim((string) $this->personal_mobile);
2193 $this->email = trim((string) $this->email);
2194 $this->personal_email = trim((string) $this->personal_email);
2195
2196 $this->job = trim((string) $this->job);
2197 $this->signature = trim((string) $this->signature);
2198 $this->note_public = trim((string) $this->note_public);
2199 $this->note_private = trim((string) $this->note_private);
2200 $this->openid = trim((string) $this->openid);
2201 $this->admin = ($this->admin > 0 ? $this->admin : 0);
2202 $this->user_modification_id = $user->id;
2203
2204 $this->accountancy_code_user_general = trim((string) $this->accountancy_code_user_general);
2205 $this->accountancy_code = trim((string) $this->accountancy_code);
2206 $this->color = trim(str_replace('#', '', (string) $this->color));
2207 $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
2208 $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
2209
2210 $this->birth = empty($this->birth) ? '' : $this->birth;
2211 $this->fk_warehouse = (int) $this->fk_warehouse;
2212 $this->fk_establishment = (int) $this->fk_establishment;
2213
2214 $this->setUpperOrLowerCase();
2215
2216 // Check parameters
2217 $badCharUnauthorizedIntoLoginName = getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
2218
2219 if (getDolGlobalString('USER_MAIL_REQUIRED') && !isValidEmail($this->email)) {
2220 $langs->load("errors");
2221 $this->error = $langs->trans("ErrorBadEMail", $this->email);
2222 return -1;
2223 }
2224 if (empty($this->login)) {
2225 $langs->load("errors");
2226 $this->error = $langs->trans("ErrorFieldRequired", 'Login');
2227 return -1;
2228 } elseif (preg_match('/['.preg_quote($badCharUnauthorizedIntoLoginName, '/').']/', $this->login)) {
2229 $langs->load("errors");
2230 $this->error = $langs->trans("ErrorBadCharIntoLoginName", $langs->transnoentitiesnoconv("Login"));
2231 return -1;
2232 }
2233
2234 $this->db->begin();
2235
2236 // Check if login already exists in same entity or into entity 0.
2237 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->oldcopy->login != $this->login) {
2238 $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)."'";
2239 $resqltochecklogin = $this->db->query($sqltochecklogin);
2240 if ($resqltochecklogin) {
2241 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2242 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2243 $langs->load("errors");
2244 $this->error = $langs->trans("ErrorLoginAlreadyExists", $this->login);
2245 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2246 $this->db->rollback();
2247 return -1;
2248 }
2249 }
2250 }
2251 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && !empty($this->email) && $this->oldcopy->email != $this->email) {
2252 $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)."'";
2253 $resqltochecklogin = $this->db->query($sqltochecklogin);
2254 if ($resqltochecklogin) {
2255 $objtochecklogin = $this->db->fetch_object($resqltochecklogin);
2256 if ($objtochecklogin && $objtochecklogin->nb > 0) {
2257 $langs->load("errors");
2258 $this->error = $langs->trans("ErrorEmailAlreadyExists", $this->email);
2259 dol_syslog(get_class($this)."::create ".$this->error, LOG_DEBUG);
2260 $this->db->rollback();
2261 return -1;
2262 }
2263 }
2264 }
2265
2266 // Update data
2267 $sql = "UPDATE ".$this->db->prefix()."user SET";
2268 $sql .= " civility = '".$this->db->escape($this->civility_code)."'";
2269 $sql .= ", lastname = '".$this->db->escape($this->lastname)."'";
2270 $sql .= ", firstname = '".$this->db->escape($this->firstname)."'";
2271 $sql .= ", ref_employee = '".$this->db->escape($this->ref_employee)."'";
2272 $sql .= ", national_registration_number = '".$this->db->escape($this->national_registration_number)."'";
2273 $sql .= ", employee = ".(int) $this->employee;
2274 $sql .= ", login = '".$this->db->escape($this->login)."'";
2275 $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null");
2276 $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' or 'other'
2277 $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null');
2278 if (!empty($user->admin)) {
2279 $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user
2280 }
2281 $sql .= ", address = '".$this->db->escape($this->address)."'";
2282 $sql .= ", zip = '".$this->db->escape($this->zip)."'";
2283 $sql .= ", town = '".$this->db->escape($this->town)."'";
2284 $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".((int) $this->state_id)."'" : "null");
2285 $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".((int) $this->country_id)."'" : "null");
2286 $sql .= ", office_phone = '".$this->db->escape($this->office_phone)."'";
2287 $sql .= ", office_fax = '".$this->db->escape($this->office_fax)."'";
2288 $sql .= ", user_mobile = '".$this->db->escape($this->user_mobile)."'";
2289 $sql .= ", personal_mobile = '".$this->db->escape($this->personal_mobile)."'";
2290 $sql .= ", email = '".$this->db->escape($this->email)."'";
2291 $sql .= ", personal_email = '".$this->db->escape($this->personal_email)."'";
2292 $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
2293 $sql .= ", job = '".$this->db->escape($this->job)."'";
2294 $sql .= ", signature = '".$this->db->escape($this->signature)."'";
2295 $sql .= ", accountancy_code_user_general = '".$this->db->escape($this->accountancy_code_user_general)."'";
2296 $sql .= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'";
2297 $sql .= ", color = '".$this->db->escape($this->color)."'";
2298 $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".$this->db->idate($this->dateemployment)."'" : 'null');
2299 $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".$this->db->idate($this->dateemploymentend)."'" : 'null');
2300 $sql .= ", datestartvalidity=".(strval($this->datestartvalidity) != '' ? "'".$this->db->idate($this->datestartvalidity)."'" : 'null');
2301 $sql .= ", dateendvalidity=".(strval($this->dateendvalidity) != '' ? "'".$this->db->idate($this->dateendvalidity)."'" : 'null');
2302 $sql .= ", note_private = '".$this->db->escape($this->note_private)."'";
2303 $sql .= ", note_public = '".$this->db->escape($this->note_public)."'";
2304 $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
2305 $sql .= ", openid = ".($this->openid ? "'".$this->db->escape($this->openid)."'" : "null");
2306 $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".((int) $this->fk_user)."'" : "null");
2307 $sql .= ", fk_user_modif = ".($this->user_modification_id > 0 ? "'".((int) $this->user_modification_id)."'" : "null");
2308 $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".((int) $this->fk_user_expense_validator)."'" : "null");
2309 $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".((int) $this->fk_user_holiday_validator)."'" : "null");
2310 if (isset($this->thm) || $this->thm != '') {
2311 $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null");
2312 }
2313 if (isset($this->tjm) || $this->tjm != '') {
2314 $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null");
2315 }
2316 if (isset($this->salary) || $this->salary != '') {
2317 $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null");
2318 }
2319 if (isset($this->salaryextra) || $this->salaryextra != '') {
2320 $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null");
2321 }
2322 $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null");
2323 if (isModEnabled('multicompany') && !empty($user->admin) && empty($user->entity) && $user->id != $this->id) {
2324 // entity flag can be set/unset only by another superadmin user, and only when multicompany is enabled.
2325 // Without multicompany, entity must never be written here: fetch() forces an admin's entity to 0 in memory
2326 // (an admin is a global admin without multicompany), and persisting that would wrongly turn the user into
2327 // a "whole database" (entity 0) admin.
2328 $sql .= ", entity = ".((int) $this->entity);
2329 }
2330 $sql .= ", default_range = ".($this->default_range > 0 ? (int) $this->default_range : 'null');
2331 $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? (int) $this->default_c_exp_tax_cat : 'null');
2332 $sql .= ", fk_warehouse = ".($this->fk_warehouse > 0 ? (int) $this->fk_warehouse : "null");
2333 $sql .= ", fk_establishment = ".($this->fk_establishment > 0 ? (int) $this->fk_establishment : "null");
2334 $sql .= ", lang = ".($this->lang ? "'".$this->db->escape($this->lang)."'" : "null");
2335 $sql .= " WHERE rowid = ".((int) $this->id);
2336
2337 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2338 $resql = $this->db->query($sql);
2339 if ($resql) {
2340 $nbrowsaffected += $this->db->affected_rows($resql);
2341
2342 // Update password
2343 if (!empty($this->pass)) {
2344 if ($this->pass != $this->pass_indatabase && !dol_verifyHash($this->pass, $this->pass_indatabase_crypted)) {
2345 // If a new value for password is set and different than the one encrypted into database
2346 $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass, 0, 1);
2347 if (is_int($result) && $result < 0) {
2348 return -5;
2349 }
2350 }
2351 }
2352
2353 // If user is linked to a member, remove old link to this member
2354 if ($this->fk_member > 0) {
2355 dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
2356 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member = NULL where fk_member = ".((int) $this->fk_member);
2357 $resql = $this->db->query($sql);
2358 if (!$resql) {
2359 $this->error = $this->db->error();
2360 $this->db->rollback();
2361 return -5;
2362 }
2363 }
2364 // Set link to user
2365 dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
2366 $sql = "UPDATE ".$this->db->prefix()."user SET fk_member =".($this->fk_member > 0 ? ((int) $this->fk_member) : 'null')." where rowid = ".((int) $this->id);
2367 $resql = $this->db->query($sql);
2368 if (!$resql) {
2369 $this->error = $this->db->error();
2370 $this->db->rollback();
2371 return -5;
2372 }
2373
2374 if ($nbrowsaffected) { // If something has changed in data
2375 if ($this->fk_member > 0 && !$nosyncmember) {
2376 dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
2377
2378 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2379
2380 // This user is linked with a member, so we also update member information
2381 // if this is an update.
2382 $adh = new Adherent($this->db);
2383 $result = $adh->fetch($this->fk_member);
2384
2385 if ($result > 0) {
2386 $adh->civility_code = $this->civility_code;
2387 $adh->firstname = $this->firstname;
2388 $adh->lastname = $this->lastname;
2389 $adh->login = $this->login;
2390 $adh->gender = $this->gender;
2391 $adh->birth = $this->birth;
2392
2393 $adh->pass = $this->pass;
2394
2395 $adh->address = $this->address;
2396 $adh->town = $this->town;
2397 $adh->zip = $this->zip;
2398 $adh->state_id = $this->state_id;
2399 $adh->country_id = $this->country_id;
2400
2401 $adh->email = $this->email;
2402
2403 $adh->socialnetworks = $this->socialnetworks;
2404
2405 $adh->phone = $this->office_phone;
2406 $adh->phone_mobile = $this->user_mobile;
2407
2408 $adh->default_lang = $this->lang;
2409
2410 $adh->user_id = $this->id;
2411 $adh->user_login = $this->login;
2412
2413 $result = $adh->update($user, 0, 1, 0);
2414 if ($result < 0) {
2415 $this->error = $adh->error;
2416 $this->errors = $adh->errors;
2417 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2418 $error++;
2419 }
2420 } elseif ($result < 0) {
2421 $this->error = $adh->error;
2422 $this->errors = $adh->errors;
2423 $error++;
2424 }
2425 }
2426
2427 if ($this->contact_id > 0 && !$nosynccontact) {
2428 dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
2429
2430 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2431
2432 // This user is linked with a contact, so we also update contact information if this is an update.
2433 $tmpobj = new Contact($this->db);
2434 $result = $tmpobj->fetch($this->contact_id);
2435
2436 if ($result >= 0) {
2437 $tmpobj->civility_code = $this->civility_code;
2438 $tmpobj->firstname = $this->firstname;
2439 $tmpobj->lastname = $this->lastname;
2440 $tmpobj->login = $this->login;
2441 $tmpobj->gender = $this->gender;
2442 $tmpobj->birth = $this->birth;
2443
2444 //$tmpobj->pass=$this->pass;
2445
2446 $tmpobj->email = $this->email;
2447
2448 $tmpobj->socialnetworks = $this->socialnetworks;
2449
2450 $tmpobj->phone_pro = $this->office_phone;
2451 $tmpobj->phone_mobile = $this->user_mobile;
2452 $tmpobj->fax = $this->office_fax;
2453
2454 $tmpobj->default_lang = $this->lang;
2455
2456 $tmpobj->address = $this->address;
2457 $tmpobj->town = $this->town;
2458 $tmpobj->zip = $this->zip;
2459 $tmpobj->state_id = $this->state_id;
2460 $tmpobj->country_id = $this->country_id;
2461
2462 $tmpobj->user_id = $this->id;
2463 $tmpobj->user_login = $this->login;
2464
2465 $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1);
2466 if ($result < 0) {
2467 $this->error = $tmpobj->error;
2468 $this->errors = $tmpobj->errors;
2469 dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
2470 $error++;
2471 }
2472 } else {
2473 $this->error = $tmpobj->error;
2474 $this->errors = $tmpobj->errors;
2475 $error++;
2476 }
2477 }
2478 }
2479
2480 $action = 'update';
2481
2482 // Actions on extra fields
2483 if (!$error) {
2484 $result = $this->insertExtraFields();
2485 if ($result < 0) {
2486 $error++;
2487 }
2488 }
2489
2490 if (!$error && !$notrigger) {
2491 // Call trigger
2492 $result = $this->call_trigger('USER_MODIFY', $user);
2493 if ($result < 0) {
2494 $error++;
2495 }
2496 // End call triggers
2497 }
2498
2499 if (!$error) {
2500 $this->db->commit();
2501 return $nbrowsaffected;
2502 } else {
2503 dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
2504 $this->db->rollback();
2505 return -1;
2506 }
2507 } else {
2508 $this->error = $this->db->lasterror();
2509 $this->db->rollback();
2510 return -2;
2511 }
2512 }
2513
2514 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2521 public function update_last_login_date()
2522 {
2523 // phpcs:enable
2524 $now = dol_now();
2525
2526 $userremoteip = getUserRemoteIP();
2527
2528 $sql = "UPDATE ".$this->db->prefix()."user SET";
2529 $sql .= " datepreviouslogin = datelastlogin,";
2530 $sql .= " ippreviouslogin = iplastlogin,";
2531 $sql .= " datelastlogin = '".$this->db->idate($now)."',";
2532 $sql .= " iplastlogin = '".$this->db->escape($userremoteip)."',";
2533 $sql .= " tms = tms"; // The last update date must change because the last login date is updated
2534 $sql .= " WHERE rowid = ".((int) $this->id);
2535
2536 dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
2537 $resql = $this->db->query($sql);
2538 if ($resql) {
2539 $this->datepreviouslogin = $this->datelastlogin;
2540 $this->datelastlogin = $now;
2541 $this->ippreviouslogin = $this->iplastlogin;
2542 $this->iplastlogin = $userremoteip;
2543 return 1;
2544 } else {
2545 $this->error = $this->db->lasterror().' sql='.$sql;
2546 return -1;
2547 }
2548 }
2549
2550
2563 public function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0, $passwordalreadycrypted = 0, $flagdelsessionsbefore = 1)
2564 {
2565 global $conf, $langs;
2566 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2567
2568 $error = 0;
2569
2570 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
2571
2572 // If new password not provided, we generate one
2573 if (!$password) {
2574 $password = getRandomPassword(false);
2575 }
2576
2577 $password_crypted = null;
2578 // Check and encrypt the password
2579 if (empty($passwordalreadycrypted)) {
2580 if (getDolGlobalString('USER_PASSWORD_GENERATED')) {
2581 // Add a check on rules for password syntax using the setup of the password generator
2582 $modGeneratePassClass = 'modGeneratePass'.ucfirst(getDolGlobalString('USER_PASSWORD_GENERATED'));
2583
2584 include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/'.$modGeneratePassClass.'.class.php';
2585 if (class_exists($modGeneratePassClass)) {
2586 $modGeneratePass = new $modGeneratePassClass($this->db, $conf, $langs, $user);
2587 '@phan-var-force ModeleGenPassword $modGeneratePass';
2588
2589 // To check an input user password, we disable the cleaning on ambiguous characters (this is used only for auto-generated password)
2590 $modGeneratePass->WithoutAmbi = 0;
2591
2592 // Call to validatePassword($password) to check pass match rules
2593 $testpassword = $modGeneratePass->validatePassword($password);
2594 if (!$testpassword) {
2595 $this->error = $modGeneratePass->error;
2596 return -1;
2597 }
2598 }
2599 }
2600
2601
2602 // Now, we encrypt the new password
2603 $password_crypted = dol_hash($password);
2604 }
2605
2606 // Update password
2607 if (!$changelater) {
2608 if (!is_object($this->oldcopy)) {
2609 $this->oldcopy = clone $this;
2610 }
2611
2612 $now = dol_now();
2613
2614 $this->db->begin();
2615
2616 $sql = "UPDATE ".$this->db->prefix()."user";
2617 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',";
2618 $sql .= " datelastpassvalidation = '".$this->db->idate(dol_now())."',";
2619 $sql .= " pass_temp = null";
2620 if (!empty($flagdelsessionsbefore)) {
2621 $sql .= ", flagdelsessionsbefore = '".$this->db->idate($now - 5, 'gmt')."'";
2622 }
2623 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
2624 $sql .= ", pass = null";
2625 } else {
2626 $sql .= ", pass = '".$this->db->escape($password)."'";
2627 }
2628 $sql .= " WHERE rowid = ".((int) $this->id);
2629
2630 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
2631
2632 $result = $this->db->query($sql);
2633 if ($result) {
2634 if ($this->db->affected_rows($result)) {
2635 $this->pass = $password;
2636 $this->pass_indatabase = $password;
2637 $this->pass_indatabase_crypted = (string) $password_crypted;
2638
2639 if ($this->fk_member && !$nosyncmember) {
2640 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2641
2642 // This user is linked with a member, so we also update members information
2643 // if this is an update.
2644 $adh = new Adherent($this->db);
2645 $result = $adh->fetch($this->fk_member);
2646
2647 if ($result >= 0) {
2648 $result = $adh->setPassword($user, $this->pass, (!getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 0 : 1), 1); // The encryption is not managed in the 'adherent' module
2649 if (is_int($result) && $result < 0) {
2650 $this->error = $adh->error;
2651 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
2652 $error++;
2653 }
2654 } else {
2655 $this->error = $adh->error;
2656 $error++;
2657 }
2658 }
2659
2660 dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
2661
2662 // Call trigger for the "security events" log
2663 $user->context['audit'] = 'login='.$user->login;
2664 if (!empty($flagdelsessionsbefore)) {
2665 $user->context['audit'] .= " - flagdelsessionsbefore set to '".$this->db->idate($now - 5, 'gmt')."'";
2666 }
2667
2668 if (!$error && !$notrigger) {
2669 // Call trigger
2670 $result = $this->call_trigger('USER_NEW_PASSWORD', $user);
2671 if ($result < 0) {
2672 $error++;
2673 $this->db->rollback();
2674 return -1;
2675 }
2676 // End call triggers
2677 }
2678
2679 $this->db->commit();
2680 return $this->pass;
2681 } else {
2682 $this->db->rollback();
2683 return 0;
2684 }
2685 } else {
2686 $this->db->rollback();
2687 dol_print_error($this->db);
2688 return -1;
2689 }
2690 } else {
2691 // We store password in password temporary field.
2692 // After receiving confirmation link, we will erase and store it in pass_crypted
2693 $sql = "UPDATE ".$this->db->prefix()."user";
2694 $sql .= " SET pass_temp = '".$this->db->escape($password)."'";
2695 $sql .= " WHERE rowid = ".((int) $this->id);
2696
2697 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
2698 $result = $this->db->query($sql);
2699 if ($result) {
2700 return $password;
2701 } else {
2702 dol_print_error($this->db);
2703 return -3;
2704 }
2705 }
2706 }
2707
2708 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2717 public function send_password($user, $password = '', $changelater = 0)
2718 {
2719 // phpcs:enable
2720 global $conf, $langs;
2722
2723 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2724
2725 $msgishtml = 0;
2726
2727 // Define $msg
2728 $mesg = '';
2729
2730 $outputlangs = new Translate("", $conf);
2731
2732 if (getDolGlobalString('MAIN_LANG_DEFAULT')) {
2733 $outputlangs->setDefaultLang(getDolGlobalString('MAIN_LANG_DEFAULT'));
2734 } else { // If user has not defined its own language, we used current language
2735 $outputlangs = $langs;
2736 }
2737
2738 // Load translation files required by the page
2739 $outputlangs->loadLangs(array("main", "errors", "users", "other"));
2740
2741 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', constant('DOL_APPLICATION_TITLE'));
2742
2743 $subject = '['.$appli.'] '.$outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
2744
2745 // Define $urlwithroot
2746 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2747 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2748
2749 if (!$changelater) {
2750 $url = $urlwithroot.'/';
2751 if (getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD')) {
2752 $url = getDolGlobalString('URL_REDIRECTION_AFTER_CHANGEPASSWORD');
2753 }
2754
2755 dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
2756
2757 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
2758 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
2759 $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
2760 $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
2761 $mesg .= "\n";
2762
2763 $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
2764 $mesg .= "--\n";
2765 $mesg .= $user->getFullName($outputlangs); // Username that send the email (not the user for who we want to reset password)
2766 } else {
2767 //print $password.'-'.$this->id.'-'.$conf->file->instance_unique_id;
2768 $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword';
2769 $url .= '&username='.urlencode($this->login)."&passworduidhash=".urlencode(dol_hash($password.'-'.$this->id.'-'.$conf->file->instance_unique_id));
2770 if (isModEnabled('multicompany')) {
2771 $url .= '&entity='.(!empty($this->entity) ? $this->entity : 1);
2772 }
2773
2774 dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
2775
2776 $msgishtml = 1;
2777
2778 $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."<br>\n";
2779 $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :<br>\n<br>\n";
2780 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Login")."</strong> = ".$this->login."<br>\n";
2781 $mesg .= '<strong>'.$outputlangs->transnoentitiesnoconv("Password")."</strong> = ".$password."<br>\n<br>\n";
2782 $mesg .= "<br>\n";
2783 $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :<br>\n";
2784 $mesg .= '<a href="'.$url.'" rel="noopener">'.$outputlangs->transnoentitiesnoconv("ConfirmPasswordChange").'</a>'."<br>\n<br>\n";
2785 $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."<br>\n<br>\n";
2786 }
2787
2788 $trackid = 'use'.$this->id;
2789 $sendcontext = 'passwordreset';
2790
2791 $mailfile = new CMailFile(
2792 $subject,
2793 $this->email,
2794 getDolGlobalString("MAIN_MAIL_EMAIL_FROM_PASSWORDRESET", getDolGlobalString("MAIN_MAIL_EMAIL_FROM")),
2795 $mesg,
2796 array(),
2797 array(),
2798 array(),
2799 '',
2800 '',
2801 0,
2802 $msgishtml,
2803 '',
2804 '',
2805 $trackid,
2806 '',
2807 $sendcontext
2808 );
2809
2810 if ($mailfile->sendfile()) {
2811 return 1;
2812 } else {
2813 $langs->trans("errors");
2814 $this->error = $langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
2815 return -1;
2816 }
2817 }
2818
2824 public function error()
2825 {
2826 return $this->error;
2827 }
2828
2829
2830 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2836 public function fetch_clicktodial()
2837 {
2838 // phpcs:enable
2839 $sql = "SELECT url, login, pass, poste ";
2840 $sql .= " FROM ".$this->db->prefix()."user_clicktodial as u";
2841 $sql .= " WHERE u.fk_user = ".((int) $this->id);
2842
2843 $resql = $this->db->query($sql);
2844 if ($resql) {
2845 if ($this->db->num_rows($resql)) {
2846 $obj = $this->db->fetch_object($resql);
2847
2848 $this->clicktodial_url = $obj->url;
2849 $this->clicktodial_login = $obj->login;
2850 $this->clicktodial_password = $obj->pass;
2851 $this->clicktodial_poste = $obj->poste;
2852 }
2853
2854 $this->clicktodial_loaded = 1; // Data loaded (found or not)
2855
2856 $this->db->free($resql);
2857 return 1;
2858 } else {
2859 $this->error = $this->db->error();
2860 return -1;
2861 }
2862 }
2863
2864 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2870 public function update_clicktodial()
2871 {
2872 // phpcs:enable
2873 $this->db->begin();
2874
2875 $sql = "DELETE FROM ".$this->db->prefix()."user_clicktodial";
2876 $sql .= " WHERE fk_user = ".((int) $this->id);
2877
2878 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2879
2880 $result = $this->db->query($sql);
2881
2882 $sql = "INSERT INTO ".$this->db->prefix()."user_clicktodial";
2883 $sql .= " (fk_user,url,login,pass,poste)";
2884 $sql .= " VALUES (".$this->id;
2885 $sql .= ", '".$this->db->escape($this->clicktodial_url)."'";
2886 $sql .= ", '".$this->db->escape($this->clicktodial_login)."'";
2887 $sql .= ", '".$this->db->escape($this->clicktodial_password)."'";
2888 $sql .= ", '".$this->db->escape($this->clicktodial_poste)."')";
2889
2890 dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
2891
2892 $result = $this->db->query($sql);
2893 if ($result) {
2894 $this->db->commit();
2895 return 1;
2896 } else {
2897 $this->db->rollback();
2898 $this->error = $this->db->lasterror();
2899 return -1;
2900 }
2901 }
2902
2903
2904 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2913 public function SetInGroup($group, $entity, $notrigger = 0)
2914 {
2915 // phpcs:enable
2916 global $langs, $user;
2917
2918 $error = 0;
2919
2920 $this->db->begin();
2921
2922 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2923 $sql .= " WHERE fk_user = ".((int) $this->id);
2924 $sql .= " AND fk_usergroup = ".((int) $group);
2925 $sql .= " AND entity = ".((int) $entity);
2926
2927 $result = $this->db->query($sql);
2928
2929 $sql = "INSERT INTO ".$this->db->prefix()."usergroup_user (entity, fk_user, fk_usergroup)";
2930 $sql .= " VALUES (".((int) $entity).",".((int) $this->id).",".((int) $group).")";
2931
2932 $result = $this->db->query($sql);
2933 if ($result) {
2934 if (!$error && !$notrigger) {
2935 $this->context = array('audit' => $langs->trans("UserSetInGroup"), 'newgroupid' => $group);
2936
2937 // Call trigger
2938 $result = $this->call_trigger('USER_MODIFY', $user);
2939 if ($result < 0) {
2940 $error++;
2941 }
2942 // End call triggers
2943 }
2944
2945 if (!$error) {
2946 $this->db->commit();
2947 return 1;
2948 } else {
2949 dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
2950 $this->db->rollback();
2951 return -2;
2952 }
2953 } else {
2954 $this->error = $this->db->lasterror();
2955 $this->db->rollback();
2956 return -1;
2957 }
2958 }
2959
2960 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2969 public function RemoveFromGroup($group, $entity, $notrigger = 0)
2970 {
2971 // phpcs:enable
2972 global $langs, $user;
2973
2974 $error = 0;
2975
2976 $this->db->begin();
2977
2978 $sql = "DELETE FROM ".$this->db->prefix()."usergroup_user";
2979 $sql .= " WHERE fk_user = ".((int) $this->id);
2980 $sql .= " AND fk_usergroup = ".((int) $group);
2981 if (empty($entity)) {
2982 $sql .= " AND entity IN (0, 1)"; // group may be in entity 0 (so $entity=0) and link with user into entity 1.
2983 } else {
2984 $sql .= " AND entity = ".((int) $entity);
2985 }
2986
2987 $result = $this->db->query($sql);
2988 if ($result) {
2989 if (!$error && !$notrigger) {
2990 $this->context = array('audit' => $langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
2991
2992 // Call trigger
2993 $result = $this->call_trigger('USER_MODIFY', $user);
2994 if ($result < 0) {
2995 $error++;
2996 }
2997 // End call triggers
2998 }
2999
3000 if (!$error) {
3001 $this->db->commit();
3002 return 1;
3003 } else {
3004 dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
3005 $this->db->rollback();
3006 return -2;
3007 }
3008 } else {
3009 $this->error = $this->db->lasterror();
3010 $this->db->rollback();
3011 return -1;
3012 }
3013 }
3014
3015
3023 {
3024 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3025
3026 $now = dol_now();
3027
3028 //dol_syslog("isNotIntoValidityDateRange ".$this->datestartvalidity);
3029
3030 // Check date start validity
3031 if ($this->datestartvalidity && $this->datestartvalidity > dol_get_last_hour($now)) {
3032 return 1;
3033 }
3034 // Check date end validity
3035 if ($this->dateendvalidity && $this->dateendvalidity < dol_get_first_hour($now)) {
3036 return 1;
3037 }
3038
3039 return 0;
3040 }
3041
3042
3054 public function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
3055 {
3056 $result = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3057 $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
3058 $result .= '</a>';
3059
3060 return $result;
3061 }
3062
3069 public function getTooltipContentArray($params)
3070 {
3071 global $conf, $langs, $menumanager;
3072 global $dolibarr_main_demo;
3073
3074 $infologin = $params['infologin'] ?? 0;
3075 $option = $params['option'] ?? '';
3076
3077 $data = [];
3078 if (!empty($this->photo)) {
3079 $photo = '<div class="photointooltip floatright">';
3080 $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
3081 $photo .= '</div>';
3082 $data['photo'] = $photo;
3083 //$label .= '<div style="clear: both;"></div>';
3084 }
3085
3086 // Info Login
3087 $data['opendiv'] = '<div class="centpercent divtooltip">';
3088 $data['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("User").'</u> '.$this->getLibStatut(4);
3089 $data['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_string_nohtmltag($this->getFullName($langs));
3090 if (!empty($this->login)) {
3091 $data['login'] = '<br><b>'.$langs->trans('Login').':</b> '.dol_string_nohtmltag($this->login);
3092 }
3093 if (!empty($this->job)) {
3094 $data['job'] = '<br><b>'.$langs->trans("Job").':</b> '.dol_string_nohtmltag($this->job);
3095 }
3096 $data['email'] = '<br><b>'.$langs->trans("Email").':</b> '.dol_string_nohtmltag($this->email);
3097 if (!empty($this->office_phone) || !empty($this->office_fax) || !empty($this->fax)) {
3098 $phonelist = array();
3099 if ($this->office_phone) {
3100 $phonelist[] = dol_print_phone($this->office_phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3101 }
3102 if ($this->office_fax) {
3103 $phonelist[] = dol_print_phone($this->office_fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3104 }
3105 if ($this->user_mobile) {
3106 $phonelist[] = dol_print_phone($this->user_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3107 }
3108 $data['phones'] = '<br><b>'.$langs->trans('Phone').':</b> '.implode('&nbsp;', $phonelist);
3109 }
3110 if (!empty($this->admin)) {
3111 $data['administrator'] = '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($this->admin);
3112 }
3113 if (!empty($this->accountancy_code) || $option == 'accountancy') {
3114 $langs->load("companies");
3115 $data['accountancycode'] = '<br><b>'.$langs->trans("AccountancyCode").'</b>: '.$this->accountancy_code;
3116 }
3117 $company = '';
3118 if (!empty($this->socid)) { // Add thirdparty for external users
3119 $thirdpartystatic = new Societe($this->db);
3120 $thirdpartystatic->fetch($this->socid);
3121 $companyimg = '';
3122 if (empty($params['hidethirdpartylogo'])) {
3123 $companyimg = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3124 }
3125 $company = ' ('.$langs->trans("Company").': '.($companyimg ? $companyimg : img_picto('', 'company')).' '.dol_string_nohtmltag($thirdpartystatic->name).')';
3126 }
3127 $type = ($this->socid ? $langs->trans("ExternalUser").$company : $langs->trans("InternalUser"));
3128 $data['type'] = '<br><b>'.$langs->trans("Type").':</b> '.$type;
3129 $data['closediv'] = '</div>';
3130
3131 if ($infologin > 0) {
3132 $data['newlinelogin'] = '<br>';
3133 $data['session'] = '<br><u>'.$langs->trans("Session").'</u>';
3134 $data['ip'] = '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_string_nohtmltag(getUserRemoteIP());
3135 if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
3136 $data['multicompany'] = '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (User entity '.$this->entity.')';
3137 }
3138 $data['authentication'] = '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.dol_string_nohtmltag($_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'));
3139 $data['connectedsince'] = '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
3140 $data['previousconnexion'] = '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
3141 $data['currenttheme'] = '<br><b>'.$langs->trans("CurrentTheme").':</b> '.dol_string_nohtmltag($conf->theme);
3142 // @phan-suppress-next-line PhanRedefinedClassReference
3143 $data['currentmenumanager'] = '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.dol_string_nohtmltag($menumanager->name);
3144 $s = picto_from_langcode($langs->getDefaultLang());
3145 $data['currentuserlang'] = '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.dol_string_nohtmltag(($s ? $s.' ' : '').$langs->getDefaultLang());
3146 $data['browser'] = '<br><b>'.$langs->trans("Browser").':</b> '.dol_string_nohtmltag($conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')');
3147 $data['layout'] = '<br><b>'.$langs->trans("Layout").':</b> '.dol_string_nohtmltag($conf->browser->layout);
3148 $data['screen'] = '<br><b>'.$langs->trans("Screen").':</b> '.dol_string_nohtmltag($_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']);
3149 if ($conf->browser->layout == 'phone') {
3150 $data['phone'] = '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
3151 }
3152 if (!empty($_SESSION["disablemodules"])) {
3153 $data['disabledmodules'] = '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.dol_string_nohtmltag(implode(', ', explode(',', $_SESSION["disablemodules"])));
3154 }
3155 }
3156
3157 return $data;
3158 }
3159
3175 public function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
3176 {
3177 global $langs, $hookmanager, $user;
3178
3179 if (!$user->hasRight('user', 'user', 'read') && $user->id != $this->id) {
3180 $option = 'nolink';
3181 }
3182
3183 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
3184 $withpictoimg = 0;
3185 }
3186
3187 $result = '';
3188 $params = [
3189 'id' => $this->id,
3190 'objecttype' => $this->element,
3191 'infologin' => $infologin,
3192 'option' => $option,
3193 'hidethirdpartylogo' => $hidethirdpartylogo,
3194 ];
3195 $classfortooltip = 'classfortooltip';
3196 $dataparams = '';
3197 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3198 $classfortooltip = 'classforajaxtooltip';
3199 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3200 $label = '';
3201 } else {
3202 $label = implode($this->getTooltipContentArray($params));
3203 }
3204
3205 $companylink = '';
3206 if (!empty($this->socid)) { // Add thirdparty for external users
3207 $thirdpartystatic = new Societe($this->db);
3208 $thirdpartystatic->fetch($this->socid);
3209 if (empty($hidethirdpartylogo)) {
3210 $companylink = ' '.$thirdpartystatic->getNomUrl(2, 'nolink', 0, 1); // picto only of company
3211 }
3212 }
3213
3214 if ($infologin < 0) {
3215 $label = '';
3216 }
3217
3218 $baseurl = DOL_URL_ROOT . '/user/card.php';
3219 if ($option == 'leave') {
3220 $baseurl = DOL_URL_ROOT . '/holiday/list.php';
3221 }
3222 $query = ['id' => $this->id];
3223 if ($option != 'nolink') {
3224 // Add param to save lastsearch_values or not
3225 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3226 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3227 $add_save_lastsearch_values = 1;
3228 }
3229 if ($add_save_lastsearch_values) {
3230 $query = array_merge($query, ['save_lastsearch_values' => 1]);
3231 }
3232 }
3233 $url = dolBuildUrl($baseurl, $query);
3234
3235 $linkstart = '<a href="'.$url.'"';
3236 $linkclose = "";
3237 if (empty($notooltip)) {
3238 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3239 $langs->load("users");
3240 $label = $langs->trans("ShowUser");
3241 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3242 }
3243 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3244 $linkclose .= $dataparams . ' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
3245 } else {
3246 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
3247 }
3248
3249 $linkstart .= $linkclose.'>';
3250 $linkend = '</a>';
3251
3252 //if ($withpictoimg == -1) $result.='<div class="nowrap">';
3253 $result .= (($option == 'nolink') ? '' : $linkstart);
3254 if ($withpictoimg) {
3255 $paddafterimage = '';
3256 if (abs((int) $withpictoimg) == 1 || abs((int) $withpictoimg) == 4) {
3257 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3258 }
3259 // Only picto
3260 if ($withpictoimg > 0) {
3261 $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>';
3262 } else {
3263 // Picto must be a photo
3264 $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>';
3265 }
3266 $result .= $picto;
3267 }
3268 if ($withpictoimg == -4 || ($withpictoimg > -2 && $withpictoimg != 2)) {
3269 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3270 $result .= '<span class="nopadding usertext'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
3271 }
3272 if ($mode == 'login') {
3273 $result .= dol_string_nohtmltag(dol_trunc($this->login, $maxlen));
3274 } else {
3275 $result .= dol_string_nohtmltag($this->getFullName($langs, 0, ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen));
3276 }
3277 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3278 $result .= '</span>';
3279 }
3280 }
3281 $result .= (($option == 'nolink') ? '' : $linkend);
3282 //if ($withpictoimg == -1) $result.='</div>';
3283
3284 $result .= $companylink;
3285
3286 global $action;
3287 $hookmanager->initHooks(array('userdao'));
3288 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
3289 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3290 if ($reshook > 0) {
3291 $result = $hookmanager->resPrint;
3292 } else {
3293 $result .= $hookmanager->resPrint;
3294 }
3295
3296 return $result;
3297 }
3298
3308 public function getLoginUrl($withpictoimg = 0, $option = '', $notooltip = 0, $morecss = '')
3309 {
3310 global $langs, $user;
3311
3312 $result = '';
3313
3314 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3315 $linkend = '</a>';
3316
3317 //Check user's rights to see an other user
3318 if ((!$user->hasRight('user', 'user', 'lire') && $this->id != $user->id)) {
3319 $option = 'nolink';
3320 }
3321
3322 if ($option == 'xxx') {
3323 $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
3324 $linkend = '</a>';
3325 }
3326
3327 if ($option == 'nolink') {
3328 $linkstart = '';
3329 $linkend = '';
3330 }
3331
3332 $result .= $linkstart;
3333 if ($withpictoimg) {
3334 $paddafterimage = '';
3335 if (abs($withpictoimg) == 1) {
3336 $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"';
3337 }
3338 // Only picto
3339 if ($withpictoimg > 0) {
3340 $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
3341 } else {
3342 // Picto must be a photo
3343 $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>';
3344 }
3345 $result .= $picto;
3346 }
3347 $result .= $this->login;
3348 $result .= $linkend;
3349
3350 return $result;
3351 }
3352
3359 public function getLibStatut($mode = 0)
3360 {
3361 return $this->LibStatut(isset($this->statut) ? (int) $this->statut : (int) $this->status, $mode);
3362 }
3363
3364 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3372 public function LibStatut($status, $mode = 0)
3373 {
3374 // phpcs:enable
3375 global $langs;
3376
3377 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3378 global $langs;
3379 //$langs->load("mymodule");
3380 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3381 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3382 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
3383 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
3384 }
3385
3386 $statusType = 'status5';
3387 if ($status == self::STATUS_ENABLED) {
3388 $statusType = 'status4';
3389 }
3390
3391 $label = $this->labelStatus[$status];
3392 $labelshort = $this->labelStatusShort[$status];
3393
3394 $now = dol_now();
3395 if (!empty($this->datestartvalidity) && $now < $this->datestartvalidity) {
3396 $statusType = 'status3';
3397 $label .= ' ('.$langs->trans("UserNotYetValid").')';
3398 }
3399 if (!empty($this->dateendvalidity) && $now > ($this->dateendvalidity + 24 * 3600 - 1)) {
3400 $statusType = 'status2';
3401 $label .= ' ('.$langs->trans("UserExpired").')';
3402 }
3403
3404 return dolGetStatus($label, $labelshort, '', $statusType, $mode);
3405 }
3406
3407
3415 public function getKanbanView($option = '', $arraydata = null)
3416 {
3417 global $langs;
3418
3419 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3420
3421 $return = '<div class="box-flex-item box-flex-grow-zero">';
3422 $return .= '<div class="info-box info-box-sm">';
3423 $return .= '<span class="info-box-icon bg-infobox-action">';
3424
3425 $label = '';
3426 if (!empty($this->photo)) {
3427 //$label .= '<div class="photointooltip floatright">';
3428 $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
3429 //$label .= '</div>';
3430 //$label .= '<div style="clear: both;"></div>';
3431 $return .= $label;
3432 } else {
3433 $return .= img_picto('', $this->picto);
3434 }
3435
3436 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3437 $return .= '</span>';
3438 $return .= '<div class="info-box-content">';
3439 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(0, '', 0, 0, 24, 0, '', 'valignmiddle') : $this->ref);
3440 if (isModEnabled('multicompany') && $this->admin && !$this->entity) {
3441 $return .= img_picto($langs->trans("SuperAdministratorDesc"), 'superadmin', 'class="valignmiddle paddingright paddingleft"');
3442 } elseif ($this->admin) {
3443 $return .= img_picto($langs->trans("AdministratorDesc"), 'admin', 'class="valignmiddle paddingright paddingleft"');
3444 }
3445 $return .= '</span>';
3446 if ($selected >= 0) {
3447 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3448 }
3449 if (property_exists($this, 'label')) {
3450 $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
3451 }
3452 if ($this->email) {
3453 $return .= '<br><span class="info-box-label opacitymedium small">'.img_picto('', 'email').' '.$this->email.'</span>';
3454 }
3455 if (method_exists($this, 'getLibStatut')) {
3456 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3457 }
3458 $return .= '</div>';
3459 $return .= '</div>';
3460 $return .= '</div>';
3461
3462 return $return;
3463 }
3464
3465
3466 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3467 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3477 public function _load_ldap_dn($info, $mode = 0)
3478 {
3479 // phpcs:enable
3480 global $conf;
3481 $dn = '';
3482 if ($mode == 0) {
3483 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')]."," . getDolGlobalString('LDAP_USER_DN');
3484 } elseif ($mode == 1) {
3485 $dn = getDolGlobalString('LDAP_USER_DN');
3486 } elseif ($mode == 2) {
3487 $dn = getDolGlobalString('LDAP_KEY_USERS') . "=".$info[getDolGlobalString('LDAP_KEY_USERS')];
3488 }
3489 return $dn;
3490 }
3491
3492 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
3493 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3499 public function _load_ldap_info()
3500 {
3501 // phpcs:enable
3502 global $conf, $langs;
3503
3504 $info = array();
3505
3506 $socialnetworks = getArrayOfSocialNetworks();
3507
3508 $keymodified = false;
3509
3510 // Object classes
3511 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_USER_OBJECT_CLASS'));
3512
3513 $this->fullname = $this->getFullName($langs);
3514
3515 // Possible LDAP KEY (constname => varname)
3516 $ldapkey = array(
3517 'LDAP_FIELD_FULLNAME' => 'fullname',
3518 'LDAP_FIELD_NAME' => 'lastname',
3519 'LDAP_FIELD_FIRSTNAME' => 'firstname',
3520 'LDAP_FIELD_LOGIN' => 'login',
3521 'LDAP_FIELD_LOGIN_SAMBA' => 'login',
3522 'LDAP_FIELD_PHONE' => 'office_phone',
3523 'LDAP_FIELD_MOBILE' => 'user_mobile',
3524 'LDAP_FIELD_FAX' => 'office_fax',
3525 'LDAP_FIELD_MAIL' => 'email',
3526 'LDAP_FIELD_SID' => 'ldap_sid',
3527 );
3528
3529 // Champs
3530 foreach ($ldapkey as $constname => $varname) {
3531 if (!empty($this->$varname) && getDolGlobalString($constname)) {
3532 $info[getDolGlobalString($constname)] = $this->$varname;
3533
3534 // Check if it is the LDAP key and if its value has been changed
3535 if (getDolGlobalString('LDAP_KEY_USERS') && getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString($constname)) {
3536 if (is_object($this->oldcopy) && !$this->oldcopy->isEmpty() && $this->$varname != $this->oldcopy->$varname) {
3537 $keymodified = true; // For check if LDAP key has been modified
3538 }
3539 }
3540 }
3541 }
3542 foreach ($socialnetworks as $key => $value) {
3543 if (!empty($this->socialnetworks[$value['label']]) && getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))) {
3544 $info[getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3545 }
3546 }
3547 if ($this->address && getDolGlobalString('LDAP_FIELD_ADDRESS')) {
3548 $info[getDolGlobalString('LDAP_FIELD_ADDRESS')] = $this->address;
3549 }
3550 if ($this->zip && getDolGlobalString('LDAP_FIELD_ZIP')) {
3551 $info[getDolGlobalString('LDAP_FIELD_ZIP')] = $this->zip;
3552 }
3553 if ($this->town && getDolGlobalString('LDAP_FIELD_TOWN')) {
3554 $info[getDolGlobalString('LDAP_FIELD_TOWN')] = $this->town;
3555 }
3556 if ($this->note_public && getDolGlobalString('LDAP_FIELD_DESCRIPTION')) {
3557 $info[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_public, 2);
3558 }
3559 if ($this->socid > 0 && getDolGlobalString('LDAP_FIELD_COMPANY')) {
3560 $soc = new Societe($this->db);
3561 $soc->fetch($this->socid);
3562
3563 $info[getDolGlobalString('LDAP_FIELD_COMPANY')] = $soc->name;
3564 if ($soc->client == 1) {
3565 $info["businessCategory"] = "Customers";
3566 }
3567 if ($soc->client == 2) {
3568 $info["businessCategory"] = "Prospects";
3569 }
3570 if ($soc->fournisseur == 1) {
3571 $info["businessCategory"] = "Suppliers";
3572 }
3573 }
3574
3575 // When password is modified
3576 if (!empty($this->pass)) {
3577 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3578 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass; // this->pass = unencrypted password
3579 }
3580 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3581 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3582 }
3583 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3584 // Set LDAP password if possible
3585 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3586 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
3587 // Just for the default MD5 !
3588 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) {
3589 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3590 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); // Create OpenLDAP MD5 password from Dolibarr MD5 password
3591 }
3592 }
3593 } elseif (!empty($this->pass_indatabase)) {
3594 // Use $this->pass_indatabase value if exists
3595 if (getDolGlobalString('LDAP_FIELD_PASSWORD')) {
3596 $info[getDolGlobalString('LDAP_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = unencrypted password
3597 }
3598 if (getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')) {
3599 $info[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3600 }
3601 }
3602 }
3603
3604 if (getDolGlobalString('LDAP_SERVER_TYPE') == 'egroupware') {
3605 $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
3606
3607 $info['uidnumber'] = $this->id;
3608
3609 $info['phpgwTz'] = 0;
3610 $info['phpgwMailType'] = 'INTERNET';
3611 $info['phpgwMailHomeType'] = 'INTERNET';
3612
3613 $info["phpgwContactTypeId"] = 'n';
3614 $info["phpgwContactCatId"] = 0;
3615 $info["phpgwContactAccess"] = "public";
3616
3617 $info["phpgwContactOwner"] = 1;
3618
3619 if ($this->email) {
3620 $info["rfc822Mailbox"] = $this->email;
3621 }
3622 if ($this->user_mobile) {
3623 $info["phpgwCellTelephoneNumber"] = $this->user_mobile;
3624 }
3625 }
3626
3627 if (getDolGlobalString('LDAP_FIELD_USERID')) {
3628 $info[getDolGlobalString('LDAP_FIELD_USERID')] = $this->id;
3629 }
3630 if (getDolGlobalString('LDAP_FIELD_GROUPID')) {
3631 $usergroup = new UserGroup($this->db);
3632 $groupslist = $usergroup->listGroupsForUser($this->id);
3633 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = '65534';
3634 if (!empty($groupslist)) {
3635 foreach ($groupslist as $groupforuser) {
3636 $info[getDolGlobalString('LDAP_FIELD_GROUPID')] = $groupforuser->id; //Select first group in list
3637 break;
3638 }
3639 }
3640 }
3641 if (getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY') && getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')) {
3642 $info[getDolGlobalString('LDAP_FIELD_HOMEDIRECTORY')] = getDolGlobalString('LDAP_FIELD_HOMEDIRECTORYPREFIX')."/".$this->login;
3643 }
3644
3645 return $info;
3646 }
3647
3648
3656 public function initAsSpecimen()
3657 {
3658 global $user;
3659
3660 $now = dol_now();
3661
3662 // Initialise parameters
3663 $this->id = 0;
3664 $this->ref = 'SPECIMEN';
3665 $this->specimen = 1;
3666 $this->user_creation_id = $user->id;
3667
3668 $this->lastname = 'DOLIBARR';
3669 $this->firstname = 'SPECIMEN';
3670 $this->gender = 'man';
3671 $this->note_public = 'This is a note public';
3672 $this->note_private = 'This is a note private';
3673 $this->email = 'email@specimen.com';
3674 $this->personal_email = 'personalemail@specimen.com';
3675 $this->socialnetworks = array(
3676 'skype' => 'skypepseudo',
3677 'twitter' => 'twitterpseudo',
3678 'facebook' => 'facebookpseudo',
3679 'linkedin' => 'linkedinpseudo',
3680 );
3681 $this->office_phone = '0999999999';
3682 $this->office_fax = '0999999998';
3683 $this->user_mobile = '0999999997';
3684 $this->personal_mobile = '0999999996';
3685 $this->admin = 0;
3686 $this->login = 'dolibspec';
3687 $this->pass = 'dolibSpec+@123';
3688 //$this->pass_indatabase='dolibspec'; Set after a fetch
3689 //$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab'; Set after a fetch
3690 $this->datec = $now;
3691 $this->datem = $now;
3692
3693 $this->datelastlogin = $now;
3694 $this->iplastlogin = '127.0.0.1';
3695 $this->datepreviouslogin = $now;
3696 $this->ippreviouslogin = '127.0.0.1';
3697 $this->status = 1;
3698
3699 $this->entity = 1;
3700
3701 return 1;
3702 }
3703
3710 public function info($id)
3711 {
3712 $sql = "SELECT u.rowid, u.login as ref, u.datec, fk_user_creat as user_creation_id, fk_user_modif as user_modification_id,";
3713 $sql .= " GREATEST(u.tms, COALESCE(uef.tms, u.tms)) as date_modification, u.entity";
3714 $sql .= " FROM ".$this->db->prefix()."user as u";
3715 $sql .= " LEFT JOIN ".$this->db->prefix()."user_extrafields as uef ON uef.fk_object = u.rowid";
3716 $sql .= " WHERE u.rowid = ".((int) $id);
3717
3718 $result = $this->db->query($sql);
3719 if ($result) {
3720 if ($this->db->num_rows($result)) {
3721 $obj = $this->db->fetch_object($result);
3722
3723 $this->id = $obj->rowid;
3724
3725 $this->user_creation_id = $obj->user_creation_id;
3726 $this->user_modification_id = $obj->user_modification_id;
3727
3728 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
3729 $this->date_creation = $this->db->jdate($obj->datec);
3730 $this->date_modification = $this->db->jdate($obj->date_modification);
3731 $this->entity = $obj->entity;
3732 }
3733
3734 $this->db->free($result);
3735 } else {
3736 dol_print_error($this->db);
3737 }
3738 }
3739
3740
3746 public function getNbOfEMailings()
3747 {
3748 $sql = "SELECT count(mc.email) as nb";
3749 $sql .= " FROM ".$this->db->prefix()."mailing_cibles as mc";
3750 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3751 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
3752
3753 $resql = $this->db->query($sql);
3754 if ($resql) {
3755 $obj = $this->db->fetch_object($resql);
3756 $nb = (int) $obj->nb;
3757
3758 $this->db->free($resql);
3759 return $nb;
3760 } else {
3761 $this->error = $this->db->error();
3762 return -1;
3763 }
3764 }
3765
3774 public function getNbOfUsers($limitTo, $option = '', $admin = -1)
3775 {
3776 $sql = "SELECT count(rowid) as nb";
3777 $sql .= " FROM ".$this->db->prefix()."user";
3778 if ($option == 'superadmin') {
3779 $sql .= " WHERE entity = 0";
3780 } else {
3781 $sql .= " WHERE entity IN (".getEntity('user', 0).")";
3782 if ($limitTo == 'active') {
3783 $sql .= " AND statut = 1";
3784 }
3785 }
3786 if ($admin >= 0) {
3787 $sql .= " AND admin = ".(int) $admin;
3788 }
3789
3790 $resql = $this->db->query($sql);
3791 if ($resql) {
3792 $obj = $this->db->fetch_object($resql);
3793 $nb = (int) $obj->nb;
3794
3795 $this->db->free($resql);
3796 return $nb;
3797 } else {
3798 $this->error = $this->db->lasterror();
3799 return -1;
3800 }
3801 }
3802
3803 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3810 public function update_ldap2dolibarr(&$ldapuser)
3811 {
3812 // phpcs:enable
3813 // TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global $user écrase ?)
3814 global $user;
3815
3816 $socialnetworks = getArrayOfSocialNetworks();
3817
3818 $tmpvar = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
3819 $this->firstname = $ldapuser->$tmpvar;
3820 $tmpvar = getDolGlobalString('LDAP_FIELD_NAME');
3821 $this->lastname = $ldapuser->$tmpvar;
3822 $tmpvar = getDolGlobalString('LDAP_FIELD_LOGIN');
3823 $this->login = $ldapuser->$tmpvar;
3824 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD');
3825 $this->pass = $ldapuser->$tmpvar;
3826 $tmpvar = getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED');
3827 $this->pass_indatabase_crypted = $ldapuser->$tmpvar;
3828
3829 $tmpvar = getDolGlobalString('LDAP_FIELD_PHONE');
3830 $this->office_phone = $ldapuser->$tmpvar;
3831 $tmpvar = getDolGlobalString('LDAP_FIELD_MOBILE');
3832 $this->user_mobile = $ldapuser->$tmpvar;
3833 $tmpvar = getDolGlobalString('LDAP_FIELD_FAX');
3834 $this->office_fax = $ldapuser->$tmpvar;
3835 $tmpvar = getDolGlobalString('LDAP_FIELD_MAIL');
3836 $this->email = $ldapuser->$tmpvar;
3837 foreach ($socialnetworks as $key => $value) {
3838 $tmpvar = getDolGlobalString('LDAP_FIELD_'.strtoupper($value['label']));
3839 $this->socialnetworks[$value['label']] = $ldapuser->$tmpvar;
3840 }
3841 $tmpvar = getDolGlobalString('LDAP_FIELD_SID');
3842 $this->ldap_sid = $ldapuser->$tmpvar;
3843
3844 $tmpvar = getDolGlobalString('LDAP_FIELD_TITLE');
3845 $this->job = $ldapuser->$tmpvar;
3846 $tmpvar = getDolGlobalString('LDAP_FIELD_DESCRIPTION');
3847 $this->note_public = $ldapuser->$tmpvar;
3848
3849 $result = $this->update($user);
3850
3851 dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
3852
3853 return $result;
3854 }
3855
3856
3857 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3864 public function get_children()
3865 {
3866 // phpcs:enable
3867 $sql = "SELECT rowid FROM ".$this->db->prefix()."user";
3868 $sql .= " WHERE fk_user = ".((int) $this->id);
3869
3870 dol_syslog(get_class($this)."::get_children", LOG_DEBUG);
3871 $res = $this->db->query($sql);
3872 if ($res) {
3873 $users = array();
3874 while ($rec = $this->db->fetch_array($res)) {
3875 $user = new User($this->db);
3876 $user->fetch($rec['rowid']);
3877 $users[] = $user;
3878 }
3879 return $users;
3880 } else {
3881 dol_print_error($this->db);
3882 return -1;
3883 }
3884 }
3885
3886
3892 private function loadParentOf()
3893 {
3894 $this->parentof = array();
3895
3896 // Load array[child]=parent
3897 $sql = "SELECT fk_user as id_parent, rowid as id_son";
3898 $sql .= " FROM ".$this->db->prefix()."user";
3899 $sql .= " WHERE fk_user <> 0";
3900 $sql .= " AND entity IN (".getEntity('user').")";
3901
3902 dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
3903 $resql = $this->db->query($sql);
3904 if ($resql) {
3905 while ($obj = $this->db->fetch_object($resql)) {
3906 $this->parentof[$obj->id_son] = $obj->id_parent;
3907 }
3908 return 1;
3909 } else {
3910 dol_print_error($this->db);
3911 return -1;
3912 }
3913 }
3914
3915 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3929 public function get_full_tree($deleteafterid = 0, $filter = '')
3930 {
3931 // phpcs:enable
3932 global $hookmanager;
3933
3934 // Actions hooked (by external module)
3935 $hookmanager->initHooks(array('userdao'));
3936
3937 $this->users = array();
3938
3939 // Init this->parentof that is array(id_son=>id_parent, ...)
3940 $this->loadParentOf();
3941
3942 // Init $this->users array
3943 $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
3944 $sql .= " FROM ".$this->db->prefix()."user as u";
3945 // Add fields from hooks
3946 $parameters = array();
3947 $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
3948 if ($reshook > 0) {
3949 $sql .= $hookmanager->resPrint;
3950 } else {
3951 $sql .= " WHERE u.entity IN (".getEntity('user').")";
3952 }
3953 if ($filter) {
3954 $sql .= " AND ".$filter; // already sanitized
3955 }
3956
3957 dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
3958 $resql = $this->db->query($sql);
3959 if ($resql) {
3960 $i = 0;
3961 while ($obj = $this->db->fetch_object($resql)) {
3962 $this->users[(int) $obj->rowid]
3963 = array(
3964 'rowid' => (int) $obj->rowid,
3965 'id' => (int) $obj->rowid,
3966 'fk_user' => (int) $obj->fk_user,
3967 'fk_soc' => (int) $obj->fk_soc,
3968 'firstname' => (string) $obj->firstname,
3969 'lastname' => (string) $obj->lastname,
3970 'login' => (string) $obj->login,
3971 'statut' => (int) $obj->statut,
3972 'entity' => (int) $obj->entity,
3973 'email' => (string) $obj->email,
3974 'gender' => (string) $obj->gender,
3975 'admin' => (int) $obj->admin,
3976 'photo' => (string) $obj->photo,
3977 // fields are filled with build_path_from_id_user
3978 'fullpath' => '',
3979 'fullname' => '',
3980 'level' => 0,
3981 );
3982 $i++;
3983 }
3984 } else {
3985 dol_print_error($this->db);
3986 return -1;
3987 }
3988
3989 // We add the fullpath property to each element of the first level (no parent exists)
3990 dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
3991 foreach ($this->users as $key => $val) {
3992 $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
3993 if ($result < 0) {
3994 $this->error = 'ErrorLoopInHierarchy';
3995 return -1;
3996 }
3997 }
3998
3999 // Exclude leaf including $deleteafterid from tree
4000 if ($deleteafterid) {
4001 //print "Look to discard user ".$deleteafterid."\n";
4002 $keyfilter1 = '^'.$deleteafterid.'$';
4003 $keyfilter2 = '_'.$deleteafterid.'$';
4004 $keyfilter3 = '^'.$deleteafterid.'_';
4005 $keyfilter4 = '_'.$deleteafterid.'_';
4006 foreach (array_keys($this->users) as $key) {
4007 $fullpath = (string) $this->users[$key]['fullpath'];
4008 if (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
4009 || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath)) {
4010 unset($this->users[$key]);
4011 }
4012 }
4013 }
4014
4015 dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
4016 $this->users = dol_sort_array($this->users, 'fullname', 'asc', 1, 0, 1);
4017
4018 //var_dump($this->users);
4019
4020 return $this->users;
4021 }
4022
4031 public function getAllChildIds($addcurrentuser = 0)
4032 {
4033 $childids = array();
4034
4035 if (isset($this->cache_childids[$this->id])) {
4036 $childids = $this->cache_childids[$this->id];
4037 } else {
4038 // Init this->users
4039 $treeresult = $this->get_full_tree();
4040
4041 $idtoscan = $this->id;
4042
4043 dol_syslog("Build childid for id = ".$idtoscan);
4044 foreach ($this->users as $id => $val) {
4045 //var_dump($val['fullpath']);
4046 if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
4047 $childids[$val['id']] = $val['id'];
4048 }
4049 }
4050
4051 // A loop anywhere in the hierarchy aborts get_full_tree(), leaving the branches it had not
4052 // walked yet with an empty fullpath, so they silently drop out of the list above. Do not
4053 // cache such a truncated result, it would be reused for the whole request.
4054 if ($treeresult < 0) {
4055 dol_syslog(get_class($this)."::getAllChildIds got a truncated tree: ".$this->error, LOG_WARNING);
4056 return $addcurrentuser ? array($this->id => $this->id) : $childids;
4057 }
4058 }
4059 $this->cache_childids[$this->id] = $childids;
4060
4061 if ($addcurrentuser) {
4062 $childids[$this->id] = $this->id;
4063 }
4064
4065 return $childids;
4066 }
4067
4068 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4077 public function build_path_from_id_user($id_user, $protection = 0)
4078 {
4079 // phpcs:enable
4080 //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
4081
4082 if (!empty($this->users[$id_user]['fullpath'])) {
4083 // Already defined
4084 dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
4085 return 0;
4086 }
4087
4088 // Define fullpath and fullname
4089 $this->users[$id_user]['fullpath'] = '_'.$id_user;
4090 $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
4091 $i = 0;
4092 $cursor_user = $id_user;
4093
4094 $useridfound = array($id_user);
4095 while (!empty($this->parentof[$cursor_user]) && !empty($this->users[$this->parentof[$cursor_user]])) { // @phan-suppress-current-line PhanTypeMismatchProperty
4096 if (in_array($this->parentof[$cursor_user], $useridfound)) {
4097 dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
4098 return -1; // Should not happen. Protection against looping hierarchy
4099 }
4100 $useridfound[] = $this->parentof[$cursor_user];
4101 $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
4102 $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
4103 $i++;
4104 $cursor_user = $this->parentof[$cursor_user];
4105 }
4106
4107 // We count number of _ to have level
4108 $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
4109
4110 return 1;
4111 }
4112
4121 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4122 {
4123 $tables = array(
4124 'user',
4125 );
4126
4127 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4128 }
4129
4130
4136 public function loadStateBoard()
4137 {
4138 $this->nb = array();
4139
4140 $sql = "SELECT COUNT(DISTINCT u.rowid) as nb";
4141 $sql .= " FROM ".$this->db->prefix()."user as u";
4142 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4143 $sql .= ", ".$this->db->prefix()."usergroup_user as ug";
4144 $sql .= " WHERE ug.entity IN (".getEntity('usergroup').")";
4145 $sql .= " AND ug.fk_user = u.rowid";
4146 } else {
4147 $sql .= " WHERE u.entity IN (".getEntity('user').")";
4148 }
4149 $sql .= " AND u.statut > 0";
4150 //$sql.= " AND employee != 0";
4151
4152 $resql = $this->db->query($sql);
4153 if ($resql) {
4154 while ($obj = $this->db->fetch_object($resql)) {
4155 $this->nb["users"] = $obj->nb;
4156 }
4157 $this->db->free($resql);
4158 return 1;
4159 } else {
4160 dol_print_error($this->db);
4161 $this->error = $this->db->error();
4162 return -1;
4163 }
4164 }
4165
4177 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4178 {
4179 global $langs;
4180
4181 $langs->load("user");
4182
4183 // Set the '$modele' to the name of the document template (model) to use
4184 if (!dol_strlen($modele)) {
4185 if (getDolGlobalString('USER_ADDON_PDF')) {
4186 $modele = getDolGlobalString('USER_ADDON_PDF');
4187 } else {
4188 $modele = 'bluesky';
4189 }
4190 }
4191
4192 $modelpath = "core/modules/user/doc/";
4193
4194 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4195 }
4196
4197 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4205 public function user_get_property($rowid, $mode)
4206 {
4207 // phpcs:enable
4208 $user_property = '';
4209
4210 if (empty($rowid)) {
4211 return '';
4212 }
4213
4214 $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
4215 $sql .= " FROM ".$this->db->prefix()."user";
4216 $sql .= " WHERE rowid = ".((int) $rowid);
4217
4218 $resql = $this->db->query($sql);
4219 if ($resql) {
4220 $nump = $this->db->num_rows($resql);
4221
4222 if ($nump) {
4223 $obj = $this->db->fetch_object($resql);
4224
4225 if ($mode == 'email') {
4226 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
4227 } elseif ($mode == 'mobile') {
4228 $user_property = $obj->user_mobile;
4229 } elseif ($mode == 'name') {
4230 $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname);
4231 }
4232 }
4233 return $user_property;
4234 } else {
4235 dol_print_error($this->db);
4236 }
4237
4238 return '';
4239 }
4240
4248 public function getOnlineVirtualCardUrl($mode = '', $typeofurl = 'external')
4249 {
4251 global $conf;
4252
4253 $instanceuniqueid = empty($conf->file->instance_unique_id) ? '' : $conf->file->instance_unique_id;
4254 $encodedsecurekey = dol_hash($instanceuniqueid.'uservirtualcard'.$this->id.'-'.$this->login, 'md5');
4255 if (isModEnabled('multicompany')) {
4256 $entity_qr = '&entity='.((int) $conf->entity);
4257 } else {
4258 $entity_qr = '';
4259 }
4260 // Define $urlwithroot
4261 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
4262 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
4263 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
4264
4265 if ($typeofurl == 'internal') {
4266 $urlwithroot = DOL_URL_ROOT;
4267 }
4268
4269 return $urlwithroot.'/public/users/view.php?id='.$this->id.'&securekey='.$encodedsecurekey.$entity_qr.($mode ? '&mode='.urlencode($mode) : '');
4270 }
4271
4285 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND', $entityfilter = false)
4286 {
4287 global $conf, $user;
4288
4289 $sql = "SELECT t.rowid";
4290 $sql .= ' FROM '.$this->db->prefix().$this->table_element.' as t ';
4291
4292 if ($entityfilter) {
4293 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
4294 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
4295 $sql .= " WHERE t.entity IS NOT NULL"; // Show all users
4296 } else {
4297 $sql .= " WHERE t.entity = 0 OR EXISTS (";
4298 $sql .= " SELECT ug.rowid FROM " . $this->db->prefix() . "usergroup_user as ug";
4299 $sql .= " WHERE ug.fk_user = t.rowid AND ug.entity IN (" . getEntity('usergroup') . "))";
4300 }
4301 } else {
4302 $sql .= " WHERE t.entity IN (".getEntity('user').")";
4303 }
4304 } else {
4305 $sql .= " WHERE 1 = 1";
4306 }
4307
4308 // Manage filter
4309 $errormessage = '';
4310 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
4311 if ($errormessage) {
4312 $this->errors[] = $errormessage;
4313 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
4314 return -1;
4315 }
4316
4317 $sql .= $this->db->order($sortfield, $sortorder);
4318 if ($limit) {
4319 $sql .= $this->db->plimit($limit + 1, $offset);
4320 }
4321
4322 dol_syslog(__METHOD__, LOG_DEBUG);
4323
4324 $resql = $this->db->query($sql);
4325 if ($resql) {
4326 $this->users = array();
4327 $num = $this->db->num_rows($resql);
4328 if ($num) {
4329 while ($obj = $this->db->fetch_object($resql)) {
4330 $line = new self($this->db);
4331 $result = $line->fetch($obj->rowid);
4332 if ($result > 0 && !empty($line->id)) {
4333 $this->users[$obj->rowid] = clone $line;
4334 }
4335 }
4336 $this->db->free($resql);
4337 }
4338 return $num;
4339 } else {
4340 $this->errors[] = $this->db->lasterror();
4341 return -1;
4342 }
4343 }
4344
4352 private $findUserIdByEmailCache;
4353
4364 public function findUserIdByEmail($email)
4365 {
4366 if (isset($this->findUserIdByEmailCache[$email])) {
4367 return $this->findUserIdByEmailCache[$email];
4368 }
4369
4370 $this->findUserIdByEmailCache[$email] = -1;
4371
4372 $sql = 'SELECT rowid';
4373 $sql .= ' FROM '.$this->db->prefix().'user';
4374 if (getDolGlobalString('AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR')) {
4375 $sql .= " WHERE email LIKE '%".$this->db->escape($this->db->escapeforlike($email))."%'";
4376 } else {
4377 $sql .= " WHERE email = '".$this->db->escape($email)."'";
4378 }
4379 $sql .= ' LIMIT 1';
4380
4381 $resql = $this->db->query($sql);
4382 if (!$resql) {
4383 return -1;
4384 }
4385
4386 $obj = $this->db->fetch_object($resql);
4387 if (!$obj) {
4388 return -1;
4389 }
4390
4391 $this->findUserIdByEmailCache[$email] = (int) $obj->rowid;
4392
4393 return $this->findUserIdByEmailCache[$email];
4394 }
4395
4402 public function cloneRights($fromId, $toId)
4403 {
4404 if (empty($fromId) || empty($toId)) {
4405 return -1;
4406 }
4407
4408 $this->db->begin();
4409
4410 // delete default rights for UserTo
4411 $sqlDelete = "DELETE FROM ".$this->db->prefix()."user_rights";
4412 $sqlDelete .= " WHERE fk_user = ".((int) $toId);
4413
4414 dol_syslog(get_class($this)."::clone_rights (delete default permissions)", LOG_DEBUG);
4415
4416 if (!$this->db->query($sqlDelete)) {
4417 $this->db->rollback();
4418 return -1;
4419 }
4420
4421 // Construction of the insertion request
4422 $sql = "INSERT INTO ".$this->db->prefix()."user_rights (entity, fk_user, fk_id)";
4423 $sql .= " SELECT entity, ".((int) $toId).", fk_id";
4424 $sql .= " FROM ".$this->db->prefix()."user_rights src";
4425 $sql .= " WHERE fk_user = ".((int) $fromId);
4426 $sql .= " AND NOT EXISTS (";
4427 $sql .= " SELECT 1";
4428 $sql .= " FROM ".$this->db->prefix()."user_rights dest";
4429 $sql .= " WHERE dest.entity = src.entity";
4430 $sql .= " AND dest.fk_user = ".((int) $toId);
4431 $sql .= " AND dest.fk_id = src.fk_id";
4432 $sql .= " )";
4433
4434 dol_syslog(get_class($this)."::clone_rights", LOG_DEBUG);
4435
4436 // Execute request
4437 if (!$this->db->query($sql)) {
4438 $this->db->rollback();
4439 return -1;
4440 }
4441
4442 $this->db->commit();
4443 return 1;
4444 }
4445
4454 public function cloneCategories($fromId, $toId, $type = 'user')
4455 {
4456 $this->db->begin();
4457
4458 if (empty($type)) {
4459 $type = $this->table_element;
4460 }
4461
4462 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4463 $categorystatic = new Categorie($this->db);
4464
4465 $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_user)";
4466 $sql .= " SELECT fk_categorie, ".((int) $toId)." FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
4467 $sql .= " WHERE fk_user = ".((int) $fromId);
4468
4469 if (!$this->db->query($sql)) {
4470 $this->error = $this->db->lasterror();
4471 $this->db->rollback();
4472 return -1;
4473 }
4474
4475 $this->db->commit();
4476 return 1;
4477 }
4478}
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:678
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:664
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.