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