Passed
Push — master ( 4e88da...5feb35 )
by Alxarafe
26:36
created

Base/User.php (19 issues)

1
<?php
2
/* Copyright (C) 2018       Alxarafe            <[email protected]>
3
 *
4
 * This program is free software; you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16
 */
17
namespace Alixar\Base;
18
19
use Alixar\Helpers\DolUtils;
20
use Alxarafe\Helpers\Config;
21
use Alixar\Base\CommonObject;
22
use Alixar\Helpers\Globals;
23
24
class User extends CommonObject
25
{
26
27
    /**
28
     * @var string ID to identify managed object
29
     */
30
    public $element = 'user';
31
32
    /**
33
     * @var string Name of table without prefix where object is stored
34
     */
35
    public $table_element = 'user';
36
37
    /**
38
     * @var int Field with ID of parent key if this field has a parent
39
     */
40
    public $fk_element = 'fk_user';
41
42
    /**
43
     * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
44
     * @var int
45
     */
46
    public $ismultientitymanaged = 1;
47
    public $id = 0;
48
    public $statut;
49
    public $ldap_sid;
50
    public $search_sid;
51
    public $employee;
52
    public $gender;
53
    public $birth;
54
    public $email;
55
    public $skype;
56
    public $twitter;
57
    public $facebook;
58
    public $job;   // job position
59
    public $signature;
60
61
    /**
62
     * @var string Address
63
     */
64
    public $address;
65
    public $zip;
66
    public $town;
67
    public $state_id;  // The state/department
68
    public $state_code;
69
    public $state;
70
    public $office_phone;
71
    public $office_fax;
72
    public $user_mobile;
73
    public $admin;
74
    public $login;
75
    public $api_key;
76
77
    /**
78
     * @var int Entity
79
     */
80
    public $entity;
81
//! Clear password in memory
82
    public $pass;
83
//! Clear password in database (defined if DATABASE_PWD_ENCRYPTED=0)
84
    public $pass_indatabase;
85
//! Encrypted password in database (always defined)
86
    public $pass_indatabase_crypted;
87
    public $datec;
88
    public $datem;
89
//! If this is defined, it is an external user
90
    /**
91
     * @deprecated
92
     * @see socid
93
     */
94
    public $societe_id;
95
96
    /**
97
     * @deprecated
98
     * @see contactid
99
     */
100
    public $contact_id;
101
    public $socid;
102
    public $contactid;
103
104
    /**
105
     * @var int ID
106
     */
107
    public $fk_member;
108
109
    /**
110
     * @var int User ID
111
     */
112
    public $fk_user;
113
    public $clicktodial_url;
114
    public $clicktodial_login;
115
    public $clicktodial_password;
116
    public $clicktodial_poste;
117
    public $datelastlogin;
118
    public $datepreviouslogin;
119
    public $photo;
120
    public $lang;
121
    public $rights;                        // Array of permissions user->rights->permx
122
    public $all_permissions_are_loaded;    // All permission are loaded
123
    public $nb_rights;              // Number of rights granted to the user
124
    private $_tab_loaded = array();     // Cache array of already loaded permissions
125
    public $conf;             // To store personal config
126
    public $default_values;         // To store default values for user
127
    public $lastsearch_values_tmp;  // To store current search criterias for user
128
    public $lastsearch_values;      // To store last saved search criterias for user
129
    public $users = array();  // To store all tree of users hierarchy
130
    public $parentof;    // To store an array of all parents for all ids.
131
    private $cache_childids;
132
    public $accountancy_code;   // Accountancy code in prevision of the complete accountancy module
133
    public $thm;     // Average cost of employee - Used for valuation of time spent
134
    public $tjm;     // Average cost of employee
135
    public $salary;     // Monthly salary       - Denormalized value from llx_user_employment
136
    public $salaryextra;    // Monthly salary extra - Denormalized value from llx_user_employment
137
    public $weeklyhours;    // Weekly hours         - Denormalized value from llx_user_employment
138
    public $color;      // Define background color for user in agenda
139
    public $dateemployment;   // Define date of employment by company
140
    public $dateemploymentend;  // Define date of employment end by company
141
    public $default_c_exp_tax_cat;
142
    public $default_range;
143
    public $fields = array(
144
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
145
        'lastname' => array('type' => 'varchar(50)', 'label' => 'Name', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 20, 'searchall' => 1, 'comment' => 'Reference of object'),
146
        'firstname' => array('type' => 'varchar(50)', 'label' => 'Name', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1, 'comment' => 'Reference of object'),
147
    );
148
149
    /**
150
     *    Constructor of the class
151
     *
152
     *    @param   DoliDb  $db     Database handler
153
     */
154
    function __construct()
155
    {
156
// User preference
157
        $this->liste_limit = 0;
158
        $this->clicktodial_loaded = 0;
159
160
// For cache usage
161
        $this->all_permissions_are_loaded = 0;
162
        $this->nb_rights = 0;
163
164
// Force some default values
165
        $this->admin = 0;
166
        $this->employee = 1;
167
168
        $this->conf = new \stdClass();
169
        $this->rights = new \stdClass();
170
        $this->rights->user = new \stdClass();
171
        $this->rights->user->user = new \stdClass();
172
        $this->rights->user->self = new \stdClass();
173
    }
174
175
    /**
176
     * 	Load a user from database with its id or ref (login).
177
     *  This function does not load permissions, only user properties. Use getrights() for this just after the fetch.
178
     *
179
     * 	@param	int		$id		       		If defined, id to used for search
180
     * 	@param  string	$login       		If defined, login to used for search
181
     * 	@param  string	$sid				If defined, sid to used for search
182
     * 	@param	int		$loadpersonalconf	1=also load personal conf of user (in Globals::$user->conf->xxx), 0=do not load personal conf.
183
     *  @param  int     $entity             If a value is >= 0, we force the search on a specific entity. If -1, means search depens on default setup.
184
     * 	@return	int							<0 if KO, 0 not found, >0 if OK
185
     */
186
    function fetch($id = '', $login = '', $sid = '', $loadpersonalconf = 0, $entity = -1)
187
    {
188
// global $conf, Globals::$user;
189
// Clean parameters
190
        $login = trim($login);
191
192
// Get user
193
        $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.birth, u.email, u.job, u.skype, u.twitter, u.facebook,";
194
        $sql .= " u.signature, u.office_phone, u.office_fax, u.user_mobile,";
195
        $sql .= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,";
196
        $sql .= " u.admin, u.login, u.note,";
197
        $sql .= " u.pass, u.pass_crypted, u.pass_temp, u.api_key,";
198
        $sql .= " u.fk_soc, u.fk_socpeople, u.fk_member, u.fk_user, u.ldap_sid,";
199
        $sql .= " u.statut, u.lang, u.entity,";
200
        $sql .= " u.datec as datec,";
201
        $sql .= " u.tms as datem,";
202
        $sql .= " u.datelastlogin as datel,";
203
        $sql .= " u.datepreviouslogin as datep,";
204
        $sql .= " u.photo as photo,";
205
        $sql .= " u.openid as openid,";
206
        $sql .= " u.accountancy_code,";
207
        $sql .= " u.thm,";
208
        $sql .= " u.tjm,";
209
        $sql .= " u.salary,";
210
        $sql .= " u.salaryextra,";
211
        $sql .= " u.weeklyhours,";
212
        $sql .= " u.color,";
213
        $sql .= " u.dateemployment, u.dateemploymentend,";
214
        $sql .= " u.ref_int, u.ref_ext,";
215
        $sql .= " u.default_range, u.default_c_exp_tax_cat,";   // Expense report default mode
216
        $sql .= " c.code as country_code, c.label as country,";
217
        $sql .= " d.code_departement as state_code, d.nom as state";
218
        $sql .= " FROM " . MAIN_DB_PREFIX . "user as u";
219
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as c ON u.fk_country = c.rowid";
220
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_departements as d ON u.fk_state = d.rowid";
221
222
        if ($entity < 0) {
223
            if ((empty($conf->multicompany->enabled) || empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) && (!empty(Globals::$user->entity))) {
224
                $sql .= " WHERE u.entity IN (0," . Globals::$conf->entity . ")";
225
            } else {
226
                $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
227
            }
228
        } else {  // The fetch was forced on an entity
229
            if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
230
                $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
231
            } else {
232
                $sql .= " WHERE u.entity IN (0, " . (($entity != '' && $entity >= 0) ? $entity : Globals::$conf->entity) . ")";   // search in entity provided in parameter
233
            }
234
        }
235
236
        if ($sid) {    // permet une recherche du user par son SID ActiveDirectory ou Samba
237
//$sql .= " AND (u.ldap_sid = '" . Config::$dbEngine->escape($sid) . "' OR u.login = '" . Config::$dbEngine->escape($login) . "') LIMIT 1";
238
            $sql .= " AND (u.ldap_sid = '" . $sid . "' OR u.login = '" . Config::$dbEngine->escape($login) . "') LIMIT 1";
239
        } else if ($login) {
240
// $sql .= " AND u.login = '" . Config::$dbEngine->escape($login) . "'";
241
            $sql .= " AND u.login = '" . $login . "'";
242
        } else {
243
            $sql .= " AND u.rowid = " . $id;
244
        }
245
        $sql .= " ORDER BY u.entity ASC";    // Avoid random result when there is 2 login in 2 different entities
246
247
        $result = Config::$dbEngine->select($sql);
248
// echo "<p>SQL in 2477 of User: '$sql'</p>";
249
        if ($result) {
250
            if (count($result) > 0) {
251
252
// Convert array to stdclass
253
                $obj = json_decode(json_encode($result[0]));
254
255
                $this->id = $obj->rowid;
256
                $this->ref = $obj->rowid;
257
258
                $this->ref_int = $obj->ref_int;
259
                $this->ref_ext = $obj->ref_ext;
260
261
                $this->ldap_sid = $obj->ldap_sid;
262
                $this->lastname = $obj->lastname;
263
                $this->firstname = $obj->firstname;
264
265
                $this->employee = $obj->employee;
266
267
                $this->login = $obj->login;
268
                $this->gender = $obj->gender;
269
// $this->birth = Config::$dbEngine->jdate($obj->birth);
270
                $this->birth = $obj->birth;
271
272
                $this->pass_indatabase = $obj->pass;
273
                $this->pass_indatabase_crypted = $obj->pass_crypted;
274
                $this->pass = $obj->pass;
275
                $this->pass_temp = $obj->pass_temp;
276
                $this->api_key = $obj->api_key;
277
278
                $this->address = $obj->address;
279
                $this->zip = $obj->zip;
280
                $this->town = $obj->town;
281
282
                $this->country_id = $obj->country_id;
283
                $this->country_code = $obj->country_id ? $obj->country_code : '';
284
//$this->country 		= $obj->country_id?(Globals::$langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?Globals::$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
285
286
                $this->state_id = $obj->state_id;
287
                $this->state_code = $obj->state_code;
288
                $this->state = ($obj->state != '-' ? $obj->state : '');
289
290
                $this->office_phone = $obj->office_phone;
291
                $this->office_fax = $obj->office_fax;
292
                $this->user_mobile = $obj->user_mobile;
293
                $this->email = $obj->email;
294
                $this->skype = $obj->skype;
295
                $this->twitter = $obj->twitter;
296
                $this->facebook = $obj->facebook;
297
                $this->job = $obj->job;
298
                $this->signature = $obj->signature;
299
                $this->admin = $obj->admin;
300
                $this->note = $obj->note;
301
                $this->statut = $obj->statut;
302
                $this->photo = $obj->photo;
303
                $this->openid = $obj->openid;
304
                $this->lang = $obj->lang;
305
                $this->entity = $obj->entity;
306
                $this->accountancy_code = $obj->accountancy_code;
307
                $this->thm = $obj->thm;
308
                $this->tjm = $obj->tjm;
309
                $this->salary = $obj->salary;
310
                $this->salaryextra = $obj->salaryextra;
311
                $this->weeklyhours = $obj->weeklyhours;
312
                $this->color = $obj->color;
313
314
                /*
315
                  $this->dateemployment = Config::$dbEngine->jdate($obj->dateemployment);
316
                  $this->dateemploymentend = Config::$dbEngine->jdate($obj->dateemploymentend);
317
318
                  $this->datec = Config::$dbEngine->jdate($obj->datec);
319
                  $this->datem = Config::$dbEngine->jdate($obj->datem);
320
                  $this->datelastlogin = Config::$dbEngine->jdate($obj->datel);
321
                  $this->datepreviouslogin = Config::$dbEngine->jdate($obj->datep);
322
                 */
323
                $this->dateemployment = $obj->dateemployment;
324
                $this->dateemploymentend = $obj->dateemploymentend;
325
326
                $this->datec = $obj->datec;
327
                $this->datem = $obj->datem;
328
                $this->datelastlogin = $obj->datel;
329
                $this->datepreviouslogin = $obj->datep;
330
331
                $this->societe_id = $obj->fk_soc;  // deprecated
332
                $this->contact_id = $obj->fk_socpeople; // deprecated
333
                $this->socid = $obj->fk_soc;
334
                $this->contactid = $obj->fk_socpeople;
335
                $this->fk_member = $obj->fk_member;
336
                $this->fk_user = $obj->fk_user;
337
338
                $this->default_range = $obj->default_range;
339
                $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat;
340
341
// Protection when module multicompany was set, admin was set to first entity and then, the module was disabled,
342
// in such case, this admin user must be admin for ALL entities.
343
                if (empty($conf->multicompany->enabled) && $this->admin && $this->entity == 1) {
344
                    $this->entity = 0;
345
                }
346
347
// Retreive all extrafield
348
// fetch optionals attributes and labels
349
                $this->fetch_optionals();
350
            } else {
351
                $this->error = "USERNOTFOUND";
352
                DolUtils::dol_syslog(get_class($this) . "::fetch user not found", LOG_DEBUG);
353
                return 0;
354
            }
355
        } else {
356
            $this->error = Config::$dbEngine->lasterror();
357
            return -1;
358
        }
359
360
// To get back the global configuration unique to the user
361
        if ($loadpersonalconf) {
362
// Load user->conf for user
363
            $sql = "SELECT param, value FROM " . MAIN_DB_PREFIX . "user_param";
364
            $sql .= " WHERE fk_user = " . $this->id;
365
            $sql .= " AND entity = " . Globals::$conf->entity;
366
//DolUtils::dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
367
            $resql = Config::$dbEngine->select($sql);
368
            if (is_array($resql)) {
369
                foreach ($resql as $array) {
370
                    $obj = json_decode(json_encode($array));
371
372
                    $p = (!empty($obj->param) ? $obj->param : '');
373
                    if (!empty($p)) {
374
                        $this->conf->$p = $obj->value;
375
                    }
376
                }
377
            } else {
378
// $this->error = Config::$dbEngine->lasterror();
379
                return -2;
380
            }
381
382
            $result = $this->loadDefaultValues();
383
384
            if ($result < 0) {
385
// $this->error = Config::$dbEngine->lasterror();
386
                return -3;
387
            }
388
        }
389
390
        return 1;
391
    }
392
393
    /**
394
     *  Load default value in property ->default_values
395
     *
396
     *  @return int						> 0 if OK, < 0 if KO
397
     */
398
    function loadDefaultValues()
399
    {
400
// global $conf;
401
// Load user->default_values for user. TODO Save this in memcached ?
402
        $sql = "SELECT rowid, entity, type, page, param, value";
403
        $sql .= " FROM " . MAIN_DB_PREFIX . "default_values";
404
        $sql .= " WHERE entity IN (" . ($this->entity > 0 ? $this->entity . ", " : "") . Globals::$conf->entity . ")"; // Entity of user (if defined) + current entity
405
        $sql .= " AND user_id IN (0" . ($this->id > 0 ? ", " . $this->id : "") . ")";       // User 0 (all) + me (if defined)
406
        $resql = Config::$dbEngine->select($sql);
407
        if (is_array($resql)) {
408
            foreach ($resql as $array) {
409
                $obj = json_decode(json_encode($array));
410
411
                $pagewithoutquerystring = $obj->page;
412
                $pagequeries = '';
413
                if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param
414
                    $pagewithoutquerystring = $reg[1];
415
                    $pagequeries = $reg[2];
416
                }
417
                $this->default_values[$pagewithoutquerystring][$obj->type][$pagequeries ? $pagequeries : '_noquery_'][$obj->param] = $obj->value;
418
//if ($pagequeries) $this->default_values[$pagewithoutquerystring][$obj->type.'_queries']=$pagequeries;
419
            }
420
// Sort by key, so _noquery_ is last
421
            if (!empty($this->default_values)) {
422
                foreach ($this->default_values as $a => $b) {
423
                    foreach ($b as $c => $d) {
424
                        krsort($this->default_values[$a][$c]);
425
                    }
426
                }
427
            }
428
// Config::$dbEngine->free($resql);
429
430
            return 1;
431
        }
432
        DolUtils::dol_print_error(Config::$dbEngine);
433
        return -1;
434
    }
435
436
    /**
437
     *  Add a right to the user
438
     *
439
     * 	@param	int		$rid			Id of permission to add or 0 to add several permissions
440
     *  @param  string	$allmodule		Add all permissions of module $allmodule
441
     *  @param  string	$allperms		Add all permissions of module $allmodule, subperms $allperms only
442
     *  @param	int		$entity			Entity to use
443
     *  @param  int	    $notrigger		1=Does not execute triggers, 0=Execute triggers
444
     *  @return int						> 0 if OK, < 0 if KO
445
     *  @see	clearrights, delrights, getrights
446
     */
447
    function addrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
448
    {
449
//global $conf, Globals::$user, Globals::$langs;
450
451
        $entity = (!empty($entity) ? $entity : Globals::$conf->entity);
452
453
        DolUtils::dol_syslog(get_class($this) . "::addrights $rid, $allmodule, $allperms, $entity");
454
        $error = 0;
455
        $whereforadd = '';
456
457
        Config::$dbEngine->begin();
458
459
        if (!empty($rid)) {
460
// Si on a demande ajout d'un droit en particulier, on recupere
461
// les caracteristiques (module, perms et subperms) de ce droit.
462
            $sql = "SELECT module, perms, subperms";
463
            $sql .= " FROM " . MAIN_DB_PREFIX . "rights_def";
464
            $sql .= " WHERE id = '" . Config::$dbEngine->escape($rid) . "'";
465
            $sql .= " AND entity = " . $entity;
466
467
            $result = Config::$dbEngine->query($sql);
468
            if ($result) {
469
                $obj = Config::$dbEngine->fetch_object($result);
470
                $module = $obj->module;
471
                $perms = $obj->perms;
472
                $subperms = $obj->subperms;
473
            } else {
474
                $error++;
475
                dol_print_error(Config::$dbEngine);
476
            }
477
478
// Where pour la liste des droits a ajouter
479
            $whereforadd = "id=" . Config::$dbEngine->escape($rid);
480
// Ajout des droits induits
481
            if (!empty($subperms)) {
482
                $whereforadd .= " OR (module='$module' AND perms='$perms' AND (subperms='lire' OR subperms='read'))";
483
            } else {
484
                if (!empty($perms)) {
485
                    $whereforadd .= " OR (module='$module' AND (perms='lire' OR perms='read') AND subperms IS NULL)";
486
                }
487
            }
488
        } else {
489
// On a pas demande un droit en particulier mais une liste de droits
490
// sur la base d'un nom de module de de perms
491
// Where pour la liste des droits a ajouter
492
            if (!empty($allmodule)) {
493
                if ($allmodule == 'allmodules') {
494
                    $whereforadd = 'allmodules';
495
                } else {
496
                    $whereforadd = "module='" . Config::$dbEngine->escape($allmodule) . "'";
497
                    if (!empty($allperms)) {
498
                        $whereforadd .= " AND perms='" . Config::$dbEngine->escape($allperms) . "'";
499
                    }
500
                }
501
            }
502
        }
503
504
// Ajout des droits trouves grace au critere whereforadd
505
        if (!empty($whereforadd)) {
506
//print "$module-$perms-$subperms";
507
            $sql = "SELECT id";
508
            $sql .= " FROM " . MAIN_DB_PREFIX . "rights_def";
509
            $sql .= " WHERE entity = " . $entity;
510
            if (!empty($whereforadd) && $whereforadd != 'allmodules') {
511
                $sql .= " AND " . $whereforadd;
512
            }
513
514
            $result = Config::$dbEngine->query($sql);
515
            if ($result) {
516
                $num = Config::$dbEngine->num_rows($result);
517
                $i = 0;
518
                while ($i < $num) {
519
                    $obj = Config::$dbEngine->fetch_object($result);
520
                    $nid = $obj->id;
521
522
                    $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights WHERE fk_user = " . $this->id . " AND fk_id=" . $nid . " AND entity = " . $entity;
523
                    if (!Config::$dbEngine->query($sql))
524
                        $error++;
525
                    $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_rights (entity, fk_user, fk_id) VALUES (" . $entity . ", " . $this->id . ", " . $nid . ")";
526
                    if (!Config::$dbEngine->query($sql))
527
                        $error++;
528
529
                    $i++;
530
                }
531
            }
532
            else {
533
                $error++;
534
                dol_print_error(Config::$dbEngine);
535
            }
536
        }
537
538
        if (!$error && !$notrigger) {
539
            Globals::$langs->load("other");
540
            $this->context = array('audit' => Globals::$langs->trans("PermissionsAdd") . ($rid ? ' (id=' . $rid . ')' : ''));
541
542
// Call trigger
543
            $result = $this->call_trigger('USER_MODIFY', Globals::$user);
544
            if ($result < 0) {
545
                $error++;
546
            }
547
// End call triggers
548
        }
549
550
        if ($error) {
551
            Config::$dbEngine->rollback();
552
            return -$error;
553
        } else {
554
            Config::$dbEngine->commit();
555
            return 1;
556
        }
557
    }
558
559
    /**
560
     *  Remove a right to the user
561
     *
562
     *  @param	int		$rid        Id du droit a retirer
563
     *  @param  string	$allmodule  Retirer tous les droits du module allmodule
564
     *  @param  string	$allperms   Retirer tous les droits du module allmodule, perms allperms
565
     *  @param	int		$entity		Entity to use
566
     *  @param  int	    $notrigger	1=Does not execute triggers, 0=Execute triggers
567
     *  @return int         		> 0 if OK, < 0 if OK
568
     *  @see	clearrights, addrights, getrights
569
     */
570
    function delrights($rid, $allmodule = '', $allperms = '', $entity = 0, $notrigger = 0)
571
    {
572
//global $conf, Globals::$user, Globals::$langs;
573
574
        $error = 0;
575
        $wherefordel = '';
576
        $entity = (!empty($entity) ? $entity : Globals::$conf->entity);
577
578
        Config::$dbEngine->begin();
579
580
        if (!empty($rid)) {
581
// Si on a demande supression d'un droit en particulier, on recupere
582
// les caracteristiques module, perms et subperms de ce droit.
583
            $sql = "SELECT module, perms, subperms";
584
            $sql .= " FROM " . MAIN_DB_PREFIX . "rights_def";
585
            $sql .= " WHERE id = '" . Config::$dbEngine->escape($rid) . "'";
586
            $sql .= " AND entity = " . $entity;
587
588
            $result = Config::$dbEngine->query($sql);
589
            if ($result) {
590
                $obj = Config::$dbEngine->fetch_object($result);
591
                $module = $obj->module;
592
                $perms = $obj->perms;
593
                $subperms = $obj->subperms;
594
            } else {
595
                $error++;
596
                dol_print_error(Config::$dbEngine);
597
            }
598
599
// Where pour la liste des droits a supprimer
600
            $wherefordel = "id=" . Config::$dbEngine->escape($rid);
601
// Suppression des droits induits
602
            if ($subperms == 'lire' || $subperms == 'read') {
603
                $wherefordel .= " OR (module='$module' AND perms='$perms' AND subperms IS NOT NULL)";
604
            }
605
            if ($perms == 'lire' || $perms == 'read') {
606
                $wherefordel .= " OR (module='$module')";
607
            }
608
        } else {
609
// On a demande suppression d'un droit sur la base d'un nom de module ou perms
610
// Where pour la liste des droits a supprimer
611
            if (!empty($allmodule)) {
612
                if ($allmodule == 'allmodules') {
613
                    $wherefordel = 'allmodules';
614
                } else {
615
                    $wherefordel = "module='" . Config::$dbEngine->escape($allmodule) . "'";
616
                    if (!empty($allperms)) {
617
                        $whereforadd .= " AND perms='" . Config::$dbEngine->escape($allperms) . "'";
618
                    }
619
                }
620
            }
621
        }
622
623
// Suppression des droits selon critere defini dans wherefordel
624
        if (!empty($wherefordel)) {
625
//print "$module-$perms-$subperms";
626
            $sql = "SELECT id";
627
            $sql .= " FROM " . MAIN_DB_PREFIX . "rights_def";
628
            $sql .= " WHERE entity = " . $entity;
629
            if (!empty($wherefordel) && $wherefordel != 'allmodules') {
630
                $sql .= " AND " . $wherefordel;
631
            }
632
633
            $result = Config::$dbEngine->query($sql);
634
            if ($result) {
635
                $num = Config::$dbEngine->num_rows($result);
636
                $i = 0;
637
                while ($i < $num) {
638
                    $obj = Config::$dbEngine->fetch_object($result);
639
                    $nid = $obj->id;
640
641
                    $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights";
642
                    $sql .= " WHERE fk_user = " . $this->id . " AND fk_id=" . $nid;
643
                    $sql .= " AND entity = " . $entity;
644
                    if (!Config::$dbEngine->query($sql)) {
645
                        $error++;
646
                    }
647
648
                    $i++;
649
                }
650
            } else {
651
                $error++;
652
                dol_print_error(Config::$dbEngine);
653
            }
654
        }
655
656
        if (!$error && !$notrigger) {
657
            Globals::$langs->load("other");
658
            $this->context = array('audit' => Globals::$langs->trans("PermissionsDelete") . ($rid ? ' (id=' . $rid . ')' : ''));
659
660
// Call trigger
661
            $result = $this->call_trigger('USER_MODIFY', Globals::$user);
662
            if ($result < 0) {
663
                $error++;
664
            }
665
// End call triggers
666
        }
667
668
        if ($error) {
669
            Config::$dbEngine->rollback();
670
            return -$error;
671
        } else {
672
            Config::$dbEngine->commit();
673
            return 1;
674
        }
675
    }
676
677
    /**
678
     *  Clear all permissions array of user
679
     *
680
     *  @return	void
681
     *  @see	getrights
682
     */
683
    function clearrights()
684
    {
685
        DolUtils::dol_syslog(get_class($this) . "::clearrights reset user->rights");
686
        $this->rights = '';
687
        $this->all_permissions_are_loaded = false;
688
        $this->_tab_loaded = array();
689
    }
690
691
    /**
692
     * 	Load permissions granted to user into object user
693
     *
694
     * 	@param  string	$moduletag		Limit permission for a particular module ('' by default means load all permissions)
695
     *  @param	int		$forcereload	Force reload of permissions even if they were already loaded (ignore cache)
696
     * 	@return	void
697
     *  @see	clearrights, delrights, addrights
698
     */
699
    function getrights($moduletag = '', $forcereload = 0)
700
    {
701
        global $conf;
702
703
        if (empty($forcereload)) {
704
            if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
705
// Rights for this module are already loaded, so we leave
706
                return;
707
            }
708
709
            if ($this->all_permissions_are_loaded) {
710
// We already loaded all rights for this user, so we leave
711
                return;
712
            }
713
        }
714
715
// Recuperation des droits utilisateurs + recuperation des droits groupes
716
// D'abord les droits utilisateurs
717
        $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
718
        $sql .= " FROM " . MAIN_DB_PREFIX . "user_rights as ur";
719
        $sql .= ", " . MAIN_DB_PREFIX . "rights_def as r";
720
        $sql .= " WHERE r.id = ur.fk_id";
721
        if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
722
            $sql .= " AND r.entity IN (0," . (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) ? "1," : "") . Globals::$conf->entity . ")";
723
        } else {
724
            $sql .= " AND ur.entity = " . Globals::$conf->entity;
725
        }
726
        $sql .= " AND ur.fk_user= " . $this->id;
727
        $sql .= " AND r.perms IS NOT NULL";
728
        if ($moduletag) {
729
// $sql .= " AND r.module = '" . Config::$dbEngine->escape($moduletag) . "'";
730
            $sql .= " AND r.module = '" . $moduletag . "'";
731
        }
732
733
        $resql = Config::$dbEngine->select($sql);
734
        if (is_array($resql)) {
735
            foreach ($resql as $array) {
736
                $obj = json_decode(json_encode($array));
737
738
                $module = $obj->module;
739
                $perms = $obj->perms;
740
                $subperms = $obj->subperms;
741
742
                if ($perms) {
743
                    if (!isset($this->rights) || !is_object($this->rights)) {
744
                        $this->rights = new \stdClass(); // For avoid error
745
                    }
746
                    if ($module) {
747
                        if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
748
                            $this->rights->$module = new \stdClass();
749
                        }
750
                        if ($subperms) {
751
                            if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
752
                                $this->rights->$module->$perms = new \stdClass();
753
                            }
754
                            if (empty($this->rights->$module->$perms->$subperms)) {
755
                                $this->nb_rights++;
756
                            }
757
                            $this->rights->$module->$perms->$subperms = 1;
758
                        } else {
759
                            if (empty($this->rights->$module->$perms)) {
760
                                $this->nb_rights++;
761
                            }
762
                            $this->rights->$module->$perms = 1;
763
                        }
764
                    }
765
                }
766
            }
767
        }
768
769
// Maintenant les droits groupes
770
        $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
771
        $sql .= " FROM " . MAIN_DB_PREFIX . "usergroup_rights as gr,";
772
        $sql .= " " . MAIN_DB_PREFIX . "usergroup_user as gu,";
773
        $sql .= " " . MAIN_DB_PREFIX . "rights_def as r";
774
        $sql .= " WHERE r.id = gr.fk_id";
775
        if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
776
            if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
777
                $sql .= " AND gu.entity IN (0," . Globals::$conf->entity . ")";
778
            } else {
779
                $sql .= " AND r.entity = " . Globals::$conf->entity;
780
            }
781
        } else {
782
            $sql .= " AND gr.entity = " . Globals::$conf->entity;
783
            $sql .= " AND r.entity = " . Globals::$conf->entity;
784
        }
785
        $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
786
        $sql .= " AND gu.fk_user = " . $this->id;
787
        $sql .= " AND r.perms IS NOT NULL";
788
        if ($moduletag) {
789
            $sql .= " AND r.module = '" . $moduletag . "'";
790
        }
791
792
        $resql = Config::$dbEngine->select($sql);
793
        if (is_array($resql)) {
794
            foreach ($resql as $array) {
795
                $obj = json_decode(json_encode($array));
796
797
                $module = $obj->module;
798
                $perms = $obj->perms;
799
                $subperms = $obj->subperms;
800
801
                if ($perms) {
802
                    if (!isset($this->rights) || !is_object($this->rights)) {
803
                        $this->rights = new \stdClass(); // For avoid error
804
                    }
805
                    if (!isset($this->rights->$module) || !is_object($this->rights->$module)) {
806
                        $this->rights->$module = new \stdClass();
807
                    }
808
                    if ($subperms) {
809
                        if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) {
810
                            $this->rights->$module->$perms = new \stdClass();
811
                        }
812
                        if (empty($this->rights->$module->$perms->$subperms)) {
813
                            $this->nb_rights++;
814
                        }
815
                        $this->rights->$module->$perms->$subperms = 1;
816
                    } else {
817
                        if (empty($this->rights->$module->$perms)) {
818
                            $this->nb_rights++;
819
                        }
820
// 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
821
                        if (!is_object($this->rights->$module->$perms)) {
822
                            $this->rights->$module->$perms = 1;
823
                        }
824
                    }
825
                }
826
            }
827
        }
828
829
// For backward compatibility
830
        if (isset($this->rights->propale) && !isset($this->rights->propal)) {
831
            $this->rights->propal = $this->rights->propale;
832
        }
833
        if (isset($this->rights->propal) && !isset($this->rights->propale)) {
834
            $this->rights->propale = $this->rights->propal;
835
        }
836
837
        if (!$moduletag) {
838
// Si module etait non defini, alors on a tout charge, on peut donc considerer
839
// que les droits sont en cache (car tous charges) pour cet instance de user
840
            $this->all_permissions_are_loaded = 1;
841
        } else {
842
// Si module defini, on le marque comme charge en cache
843
            $this->_tab_loaded[$moduletag] = 1;
844
        }
845
    }
846
847
    /**
848
     *  Change status of a user
849
     *
850
     * 	@param	int		$statut		Status to set
851
     *  @return int     			<0 if KO, 0 if nothing is done, >0 if OK
852
     */
853
    function setstatus($statut)
854
    {
855
// global $conf, Globals::$langs, Globals::$user;
856
857
        $error = 0;
858
859
// Check parameters
860
        if ($this->statut == $statut) {
861
            return 0;
862
        } else {
863
            $this->statut = $statut;
864
        }
865
866
        Config::$dbEngine->begin();
867
868
// Deactivate user
869
        $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
870
        $sql .= " SET statut = " . $this->statut;
871
        $sql .= " WHERE rowid = " . $this->id;
872
        $result = Config::$dbEngine->query($sql);
873
874
        DolUtils::dol_syslog(get_class($this) . "::setstatus", LOG_DEBUG);
875
        if ($result) {
876
// Call trigger
877
            $result = $this->call_trigger('USER_ENABLEDISABLE', Globals::$user);
878
            if ($result < 0) {
879
                $error++;
880
            }
881
// End call triggers
882
        }
883
884
        if ($error) {
885
            Config::$dbEngine->rollback();
886
            return -$error;
887
        } else {
888
            Config::$dbEngine->commit();
889
            return 1;
890
        }
891
    }
892
893
    /**
894
     * Sets object to supplied categories.
895
     *
896
     * Deletes object from existing categories not supplied.
897
     * Adds it to non existing supplied categories.
898
     * Existing categories are left untouch.
899
     *
900
     * @param int[]|int $categories Category or categories IDs
901
     * @return void
902
     */
903
    public function setCategories($categories)
904
    {
905
// Handle single category
906
        if (!is_array($categories)) {
907
            $categories = array($categories);
908
        }
909
910
// Get current categories
911
        require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
912
        $c = new Categorie(Config::$dbEngine);
913
        $existing = $c->containing($this->id, Categorie::TYPE_USER, 'id');
914
915
// Diff
916
        if (is_array($existing)) {
917
            $to_del = array_diff($existing, $categories);
918
            $to_add = array_diff($categories, $existing);
919
        } else {
920
            $to_del = array(); // Nothing to delete
921
            $to_add = $categories;
922
        }
923
924
// Process
925
        foreach ($to_del as $del) {
926
            if ($c->fetch($del) > 0) {
927
                $c->del_type($this, 'user');
928
            }
929
        }
930
        foreach ($to_add as $add) {
931
            if ($c->fetch($add) > 0) {
932
                $c->add_type($this, 'user');
933
            }
934
        }
935
936
        return;
937
    }
938
939
    /**
940
     *    	Delete the user
941
     *
942
     * 		@return		int		<0 if KO, >0 if OK
943
     */
944
    function delete()
945
    {
946
//global Globals::$user, $conf, Globals::$langs;
947
948
        $error = 0;
949
950
        Config::$dbEngine->begin();
951
952
        $this->fetch($this->id);
953
954
        DolUtils::dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
955
956
// Remove rights
957
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights WHERE fk_user = " . $this->id;
958
959
        if (!$error && !Config::$dbEngine->query($sql)) {
960
            $error++;
961
            $this->error = Config::$dbEngine->lasterror();
962
        }
963
964
// Remove group
965
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user WHERE fk_user  = " . $this->id;
966
        if (!$error && !Config::$dbEngine->query($sql)) {
967
            $error++;
968
            $this->error = Config::$dbEngine->lasterror();
969
        }
970
971
// If contact, remove link
972
        if ($this->contact_id) {
973
            $sql = "UPDATE " . MAIN_DB_PREFIX . "socpeople SET fk_user_creat = null WHERE rowid = " . $this->contact_id;
974
            if (!$error && !Config::$dbEngine->query($sql)) {
975
                $error++;
976
                $this->error = Config::$dbEngine->lasterror();
977
            }
978
        }
979
980
// Remove extrafields
981
        if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) { // For avoid conflicts if trigger used
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
982
            $result = $this->deleteExtraFields();
983
            if ($result < 0) {
984
                $error++;
985
                DolUtils::dol_syslog(get_class($this) . "::delete error -4 " . $this->error, LOG_ERR);
986
            }
987
        }
988
989
// Remove user
990
        if (!$error) {
991
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user WHERE rowid = " . $this->id;
992
            DolUtils::dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
993
            if (!Config::$dbEngine->query($sql)) {
994
                $error++;
995
                $this->error = Config::$dbEngine->lasterror();
996
            }
997
        }
998
999
        if (!$error) {
1000
// Call trigger
1001
            $result = $this->call_trigger('USER_DELETE', Globals::$user);
1002
            if ($result < 0) {
1003
                $error++;
1004
                Config::$dbEngine->rollback();
1005
                return -1;
1006
            }
1007
// End call triggers
1008
1009
            Config::$dbEngine->commit();
1010
            return 1;
1011
        } else {
1012
            Config::$dbEngine->rollback();
1013
            return -1;
1014
        }
1015
    }
1016
1017
    /**
1018
     *  Create a user into database
1019
     *
1020
     *  @param	User	Globals::$user        	Objet user doing creation
1021
     *  @param  int		$notrigger		1=do not execute triggers, 0 otherwise
1022
     *  @return int			         	<0 if KO, id of created user if OK
1023
     */
1024
    function create($user, $notrigger = 0)
1025
    {
1026
//global $conf, Globals::$langs;
1027
//global $mysoc;
1028
// Clean parameters
1029
        $this->login = trim($this->login);
1030
        if (!isset($this->entity)) {
1031
            $this->entity = Globals::$conf->entity; // If not defined, we use default value
1032
        }
1033
        DolUtils::dol_syslog(get_class($this) . "::create login=" . $this->login . ", user=" . (is_object(Globals::$user) ? Globals::$user->id : ''), LOG_DEBUG);
1034
1035
// Check parameters
1036
        if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
1037
            Globals::$langs->load("errors");
1038
            $this->error = Globals::$langs->trans("ErrorBadEMail", $this->email);
1039
            return -1;
1040
        }
1041
        if (empty($this->login)) {
1042
            Globals::$langs->load("errors");
1043
            $this->error = Globals::$langs->trans("ErrorFieldRequired", Globals::$langs->transnoentitiesnoconv("Login"));
1044
            return -1;
1045
        }
1046
1047
        $this->datec = dol_now();
1048
1049
        $error = 0;
1050
        Config::$dbEngine->begin();
1051
1052
        $sql = "SELECT login FROM " . MAIN_DB_PREFIX . "user";
1053
        $sql .= " WHERE login ='" . Config::$dbEngine->escape($this->login) . "'";
1054
        $sql .= " AND entity IN (0," . Config::$dbEngine->escape($conf->entity) . ")";
1055
1056
        DolUtils::dol_syslog(get_class($this) . "::create", LOG_DEBUG);
1057
        $resql = Config::$dbEngine->query($sql);
1058
        if ($resql) {
1059
            $num = Config::$dbEngine->num_rows($resql);
1060
            Config::$dbEngine->free($resql);
0 ignored issues
show
The method free() does not exist on Alxarafe\Database\Engine. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1060
            Config::$dbEngine->/** @scrutinizer ignore-call */ free($resql);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1061
1062
            if ($num) {
1063
                $this->error = 'ErrorLoginAlreadyExists';
1064
                DolUtils::dol_syslog(get_class($this) . "::create " . $this->error, LOG_WARNING);
1065
                Config::$dbEngine->rollback();
1066
                return -6;
1067
            } else {
1068
                $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user (datec,login,ldap_sid,entity)";
1069
                $sql .= " VALUES('" . Config::$dbEngine->idate($this->datec) . "','" . Config::$dbEngine->escape($this->login) . "','" . Config::$dbEngine->escape($this->ldap_sid) . "'," . Config::$dbEngine->escape($this->entity) . ")";
1070
                $result = Config::$dbEngine->query($sql);
1071
1072
                DolUtils::dol_syslog(get_class($this) . "::create", LOG_DEBUG);
1073
                if ($result) {
1074
                    $this->id = Config::$dbEngine->last_insert_id(MAIN_DB_PREFIX . "user");
1075
1076
// Set default rights
1077
                    if ($this->set_default_rights() < 0) {
1078
                        $this->error = 'ErrorFailedToSetDefaultRightOfUser';
1079
                        Config::$dbEngine->rollback();
1080
                        return -5;
1081
                    }
1082
1083
// Update minor fields
1084
                    $result = $this->update(Globals::$user, 1, 1);
1085
                    if ($result < 0) {
1086
                        Config::$dbEngine->rollback();
1087
                        return -4;
1088
                    }
1089
1090
                    if (!empty($conf->global->STOCK_USERSTOCK_AUTOCREATE)) {
1091
                        require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
1092
                        Globals::$langs->load("stocks");
1093
                        $entrepot = new Entrepot(Config::$dbEngine);
1094
                        $entrepot->libelle = Globals::$langs->trans("PersonalStock", $this->getFullName(Globals::$langs));
1095
                        $entrepot->description = Globals::$langs->trans("ThisWarehouseIsPersonalStock", $this->getFullName(Globals::$langs));
1096
                        $entrepot->statut = 1;
1097
                        $entrepot->country_id = $mysoc->country_id;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $mysoc seems to be never defined.
Loading history...
1098
                        $entrepot->create(Globals::$user);
1099
                    }
1100
1101
                    if (!$notrigger) {
1102
// Call trigger
1103
                        $result = $this->call_trigger('USER_CREATE', Globals::$user);
1104
                        if ($result < 0) {
1105
                            $error++;
1106
                        }
1107
// End call triggers
1108
                    }
1109
1110
                    if (!$error) {
1111
                        Config::$dbEngine->commit();
1112
                        return $this->id;
1113
                    } else {
1114
//$this->error=$interface->error;
1115
                        DolUtils::dol_syslog(get_class($this) . "::create " . $this->error, LOG_ERR);
1116
                        Config::$dbEngine->rollback();
1117
                        return -3;
1118
                    }
1119
                } else {
1120
                    $this->error = Config::$dbEngine->lasterror();
1121
                    Config::$dbEngine->rollback();
1122
                    return -2;
1123
                }
1124
            }
1125
        } else {
1126
            $this->error = Config::$dbEngine->lasterror();
1127
            Config::$dbEngine->rollback();
1128
            return -1;
1129
        }
1130
    }
1131
1132
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1133
    /**
1134
     *  Create a user from a contact object. User will be internal but if contact is linked to a third party, user will be external
1135
     *
1136
     *  @param	Contact	$contact    Object for source contact
1137
     * 	@param  string	$login      Login to force
1138
     *  @param  string	$password   Password to force
1139
     *  @return int 				<0 if error, if OK returns id of created user
1140
     */
1141
    function create_from_contact($contact, $login = '', $password = '')
1142
    {
1143
// phpcs:enable
1144
//global $conf, Globals::$user, Globals::$langs;
1145
1146
        $error = 0;
1147
1148
// Define parameters
1149
        $this->admin = 0;
1150
        $this->lastname = $contact->lastname;
1151
        $this->firstname = $contact->firstname;
1152
        $this->gender = $contact->gender;
1153
        $this->email = $contact->email;
1154
        $this->skype = $contact->skype;
1155
        $this->twitter = $contact->twitter;
1156
        $this->facebook = $contact->facebook;
1157
        $this->office_phone = $contact->phone_pro;
1158
        $this->office_fax = $contact->fax;
1159
        $this->user_mobile = $contact->phone_mobile;
1160
        $this->address = $contact->address;
1161
        $this->zip = $contact->zip;
1162
        $this->town = $contact->town;
1163
        $this->state_id = $contact->state_id;
1164
        $this->country_id = $contact->country_id;
1165
        $this->employee = 0;
1166
1167
        if (empty($login)) {
1168
            $login = strtolower(substr($contact->firstname, 0, 4)) . strtolower(substr($contact->lastname, 0, 4));
1169
        }
1170
        $this->login = $login;
1171
1172
        Config::$dbEngine->begin();
1173
1174
// Cree et positionne $this->id
1175
        $result = $this->create(Globals::$user);
1176
        if ($result > 0) {
1177
            $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
1178
            $sql .= " SET fk_socpeople=" . $contact->id;
1179
            if ($contact->socid) {
1180
                $sql .= ", fk_soc=" . $contact->socid;
1181
            }
1182
            $sql .= " WHERE rowid=" . $this->id;
1183
            $resql = Config::$dbEngine->query($sql);
1184
1185
            DolUtils::dol_syslog(get_class($this) . "::create_from_contact", LOG_DEBUG);
1186
            if ($resql) {
1187
                $this->context['createfromcontact'] = 'createfromcontact';
1188
1189
// Call trigger
1190
                $result = $this->call_trigger('USER_CREATE', Globals::$user);
1191
                if ($result < 0) {
1192
                    $error++;
1193
                    Config::$dbEngine->rollback();
1194
                    return -1;
1195
                }
1196
// End call triggers
1197
1198
                Config::$dbEngine->commit();
1199
                return $this->id;
1200
            } else {
1201
                $this->error = Config::$dbEngine->error();
1202
1203
                Config::$dbEngine->rollback();
1204
                return -1;
1205
            }
1206
        } else {
1207
// $this->error deja positionne
1208
            DolUtils::dol_syslog(get_class($this) . "::create_from_contact - 0");
1209
1210
            Config::$dbEngine->rollback();
1211
            return $result;
1212
        }
1213
    }
1214
1215
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1216
    /**
1217
     *  Create a user into database from a member object
1218
     *
1219
     *  @param	Adherent	$member		Object member source
1220
     * 	@param	string		$login		Login to force
1221
     *  @return int						<0 if KO, if OK, return id of created account
1222
     */
1223
    function create_from_member($member, $login = '')
1224
    {
1225
// phpcs:enable
1226
// global $conf, Globals::$user, Globals::$langs;
1227
// Positionne parametres
1228
        $this->admin = 0;
1229
        $this->lastname = $member->lastname;
1230
        $this->firstname = $member->firstname;
1231
        $this->gender = $member->gender;
1232
        $this->email = $member->email;
1233
        $this->fk_member = $member->id;
1234
        $this->pass = $member->pass;
1235
        $this->address = $member->address;
1236
        $this->zip = $member->zip;
1237
        $this->town = $member->town;
1238
        $this->state_id = $member->state_id;
1239
        $this->country_id = $member->country_id;
1240
1241
        if (empty($login)) {
1242
            $login = strtolower(substr($member->firstname, 0, 4)) . strtolower(substr($member->lastname, 0, 4));
1243
        }
1244
        $this->login = $login;
1245
1246
        Config::$dbEngine->begin();
1247
1248
// Create and set $this->id
1249
        $result = $this->create(Globals::$user);
1250
        if ($result > 0) {
1251
            $newpass = $this->setPassword(Globals::$user, $this->pass);
1252
            if (is_numeric($newpass) && $newpass < 0) {
1253
                $result = -2;
1254
            }
1255
1256
            if ($result > 0 && $member->fk_soc) { // If member is linked to a thirdparty
1257
                $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
1258
                $sql .= " SET fk_soc=" . $member->fk_soc;
1259
                $sql .= " WHERE rowid=" . $this->id;
1260
1261
                DolUtils::dol_syslog(get_class($this) . "::create_from_member", LOG_DEBUG);
1262
                $resql = Config::$dbEngine->query($sql);
1263
                if ($resql) {
1264
                    Config::$dbEngine->commit();
1265
                    return $this->id;
1266
                } else {
1267
                    $this->error = Config::$dbEngine->lasterror();
1268
1269
                    Config::$dbEngine->rollback();
1270
                    return -1;
1271
                }
1272
            }
1273
        }
1274
1275
        if ($result > 0) {
1276
            Config::$dbEngine->commit();
1277
            return $this->id;
1278
        } else {
1279
// $this->error deja positionne
1280
            Config::$dbEngine->rollback();
1281
            return -2;
1282
        }
1283
    }
1284
1285
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1286
    /**
1287
     *    Assign rights by default
1288
     *
1289
     *    @return     integer erreur <0, si ok renvoi le nbre de droits par defaut positionnes
1290
     */
1291
    function set_default_rights()
1292
    {
1293
// phpcs:enable
1294
        global $conf;
1295
1296
        $sql = "SELECT id FROM " . MAIN_DB_PREFIX . "rights_def";
1297
        $sql .= " WHERE bydefault = 1";
1298
        $sql .= " AND entity = " . Globals::$conf->entity;
1299
1300
        $resql = Config::$dbEngine->query($sql);
1301
        if ($resql) {
1302
            $num = Config::$dbEngine->num_rows($resql);
1303
            $i = 0;
1304
            $rd = array();
1305
            while ($i < $num) {
1306
                $row = Config::$dbEngine->fetch_row($resql);
1307
                $rd[$i] = $row[0];
1308
                $i++;
1309
            }
1310
            Config::$dbEngine->free($resql);
1311
        }
1312
        $i = 0;
1313
        while ($i < $num) {
1314
1315
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
1316
            $result = Config::$dbEngine->query($sql);
1317
1318
            $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
1319
            $result = Config::$dbEngine->query($sql);
1320
            if (!$result) {
1321
                return -1;
1322
            }
1323
            $i++;
1324
        }
1325
1326
        return $i;
1327
    }
1328
1329
    /**
1330
     *  	Update a user into database (and also password if this->pass is defined)
1331
     *
1332
     * 		@param	User	Globals::$user				User qui fait la mise a jour
1333
     *    	@param  int		$notrigger			1 ne declenche pas les triggers, 0 sinon
1334
     * 		@param	int		$nosyncmember		0=Synchronize linked member (standard info), 1=Do not synchronize linked member
1335
     * 		@param	int		$nosyncmemberpass	0=Synchronize linked member (password), 1=Do not synchronize linked member
1336
     * 		@param	int		$nosynccontact		0=Synchronize linked contact, 1=Do not synchronize linked contact
1337
     *    	@return int 		        		<0 si KO, >=0 si OK
1338
     */
1339
    function update($user, $notrigger = 0, $nosyncmember = 0, $nosyncmemberpass = 0, $nosynccontact = 0)
1340
    {
1341
//global $conf, Globals::$langs;
1342
1343
        $nbrowsaffected = 0;
1344
        $error = 0;
1345
1346
        DolUtils::dol_syslog(get_class($this) . "::update notrigger=" . $notrigger . ", nosyncmember=" . $nosyncmember . ", nosyncmemberpass=" . $nosyncmemberpass);
1347
1348
// Clean parameters
1349
        $this->lastname = trim($this->lastname);
1350
        $this->firstname = trim($this->firstname);
1351
        $this->employee = $this->employee ? $this->employee : 0;
1352
        $this->login = trim($this->login);
1353
        $this->gender = trim($this->gender);
1354
        $this->birth = trim($this->birth);
1355
        $this->pass = trim($this->pass);
1356
        $this->api_key = trim($this->api_key);
1357
        $this->address = $this->address ? trim($this->address) : trim($this->address);
1358
        $this->zip = $this->zip ? trim($this->zip) : trim($this->zip);
1359
        $this->town = $this->town ? trim($this->town) : trim($this->town);
1360
        $this->state_id = trim($this->state_id);
1361
        $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1362
        $this->office_phone = trim($this->office_phone);
1363
        $this->office_fax = trim($this->office_fax);
1364
        $this->user_mobile = trim($this->user_mobile);
1365
        $this->email = trim($this->email);
1366
1367
        $this->skype = trim($this->skype);
1368
        $this->twitter = trim($this->twitter);
1369
        $this->facebook = trim($this->facebook);
1370
1371
        $this->job = trim($this->job);
1372
        $this->signature = trim($this->signature);
1373
        $this->note = trim($this->note);
1374
        $this->openid = trim(empty($this->openid) ? '' : $this->openid);    // Avoid warning
1375
        $this->admin = $this->admin ? $this->admin : 0;
1376
        $this->address = empty($this->address) ? '' : $this->address;
1377
        $this->zip = empty($this->zip) ? '' : $this->zip;
1378
        $this->town = empty($this->town) ? '' : $this->town;
1379
        $this->accountancy_code = trim($this->accountancy_code);
1380
        $this->color = empty($this->color) ? '' : $this->color;
1381
        $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment;
1382
        $this->dateemploymentend = empty($this->dateemploymentend) ? '' : $this->dateemploymentend;
1383
1384
// Check parameters
1385
        if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
1386
            Globals::$langs->load("errors");
1387
            $this->error = Globals::$langs->trans("ErrorBadEMail", $this->email);
1388
            return -1;
1389
        }
1390
        if (empty($this->login)) {
1391
            Globals::$langs->load("errors");
1392
            $this->error = Globals::$langs->trans("ErrorFieldRequired", $this->login);
1393
            return -1;
1394
        }
1395
1396
        Config::$dbEngine->begin();
1397
1398
// Update datas
1399
        $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET";
1400
        $sql .= " lastname = '" . Config::$dbEngine->escape($this->lastname) . "'";
1401
        $sql .= ", firstname = '" . Config::$dbEngine->escape($this->firstname) . "'";
1402
        $sql .= ", employee = " . $this->employee;
1403
        $sql .= ", login = '" . Config::$dbEngine->escape($this->login) . "'";
1404
        $sql .= ", api_key = " . ($this->api_key ? "'" . Config::$dbEngine->escape($this->api_key) . "'" : "null");
1405
        $sql .= ", gender = " . ($this->gender != -1 ? "'" . Config::$dbEngine->escape($this->gender) . "'" : "null"); // 'man' or 'woman'
1406
        $sql .= ", birth=" . (strval($this->birth) != '' ? "'" . Config::$dbEngine->idate($this->birth) . "'" : 'null');
1407
        if (!empty(Globals::$user->admin)) {
1408
            $sql .= ", admin = " . $this->admin; // admin flag can be set/unset only by an admin user
1409
        }
1410
        $sql .= ", address = '" . Config::$dbEngine->escape($this->address) . "'";
1411
        $sql .= ", zip = '" . Config::$dbEngine->escape($this->zip) . "'";
1412
        $sql .= ", town = '" . Config::$dbEngine->escape($this->town) . "'";
1413
        $sql .= ", fk_state = " . ((!empty($this->state_id) && $this->state_id > 0) ? "'" . Config::$dbEngine->escape($this->state_id) . "'" : "null");
1414
        $sql .= ", fk_country = " . ((!empty($this->country_id) && $this->country_id > 0) ? "'" . Config::$dbEngine->escape($this->country_id) . "'" : "null");
1415
        $sql .= ", office_phone = '" . Config::$dbEngine->escape($this->office_phone) . "'";
1416
        $sql .= ", office_fax = '" . Config::$dbEngine->escape($this->office_fax) . "'";
1417
        $sql .= ", user_mobile = '" . Config::$dbEngine->escape($this->user_mobile) . "'";
1418
        $sql .= ", email = '" . Config::$dbEngine->escape($this->email) . "'";
1419
        $sql .= ", skype = '" . Config::$dbEngine->escape($this->skype) . "'";
1420
        $sql .= ", twitter = '" . Config::$dbEngine->escape($this->twitter) . "'";
1421
        $sql .= ", facebook = '" . Config::$dbEngine->escape($this->facebook) . "'";
1422
        $sql .= ", job = '" . Config::$dbEngine->escape($this->job) . "'";
1423
        $sql .= ", signature = '" . Config::$dbEngine->escape($this->signature) . "'";
1424
        $sql .= ", accountancy_code = '" . Config::$dbEngine->escape($this->accountancy_code) . "'";
1425
        $sql .= ", color = '" . Config::$dbEngine->escape($this->color) . "'";
1426
        $sql .= ", dateemployment=" . (strval($this->dateemployment) != '' ? "'" . Config::$dbEngine->idate($this->dateemployment) . "'" : 'null');
1427
        $sql .= ", dateemploymentend=" . (strval($this->dateemploymentend) != '' ? "'" . Config::$dbEngine->idate($this->dateemploymentend) . "'" : 'null');
1428
        $sql .= ", note = '" . Config::$dbEngine->escape($this->note) . "'";
1429
        $sql .= ", photo = " . ($this->photo ? "'" . Config::$dbEngine->escape($this->photo) . "'" : "null");
1430
        $sql .= ", openid = " . ($this->openid ? "'" . Config::$dbEngine->escape($this->openid) . "'" : "null");
1431
        $sql .= ", fk_user = " . ($this->fk_user > 0 ? "'" . Config::$dbEngine->escape($this->fk_user) . "'" : "null");
1432
        if (isset($this->thm) || $this->thm != '') {
1433
            $sql .= ", thm= " . ($this->thm != '' ? "'" . Config::$dbEngine->escape($this->thm) . "'" : "null");
1434
        }
1435
        if (isset($this->tjm) || $this->tjm != '') {
1436
            $sql .= ", tjm= " . ($this->tjm != '' ? "'" . Config::$dbEngine->escape($this->tjm) . "'" : "null");
1437
        }
1438
        if (isset($this->salary) || $this->salary != '') {
1439
            $sql .= ", salary= " . ($this->salary != '' ? "'" . Config::$dbEngine->escape($this->salary) . "'" : "null");
1440
        }
1441
        if (isset($this->salaryextra) || $this->salaryextra != '') {
1442
            $sql .= ", salaryextra= " . ($this->salaryextra != '' ? "'" . Config::$dbEngine->escape($this->salaryextra) . "'" : "null");
1443
        }
1444
        $sql .= ", weeklyhours= " . ($this->weeklyhours != '' ? "'" . Config::$dbEngine->escape($this->weeklyhours) . "'" : "null");
1445
        $sql .= ", entity = '" . Config::$dbEngine->escape($this->entity) . "'";
1446
        $sql .= ", default_range = " . ($this->default_range > 0 ? $this->default_range : 'null');
1447
        $sql .= ", default_c_exp_tax_cat = " . ($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
1448
1449
        $sql .= " WHERE rowid = " . $this->id;
1450
1451
        DolUtils::dol_syslog(get_class($this) . "::update", LOG_DEBUG);
1452
        $resql = Config::$dbEngine->query($sql);
1453
        if ($resql) {
1454
            $nbrowsaffected += Config::$dbEngine->affected_rows($resql);
1455
1456
// Update password
1457
            if (!empty($this->pass)) {
1458
                if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted) {
1459
// Si mot de passe saisi et different de celui en base
1460
                    $result = $this->setPassword(Globals::$user, $this->pass, 0, $notrigger, $nosyncmemberpass);
1461
                    if (!$nbrowsaffected) {
1462
                        $nbrowsaffected++;
1463
                    }
1464
                }
1465
            }
1466
1467
// If user is linked to a member, remove old link to this member
1468
            if ($this->fk_member > 0) {
1469
                DolUtils::dol_syslog(get_class($this) . "::update remove link with member. We will recreate it later", LOG_DEBUG);
1470
                $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET fk_member = NULL where fk_member = " . $this->fk_member;
1471
                $resql = Config::$dbEngine->query($sql);
1472
                if (!$resql) {
1473
                    $this->error = Config::$dbEngine->error();
1474
                    Config::$dbEngine->rollback();
1475
                    return -5;
1476
                }
1477
            }
1478
// Set link to user
1479
            DolUtils::dol_syslog(get_class($this) . "::update set link with member", LOG_DEBUG);
1480
            $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET fk_member =" . ($this->fk_member > 0 ? $this->fk_member : 'null') . " where rowid = " . $this->id;
1481
            $resql = Config::$dbEngine->query($sql);
1482
            if (!$resql) {
1483
                $this->error = Config::$dbEngine->error();
1484
                Config::$dbEngine->rollback();
1485
                return -5;
1486
            }
1487
1488
            if ($nbrowsaffected) { // If something has changed in data
1489
                if ($this->fk_member > 0 && !$nosyncmember) {
1490
                    DolUtils::dol_syslog(get_class($this) . "::update user is linked with a member. We try to update member too.", LOG_DEBUG);
1491
1492
                    require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
1493
1494
// This user is linked with a member, so we also update member information
1495
// if this is an update.
1496
                    $adh = new Adherent(Config::$dbEngine);
1497
                    $result = $adh->fetch($this->fk_member);
1498
1499
                    if ($result >= 0) {
1500
                        $adh->firstname = $this->firstname;
1501
                        $adh->lastname = $this->lastname;
1502
                        $adh->login = $this->login;
1503
                        $adh->gender = $this->gender;
1504
                        $adh->birth = $this->birth;
1505
1506
                        $adh->pass = $this->pass;
1507
1508
                        $adh->societe = (empty($adh->societe) && $this->societe_id ? $this->societe_id : $adh->societe);
1509
1510
                        $adh->address = $this->address;
1511
                        $adh->town = $this->town;
1512
                        $adh->zip = $this->zip;
1513
                        $adh->state_id = $this->state_id;
1514
                        $adh->country_id = $this->country_id;
1515
1516
                        $adh->email = $this->email;
1517
1518
                        $adh->skype = $this->skype;
1519
                        $adh->twitter = $this->twitter;
1520
                        $adh->facebook = $this->facebook;
1521
1522
                        $adh->phone = $this->office_phone;
1523
                        $adh->phone_mobile = $this->user_mobile;
1524
1525
                        $adh->user_id = $this->id;
1526
                        $adh->user_login = $this->login;
1527
1528
                        $result = $adh->update(Globals::$user, 0, 1, 0);
1529
                        if ($result < 0) {
1530
                            $this->error = $adh->error;
1531
                            $this->errors = $adh->errors;
1532
                            DolUtils::dol_syslog(get_class($this) . "::update error after calling adh->update to sync it with user: " . $this->error, LOG_ERR);
1533
                            $error++;
1534
                        }
1535
                    } else {
1536
                        $this->error = $adh->error;
1537
                        $this->errors = $adh->errors;
1538
                        $error++;
1539
                    }
1540
                }
1541
1542
                if ($this->contact_id > 0 && !$nosynccontact) {
1543
                    DolUtils::dol_syslog(get_class($this) . "::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
1544
1545
                    require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
1546
1547
// This user is linked with a contact, so we also update contact information
1548
// if this is an update.
1549
                    $tmpobj = new Contact(Config::$dbEngine);
1550
                    $result = $tmpobj->fetch($this->contact_id);
1551
1552
                    if ($result >= 0) {
1553
                        $tmpobj->firstname = $this->firstname;
1554
                        $tmpobj->lastname = $this->lastname;
1555
                        $tmpobj->login = $this->login;
1556
                        $tmpobj->gender = $this->gender;
1557
                        $tmpobj->birth = $this->birth;
1558
1559
//$tmpobj->pass=$this->pass;
1560
//$tmpobj->societe=(empty($tmpobj->societe) && $this->societe_id ? $this->societe_id : $tmpobj->societe);
1561
1562
                        $tmpobj->email = $this->email;
1563
1564
                        $tmpobj->skype = $this->skype;
1565
                        $tmpobj->twitter = $this->twitter;
1566
                        $tmpobj->facebook = $this->facebook;
1567
1568
                        $tmpobj->phone_pro = $this->office_phone;
1569
                        $tmpobj->phone_mobile = $this->user_mobile;
1570
                        $tmpobj->fax = $this->office_fax;
1571
1572
                        $tmpobj->address = $this->address;
1573
                        $tmpobj->town = $this->town;
1574
                        $tmpobj->zip = $this->zip;
1575
                        $tmpobj->state_id = $this->state_id;
1576
                        $tmpobj->country_id = $this->country_id;
1577
1578
                        $tmpobj->user_id = $this->id;
1579
                        $tmpobj->user_login = $this->login;
1580
1581
                        $result = $tmpobj->update($tmpobj->id, Globals::$user, 0, 'update', 1);
1582
                        if ($result < 0) {
1583
                            $this->error = $tmpobj->error;
1584
                            $this->errors = $tmpobj->errors;
1585
                            DolUtils::dol_syslog(get_class($this) . "::update error after calling adh->update to sync it with user: " . $this->error, LOG_ERR);
1586
                            $error++;
1587
                        }
1588
                    } else {
1589
                        $this->error = $tmpobj->error;
1590
                        $this->errors = $tmpobj->errors;
1591
                        $error++;
1592
                    }
1593
                }
1594
            }
1595
1596
            $action = 'update';
1597
1598
// Actions on extra fields
1599
            if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
1600
                $result = $this->insertExtraFields();
1601
                if ($result < 0) {
1602
                    $error++;
1603
                }
1604
            }
1605
1606
            if (!$error && !$notrigger) {
1607
// Call trigger
1608
                $result = $this->call_trigger('USER_MODIFY', Globals::$user);
1609
                if ($result < 0) {
1610
                    $error++;
1611
                }
1612
// End call triggers
1613
            }
1614
1615
            if (!$error) {
1616
                Config::$dbEngine->commit();
1617
                return $nbrowsaffected;
1618
            } else {
1619
                DolUtils::dol_syslog(get_class($this) . "::update error=" . $this->error, LOG_ERR);
1620
                Config::$dbEngine->rollback();
1621
                return -1;
1622
            }
1623
        } else {
1624
            $this->error = Config::$dbEngine->lasterror();
1625
            Config::$dbEngine->rollback();
1626
            return -2;
1627
        }
1628
    }
1629
1630
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1631
    /**
1632
     *    Mise a jour en base de la date de derniere connexion d'un utilisateur
1633
     * 	  Fonction appelee lors d'une nouvelle connexion
1634
     *
1635
     *    @return     <0 si echec, >=0 si ok
1636
     */
1637
    function update_last_login_date()
1638
    {
1639
// phpcs:enable
1640
        $now = dol_now();
1641
1642
        $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET";
1643
        $sql .= " datepreviouslogin = datelastlogin,";
1644
        $sql .= " datelastlogin = '" . Config::$dbEngine->idate($now) . "',";
1645
        $sql .= " tms = tms";    // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
1646
        $sql .= " WHERE rowid = " . $this->id;
1647
1648
        DolUtils::dol_syslog(get_class($this) . "::update_last_login_date user->id=" . $this->id . " " . $sql, LOG_DEBUG);
1649
        $resql = Config::$dbEngine->query($sql);
1650
        if ($resql) {
1651
            $this->datepreviouslogin = $this->datelastlogin;
1652
            $this->datelastlogin = $now;
1653
            return 1;
1654
        } else {
1655
            $this->error = Config::$dbEngine->lasterror() . ' sql=' . $sql;
1656
            return -1;
1657
        }
1658
    }
1659
1660
    /**
1661
     *  Change password of a user
1662
     *
1663
     *  @param	User	Globals::$user             		Object user of user making change
1664
     *  @param  string	$password         		New password in clear text (to generate if not provided)
1665
     * 	@param	int		$changelater			1=Change password only after clicking on confirm email
1666
     * 	@param	int		$notrigger				1=Does not launch triggers
1667
     * 	@param	int		$nosyncmember	        Do not synchronize linked member
1668
     *  @return string 			          		If OK return clear password, 0 if no change, < 0 if error
1669
     */
1670
    function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0)
1671
    {
1672
//global $conf, Globals::$langs;
1673
        require_once DOL_DOCUMENT_ROOT . '/core/lib/security2.lib.php';
1674
1675
        $error = 0;
1676
1677
        DolUtils::dol_syslog(get_class($this) . "::setPassword user=" . Globals::$user->id . " password=" . preg_replace('/./i', '*', $password) . " changelater=" . $changelater . " notrigger=" . $notrigger . " nosyncmember=" . $nosyncmember, LOG_DEBUG);
1678
1679
// If new password not provided, we generate one
1680
        if (!$password) {
1681
            $password = getRandomPassword(false);
1682
        }
1683
1684
// Crypt password
1685
        $password_crypted = dol_hash($password);
1686
1687
// Mise a jour
1688
        if (!$changelater) {
1689
            if (!is_object($this->oldcopy)) {
1690
                $this->oldcopy = clone $this;
1691
            }
1692
1693
            Config::$dbEngine->begin();
1694
1695
            $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
1696
            $sql .= " SET pass_crypted = '" . Config::$dbEngine->escape($password_crypted) . "',";
1697
            $sql .= " pass_temp = null";
1698
            if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
1699
                $sql .= ", pass = null";
1700
            } else {
1701
                $sql .= ", pass = '" . Config::$dbEngine->escape($password) . "'";
1702
            }
1703
            $sql .= " WHERE rowid = " . $this->id;
1704
1705
            DolUtils::dol_syslog(get_class($this) . "::setPassword", LOG_DEBUG);
1706
            $result = Config::$dbEngine->query($sql);
1707
            if ($result) {
1708
                if (Config::$dbEngine->affected_rows($result)) {
1709
                    $this->pass = $password;
1710
                    $this->pass_indatabase = $password;
1711
                    $this->pass_indatabase_crypted = $password_crypted;
1712
1713
                    if ($this->fk_member && !$nosyncmember) {
1714
                        require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
1715
1716
// This user is linked with a member, so we also update members informations
1717
// if this is an update.
1718
                        $adh = new Adherent(Config::$dbEngine);
1719
                        $result = $adh->fetch($this->fk_member);
1720
1721
                        if ($result >= 0) {
1722
                            $result = $adh->setPassword(Globals::$user, $this->pass, (empty($conf->global->DATABASE_PWD_ENCRYPTED) ? 0 : 1), 1); // Cryptage non gere dans module adherent
1723
                            if ($result < 0) {
1724
                                $this->error = $adh->error;
1725
                                DolUtils::dol_syslog(get_class($this) . "::setPassword " . $this->error, LOG_ERR);
1726
                                $error++;
1727
                            }
1728
                        } else {
1729
                            $this->error = $adh->error;
1730
                            $error++;
1731
                        }
1732
                    }
1733
1734
                    DolUtils::dol_syslog(get_class($this) . "::setPassword notrigger=" . $notrigger . " error=" . $error, LOG_DEBUG);
1735
1736
                    if (!$error && !$notrigger) {
1737
// Call trigger
1738
                        $result = $this->call_trigger('USER_NEW_PASSWORD', Globals::$user);
1739
                        if ($result < 0) {
1740
                            $error++;
1741
                            Config::$dbEngine->rollback();
1742
                            return -1;
1743
                        }
1744
// End call triggers
1745
                    }
1746
1747
                    Config::$dbEngine->commit();
1748
                    return $this->pass;
1749
                } else {
1750
                    Config::$dbEngine->rollback();
1751
                    return 0;
1752
                }
1753
            } else {
1754
                Config::$dbEngine->rollback();
1755
                dol_print_error(Config::$dbEngine);
1756
                return -1;
1757
            }
1758
        } else {
1759
// We store clear password in password temporary field.
1760
// After receiving confirmation link, we will crypt it and store it in pass_crypted
1761
            $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
1762
            $sql .= " SET pass_temp = '" . Config::$dbEngine->escape($password) . "'";
1763
            $sql .= " WHERE rowid = " . $this->id;
1764
1765
            DolUtils::dol_syslog(get_class($this) . "::setPassword", LOG_DEBUG); // No log
1766
            $result = Config::$dbEngine->query($sql);
1767
            if ($result) {
1768
                return $password;
1769
            } else {
1770
                dol_print_error(Config::$dbEngine);
1771
                return -3;
1772
            }
1773
        }
1774
    }
1775
1776
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1777
    /**
1778
     *  Send new password by email
1779
     *
1780
     *  @param	User	Globals::$user           Object user that send email
1781
     *  @param	string	$password       New password
1782
     * 	@param	int		$changelater	0=Send clear passwod into email, 1=Change password only after clicking on confirm email. @TODO Add method 2 = Send link to reset password
1783
     *  @return int 		            < 0 si erreur, > 0 si ok
1784
     */
1785
    function send_password($user, $password = '', $changelater = 0)
1786
    {
1787
// phpcs:enable
1788
//global $conf, Globals::$langs;
1789
//global $dolibarr_main_url_root;
1790
1791
        require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
1792
1793
        $msgishtml = 0;
1794
1795
// Define $msg
1796
        $mesg = '';
1797
1798
        $outputlangs = new Translate("", $conf);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
1799
        if (isset($this->conf->MAIN_LANG_DEFAULT) && $this->conf->MAIN_LANG_DEFAULT != 'auto') { // If user has defined its own language (rare because in most cases, auto is used)
1800
            $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
1801
        } else { // If user has not defined its own language, we used current language
1802
            $outputlangs = Globals::$langs;
1803
        }
1804
1805
// Load translation files required by the page
1806
        $outputlangs->loadLangs(array("main", "errors", "users", "other"));
1807
1808
        $appli = constant('DOL_APPLICATION_TITLE');
1809
        if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
1810
            $appli = Globals::$conf->global->MAIN_APPLICATION_TITLE;
1811
        }
1812
1813
        $subject = $outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
1814
1815
// Define $urlwithroot
1816
        $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($dolibarr_main_url_root));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dolibarr_main_url_root seems to be never defined.
Loading history...
1817
        $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT;  // This is to use external domain name found into config file
1818
1819
        if (!$changelater) {
1820
            $url = $urlwithroot . '/';
1821
1822
            $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived") . ".\n";
1823
            $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs") . " :\n\n";
1824
            $mesg .= $outputlangs->transnoentitiesnoconv("Login") . " = " . $this->login . "\n";
1825
            $mesg .= $outputlangs->transnoentitiesnoconv("Password") . " = " . $password . "\n\n";
1826
            $mesg .= "\n";
1827
1828
            $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli) . ': ' . $url . "\n\n";
1829
            $mesg .= "--\n";
1830
            $mesg .= Globals::$user->getFullName($outputlangs); // Username that make then sending
1831
1832
            DolUtils::dol_syslog(get_class($this) . "::send_password changelater is off, url=" . $url);
1833
        } else {
1834
            $url = $urlwithroot . '/user/passwordforgotten.php?action=validatenewpassword&username=' . $this->login . "&passwordhash=" . dol_hash($password);
1835
1836
            $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived") . "\n";
1837
            $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe") . " :\n\n";
1838
            $mesg .= $outputlangs->transnoentitiesnoconv("Login") . " = " . $this->login . "\n";
1839
            $mesg .= $outputlangs->transnoentitiesnoconv("Password") . " = " . $password . "\n\n";
1840
            $mesg .= "\n";
1841
            $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange") . " :\n";
1842
            $mesg .= $url . "\n\n";
1843
            $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing") . "\n\n";
1844
1845
            DolUtils::dol_syslog(get_class($this) . "::send_password changelater is on, url=" . $url);
1846
        }
1847
1848
        $mailfile = new CMailFile(
1849
            $subject, $this->email, Globals::$conf->global->MAIN_MAIL_EMAIL_FROM, $mesg, array(), array(), array(), '', '', 0, $msgishtml
1850
        );
1851
1852
        if ($mailfile->sendfile()) {
1853
            return 1;
1854
        } else {
1855
            Globals::$langs->trans("errors");
1856
            $this->error = Globals::$langs->trans("ErrorFailedToSendPassword") . ' ' . $mailfile->error;
1857
            return -1;
1858
        }
1859
    }
1860
1861
    /**
1862
     * 		Renvoie la derniere erreur fonctionnelle de manipulation de l'objet
1863
     *
1864
     * 		@return    string      chaine erreur
1865
     */
1866
    function error()
1867
    {
1868
        return $this->error;
1869
    }
1870
1871
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1872
    /**
1873
     *    	Read clicktodial information for user
1874
     *
1875
     * 		@return		<0 if KO, >0 if OK
1876
     */
1877
    function fetch_clicktodial()
1878
    {
1879
// phpcs:enable
1880
        $sql = "SELECT url, login, pass, poste ";
1881
        $sql .= " FROM " . MAIN_DB_PREFIX . "user_clicktodial as u";
1882
        $sql .= " WHERE u.fk_user = " . $this->id;
1883
1884
        $resql = Config::$dbEngine->query($sql);
1885
        if ($resql) {
1886
            if (Config::$dbEngine->num_rows($resql)) {
1887
                $obj = Config::$dbEngine->fetch_object($resql);
1888
1889
                $this->clicktodial_url = $obj->url;
1890
                $this->clicktodial_login = $obj->login;
1891
                $this->clicktodial_password = $obj->pass;
1892
                $this->clicktodial_poste = $obj->poste;
1893
            }
1894
1895
            $this->clicktodial_loaded = 1; // Data loaded (found or not)
1896
1897
            Config::$dbEngine->free($resql);
1898
            return 1;
1899
        } else {
1900
            $this->error = Config::$dbEngine->error();
1901
            return -1;
1902
        }
1903
    }
1904
1905
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1906
    /**
1907
     *  Update clicktodial info
1908
     *
1909
     *  @return	integer
1910
     */
1911
    function update_clicktodial()
1912
    {
1913
// phpcs:enable
1914
        Config::$dbEngine->begin();
1915
1916
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_clicktodial";
1917
        $sql .= " WHERE fk_user = " . $this->id;
1918
1919
        DolUtils::dol_syslog(get_class($this) . '::update_clicktodial', LOG_DEBUG);
1920
        $result = Config::$dbEngine->query($sql);
1921
1922
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_clicktodial";
1923
        $sql .= " (fk_user,url,login,pass,poste)";
1924
        $sql .= " VALUES (" . $this->id;
1925
        $sql .= ", '" . Config::$dbEngine->escape($this->clicktodial_url) . "'";
1926
        $sql .= ", '" . Config::$dbEngine->escape($this->clicktodial_login) . "'";
1927
        $sql .= ", '" . Config::$dbEngine->escape($this->clicktodial_password) . "'";
1928
        $sql .= ", '" . Config::$dbEngine->escape($this->clicktodial_poste) . "')";
1929
1930
        DolUtils::dol_syslog(get_class($this) . '::update_clicktodial', LOG_DEBUG);
1931
        $result = Config::$dbEngine->query($sql);
1932
        if ($result) {
1933
            Config::$dbEngine->commit();
1934
            return 1;
1935
        } else {
1936
            Config::$dbEngine->rollback();
1937
            $this->error = Config::$dbEngine->lasterror();
1938
            return -1;
1939
        }
1940
    }
1941
1942
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1943
    /**
1944
     *  Add user into a group
1945
     *
1946
     *  @param	int	$group      Id of group
1947
     *  @param  int		$entity     Entity
1948
     *  @param  int		$notrigger  Disable triggers
1949
     *  @return int  				<0 if KO, >0 if OK
1950
     */
1951
    function SetInGroup($group, $entity, $notrigger = 0)
1952
    {
1953
// phpcs:enable
1954
//global $conf, Globals::$langs, Globals::$user;
1955
1956
        $error = 0;
1957
1958
        Config::$dbEngine->begin();
1959
1960
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user";
1961
        $sql .= " WHERE fk_user  = " . $this->id;
1962
        $sql .= " AND fk_usergroup = " . $group;
1963
        $sql .= " AND entity = " . $entity;
1964
1965
        $result = Config::$dbEngine->query($sql);
1966
1967
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "usergroup_user (entity, fk_user, fk_usergroup)";
1968
        $sql .= " VALUES (" . $entity . "," . $this->id . "," . $group . ")";
1969
1970
        $result = Config::$dbEngine->query($sql);
1971
        if ($result) {
1972
            if (!$error && !$notrigger) {
1973
                $this->newgroupid = $group;    // deprecated. Remove this.
1974
                $this->context = array('audit' => Globals::$langs->trans("UserSetInGroup"), 'newgroupid' => $group);
1975
1976
// Call trigger
1977
                $result = $this->call_trigger('USER_MODIFY', Globals::$user);
1978
                if ($result < 0) {
1979
                    $error++;
1980
                }
1981
// End call triggers
1982
            }
1983
1984
            if (!$error) {
1985
                Config::$dbEngine->commit();
1986
                return 1;
1987
            } else {
1988
                DolUtils::dol_syslog(get_class($this) . "::SetInGroup " . $this->error, LOG_ERR);
1989
                Config::$dbEngine->rollback();
1990
                return -2;
1991
            }
1992
        } else {
1993
            $this->error = Config::$dbEngine->lasterror();
1994
            Config::$dbEngine->rollback();
1995
            return -1;
1996
        }
1997
    }
1998
1999
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2000
    /**
2001
     *  Remove a user from a group
2002
     *
2003
     *  @param	int   $group       Id of group
2004
     *  @param  int		$entity      Entity
2005
     *  @param  int		$notrigger   Disable triggers
2006
     *  @return int  			     <0 if KO, >0 if OK
2007
     */
2008
    function RemoveFromGroup($group, $entity, $notrigger = 0)
2009
    {
2010
// phpcs:enable
2011
//global $conf, Globals::$langs, Globals::$user;
2012
2013
        $error = 0;
2014
2015
        Config::$dbEngine->begin();
2016
2017
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user";
2018
        $sql .= " WHERE fk_user  = " . $this->id;
2019
        $sql .= " AND fk_usergroup = " . $group;
2020
        $sql .= " AND entity = " . $entity;
2021
2022
        $result = Config::$dbEngine->query($sql);
2023
        if ($result) {
2024
            if (!$error && !$notrigger) {
2025
                $this->oldgroupid = $group;    // deprecated. Remove this.
2026
                $this->context = array('audit' => Globals::$langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
2027
2028
// Call trigger
2029
                $result = $this->call_trigger('USER_MODIFY', Globals::$user);
2030
                if ($result < 0) {
2031
                    $error++;
2032
                }
2033
// End call triggers
2034
            }
2035
2036
            if (!$error) {
2037
                Config::$dbEngine->commit();
2038
                return 1;
2039
            } else {
2040
                $this->error = $interface->error;
2041
                DolUtils::dol_syslog(get_class($this) . "::RemoveFromGroup " . $this->error, LOG_ERR);
2042
                Config::$dbEngine->rollback();
2043
                return -2;
2044
            }
2045
        } else {
2046
            $this->error = Config::$dbEngine->lasterror();
2047
            Config::$dbEngine->rollback();
2048
            return -1;
2049
        }
2050
    }
2051
2052
    /**
2053
     *  Return a link with photo
2054
     * 	Use this->id,this->photo
2055
     *
2056
     * 	@param	int		$width			Width of image
2057
     * 	@param	int		$height			Height of image
2058
     *  @param	string	$cssclass		Force a css class
2059
     * 	@param	string	$imagesize		'mini', 'small' or '' (original)
2060
     * 	@return	string					String with URL link
2061
     */
2062
    function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
2063
    {
2064
// $result = '<a href="' . DOL_URL_ROOT . '/user/card.php?id=' . $this->id . '">';
2065
        $result = '<a href="' . BASE_URI . '?controller=user&method=card&id=' . $this->id . '">';
2066
        $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
2067
        $result .= '</a>';
2068
2069
        return $result;
2070
    }
2071
2072
    /**
2073
     *  Return a link to the user card (with optionaly the picto)
2074
     * 	Use this->id,this->lastname, this->firstname
2075
     *
2076
     * 	@param	int		$withpictoimg				Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto, -1=Include photo into link, -2=Only picto photo, -3=Only photo very small)
2077
     * 	@param	string	$option						On what the link point to ('leave', 'nolink', )
2078
     *  @param  integer $infologin      			0=Add default info tooltip, 1=Add complete info tooltip, -1=No info tooltip
2079
     *  @param	integer	$notooltip					1=Disable tooltip on picto and name
2080
     *  @param	int		$maxlen						Max length of visible user name
2081
     *  @param	int		$hidethirdpartylogo			Hide logo of thirdparty if user is external user
2082
     *  @param  string  $mode               		''=Show firstname and lastname, 'firstname'=Show only firstname, 'login'=Show login
2083
     *  @param  string  $morecss            		Add more css on link
2084
     *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
2085
     * 	@return	string								String with URL
2086
     */
2087
    function getNomUrl($withpictoimg = 0, $option = '', $infologin = 0, $notooltip = 0, $maxlen = 24, $hidethirdpartylogo = 0, $mode = '', $morecss = '', $save_lastsearch_value = -1)
2088
    {
2089
//global Globals::$langs, $conf, $db, $hookmanager, Globals::$user;
2090
//global $dolibarr_main_authentication, $dolibarr_main_demo;
2091
//global $menumanager;
2092
2093
        if (!Globals::$user->rights->user->user->lire && Globals::$user->id != $this->id) {
2094
            $option = 'nolink';
2095
        }
2096
2097
        if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
2098
            $withpictoimg = 0;
2099
        }
2100
2101
        $result = '';
2102
        $label = '';
2103
        $link = '';
2104
        $linkstart = '';
2105
        $linkend = '';
2106
2107
        if (!empty($this->photo)) {
2108
            $label .= '<div class="photointooltip">';
2109
            $label .= Form::showphoto('userphoto', $this, 0, 60, 0, 'photowithmargin photologintooltip', 'small', 0, 1); // Force height to 60 so we total height of tooltip can be calculated and collision can be managed
2110
            $label .= '</div><div style="clear: both;"></div>';
2111
        }
2112
2113
// Info Login
2114
        $label .= '<div class="centpercent">';
2115
        $label .= '<u>' . Globals::$langs->trans("User") . '</u><br>';
2116
        $label .= '<b>' . Globals::$langs->trans('Name') . ':</b> ' . $this->getFullName(Globals::$langs, '');
2117
        if (!empty($this->login)) {
2118
            $label .= '<br><b>' . Globals::$langs->trans('Login') . ':</b> ' . $this->login;
2119
        }
2120
        $label .= '<br><b>' . Globals::$langs->trans("EMail") . ':</b> ' . $this->email;
2121
        if (!empty($this->admin)) {
2122
            $label .= '<br><b>' . Globals::$langs->trans("Administrator") . '</b>: ' . DolUtils::yn($this->admin);
2123
        }
2124
        if (!empty($this->socid)) { // Add thirdparty for external users
2125
            $thirdpartystatic = new Societe($db);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $db seems to be never defined.
Loading history...
2126
            $thirdpartystatic->fetch($this->socid);
2127
            if (empty($hidethirdpartylogo)) {
2128
                $companylink = ' ' . $thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2129
            }
2130
            $company = ' (' . Globals::$langs->trans("Company") . ': ' . $thirdpartystatic->name . ')';
2131
        }
2132
        $type = ($this->socid ? Globals::$langs->trans("External") . $company : Globals::$langs->trans("Internal"));
2133
        $label .= '<br><b>' . Globals::$langs->trans("Type") . ':</b> ' . $type;
2134
        $label .= '<br><b>' . Globals::$langs->trans("Status") . '</b>: ' . $this->getLibStatut(0);
2135
        $label .= '</div>';
2136
        if ($infologin > 0) {
2137
            $label .= '<br>';
2138
            $label .= '<br><u>' . Globals::$langs->trans("Connection") . '</u>';
2139
            $label .= '<br><b>' . Globals::$langs->trans("IPAddress") . '</b>: ' . $_SERVER["REMOTE_ADDR"];
2140
            if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) {
2141
                $label .= '<br><b>' . Globals::$langs->trans("ConnectedOnMultiCompany") . ':</b> ' . Globals::$conf->entity . ' (user entity ' . $this->entity . ')';
2142
            }
2143
            $label .= '<br><b>' . Globals::$langs->trans("AuthenticationMode") . ':</b> ' . $_SESSION["dol_authmode"] . (empty($dolibarr_main_demo) ? '' : ' (demo)');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dolibarr_main_demo seems to never exist and therefore empty should always be true.
Loading history...
2144
            $label .= '<br><b>' . Globals::$langs->trans("ConnectedSince") . ':</b> ' . dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
2145
            $label .= '<br><b>' . Globals::$langs->trans("PreviousConnexion") . ':</b> ' . dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
2146
            $label .= '<br><b>' . Globals::$langs->trans("CurrentTheme") . ':</b> ' . Globals::$conf->theme;
2147
            $label .= '<br><b>' . Globals::$langs->trans("CurrentMenuManager") . ':</b> ' . $menumanager->name;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $menumanager seems to be never defined.
Loading history...
2148
            $s = picto_from_langcode(Globals::$langs->getDefaultLang());
2149
            $label .= '<br><b>' . Globals::$langs->trans("CurrentUserLanguage") . ':</b> ' . ($s ? $s . ' ' : '') . Globals::$langs->getDefaultLang();
2150
            $label .= '<br><b>' . Globals::$langs->trans("Browser") . ':</b> ' . Globals::$conf->browser->name . ($conf->browser->version ? ' ' . Globals::$conf->browser->version : '') . ' (' . $_SERVER['HTTP_USER_AGENT'] . ')';
2151
            $label .= '<br><b>' . Globals::$langs->trans("Layout") . ':</b> ' . Globals::$conf->browser->layout;
2152
            $label .= '<br><b>' . Globals::$langs->trans("Screen") . ':</b> ' . $_SESSION['dol_screenwidth'] . ' x ' . $_SESSION['dol_screenheight'];
2153
            if ($conf->browser->layout == 'phone') {
2154
                $label .= '<br><b>' . Globals::$langs->trans("Phone") . ':</b> ' . Globals::$langs->trans("Yes");
2155
            }
2156
            if (!empty($_SESSION["disablemodules"])) {
2157
                $label .= '<br><b>' . Globals::$langs->trans("DisabledModules") . ':</b> <br>' . join(', ', explode(',', $_SESSION["disablemodules"]));
2158
            }
2159
        }
2160
        if ($infologin < 0) {
2161
            $label = '';
2162
        }
2163
2164
// $url = DOL_URL_ROOT . '/user/card.php?id=' . $this->id;
2165
        $url = BASE_URI . '?controller=user&method=card&id=' . $this->id;
2166
        if ($option == 'leave') {
2167
//$url = DOL_URL_ROOT . '/holiday/list.php?id=' . $this->id;
2168
            $url = BASE_URI . '?controller=holiday&method=list&id=' . $this->id;
2169
        }
2170
        if ($option != 'nolink') {
2171
// Add param to save lastsearch_values or not
2172
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2173
            if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2174
                $add_save_lastsearch_values = 1;
2175
            }
2176
            if ($add_save_lastsearch_values) {
2177
                $url .= '&save_lastsearch_values=1';
2178
            }
2179
        }
2180
2181
        $linkstart = '<a href="' . $url . '"';
2182
        $linkclose = "";
2183
        if (empty($notooltip)) {
2184
            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2185
                Globals::$langs->load("users");
2186
                $label = Globals::$langs->trans("ShowUser");
2187
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
2188
            }
2189
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
2190
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
2191
2192
            /*
2193
              $hookmanager->initHooks(array('userdao'));
2194
              $parameters=array('id'=>$this->id);
2195
              $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
2196
              if ($reshook > 0) $linkclose = $hookmanager->resPrint;
2197
             */
2198
        }
2199
2200
        $linkstart .= $linkclose . '>';
2201
        $linkend = '</a>';
2202
2203
//if ($withpictoimg == -1) $result.='<div class="nowrap">';
2204
        $result .= (($option == 'nolink') ? '' : $linkstart);
2205
        if ($withpictoimg) {
2206
            $paddafterimage = '';
2207
            if (abs($withpictoimg) == 1) {
2208
                $paddafterimage = 'style="margin-right: 3px;"';
2209
            }
2210
// Only picto
2211
            if ($withpictoimg > 0) {
2212
                $picto = '<!-- picto user --><div class="inline-block nopadding userimg' . ($morecss ? ' ' . $morecss : '') . '">' . img_object('', 'user', $paddafterimage . ' ' . ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1) . '</div>';
2213
            } else { // Picto must be a photo
2214
                $picto = '<!-- picto photo user --><div class="inline-block nopadding userimg' . ($morecss ? ' ' . $morecss : '') . '"' . ($paddafterimage ? ' ' . $paddafterimage : '') . '>' . Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto' . ($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1) . '</div>';
2215
            }
2216
            $result .= $picto;
2217
        }
2218
        if ($withpictoimg > -2 && $withpictoimg != 2) {
2219
            if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2220
                $result .= '<div class="inline-block nopadding valignmiddle usertext' . ((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled') . ($morecss ? ' ' . $morecss : '') . '">';
2221
            }
2222
            if ($mode == 'login') {
2223
                $result .= dol_trunc($this->login, $maxlen);
2224
            } else {
2225
                $result .= $this->getFullName(Globals::$langs, '', ($mode == 'firstname' ? 2 : -1), $maxlen);
2226
            }
2227
            if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
2228
                $result .= '</div>';
2229
        }
2230
        $result .= (($option == 'nolink') ? '' : $linkend);
2231
//if ($withpictoimg == -1) $result.='</div>';
2232
2233
        $result .= $companylink;
2234
2235
        global $action;
2236
        $hookmanager->initHooks(array('userdao'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $hookmanager seems to be never defined.
Loading history...
2237
        $parameters = array('id' => $this->id, 'getnomurl' => $result);
2238
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
2239
        if ($reshook > 0) {
2240
            $result = $hookmanager->resPrint;
2241
        } else {
2242
            $result .= $hookmanager->resPrint;
2243
        }
2244
2245
        return $result;
2246
    }
2247
2248
    /**
2249
     *  Return clickable link of login (eventualy with picto)
2250
     *
2251
     * 	@param	int		$withpicto		Include picto into link
2252
     * 	@param	string	$option			Sur quoi pointe le lien
2253
     * 	@return	string					Chaine avec URL
2254
     */
2255
    function getLoginUrl($withpicto = 0, $option = '')
2256
    {
2257
        //global Globals::$langs, Globals::$user;
2258
2259
        $result = '';
2260
2261
// $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2262
        $linkstart = '<a href="' . BASE_URI . '?controller=user&method=card&id=' . $this->id . '">';
2263
        $linkend = '</a>';
2264
2265
//Check user's rights to see an other user
2266
        if ((!Globals::$user->rights->user->user->lire && $this->id != Globals::$user->id)) {
2267
            $option = 'nolink';
2268
        }
2269
2270
        if ($option == 'xxx') {
2271
//$linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2272
            $linkstart = '<a href="' . BASE_URI . '?controller=user&method=card.php&id=' . $this->id . '">';
2273
            $linkend = '</a>';
2274
        }
2275
2276
        if ($option == 'nolink') {
2277
            $linkstart = '';
2278
            $linkend = '';
2279
        }
2280
2281
        $result .= $linkstart;
2282
        if ($withpicto) {
2283
            $result .= img_object(Globals::$langs->trans("ShowUser"), 'user', 'class="paddingright"');
2284
        }
2285
        $result .= $this->login;
2286
        $result .= $linkend;
2287
        return $result;
2288
    }
2289
2290
    /**
2291
     *  Return label of status of user (active, inactive)
2292
     *
2293
     *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2294
     *  @return	string 			       Label of status
2295
     */
2296
    function getLibStatut($mode = 0)
2297
    {
2298
        return $this->LibStatut($this->statut, $mode);
2299
    }
2300
2301
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2302
    /**
2303
     *  Renvoi le libelle d'un statut donne
2304
     *
2305
     *  @param	int		$statut        	Id statut
2306
     *  @param  int		$mode          	0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2307
     *  @return string 			       	Label of status
2308
     */
2309
    function LibStatut($statut, $mode = 0)
2310
    {
2311
// phpcs:enable
2312
        //global Globals::$langs;
2313
        Globals::$langs->load('users');
2314
2315
        if ($mode == 0) {
2316
            if ($statut == 1) {
2317
                return Globals::$langs->trans('Enabled');
2318
            } elseif ($statut == 0) {
2319
                return Globals::$langs->trans('Disabled');
2320
            }
2321
        } elseif ($mode == 1) {
2322
            if ($statut == 1) {
2323
                return Globals::$langs->trans('Enabled');
2324
            } elseif ($statut == 0) {
2325
                return Globals::$langs->trans('Disabled');
2326
            }
2327
        } elseif ($mode == 2) {
2328
            if ($statut == 1) {
2329
                return img_picto(Globals::$langs->trans('Enabled'), 'statut4', 'class="pictostatus"') . ' ' . Globals::$langs->trans('Enabled');
2330
            } elseif ($statut == 0) {
2331
                return img_picto(Globals::$langs->trans('Disabled'), 'statut5', 'class="pictostatus"') . ' ' . Globals::$langs->trans('Disabled');
2332
            }
2333
        } elseif ($mode == 3) {
2334
            if ($statut == 1) {
2335
                return img_picto(Globals::$langs->trans('Enabled'), 'statut4', 'class="pictostatus"');
2336
            } elseif ($statut == 0) {
2337
                return img_picto(Globals::$langs->trans('Disabled'), 'statut5', 'class="pictostatus"');
2338
            }
2339
        } elseif ($mode == 4) {
2340
            if ($statut == 1) {
2341
                return img_picto(Globals::$langs->trans('Enabled'), 'statut4', 'class="pictostatus"') . ' ' . Globals::$langs->trans('Enabled');
2342
            } elseif ($statut == 0) {
2343
                return img_picto(Globals::$langs->trans('Disabled'), 'statut5', 'class="pictostatus"') . ' ' . Globals::$langs->trans('Disabled');
2344
            }
2345
        } elseif ($mode == 5) {
2346
            if ($statut == 1) {
2347
                return Globals::$langs->trans('Enabled') . ' ' . img_picto(Globals::$langs->trans('Enabled'), 'statut4', 'class="pictostatus"');
2348
            } elseif ($statut == 0) {
2349
                return Globals::$langs->trans('Disabled') . ' ' . img_picto(Globals::$langs->trans('Disabled'), 'statut5', 'class="pictostatus"');
2350
            }
2351
        }
2352
    }
2353
2354
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2355
    /**
2356
     * 	Retourne chaine DN complete dans l'annuaire LDAP pour l'objet
2357
     *
2358
     * 	@param	array	$info		Info array loaded by _load_ldap_info
2359
     * 	@param	int		$mode		0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb)
2360
     * 								1=Return parent (ou=xxx,dc=aaa,dc=bbb)
2361
     * 								2=Return key only (RDN) (uid=qqq)
2362
     * 	@return	string				DN
2363
     */
2364
    function _load_ldap_dn($info, $mode = 0)
2365
    {
2366
// phpcs:enable
2367
        global $conf;
2368
        $dn = '';
2369
        if ($mode == 0) {
2370
            $dn = Globals::$conf->global->LDAP_KEY_USERS . "=" . $info[$conf->global->LDAP_KEY_USERS] . "," . Globals::$conf->global->LDAP_USER_DN;
2371
        } elseif ($mode == 1) {
2372
            $dn = Globals::$conf->global->LDAP_USER_DN;
2373
        } elseif ($mode == 2) {
2374
            $dn = Globals::$conf->global->LDAP_KEY_USERS . "=" . $info[$conf->global->LDAP_KEY_USERS];
2375
        }
2376
        return $dn;
2377
    }
2378
2379
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2380
    /**
2381
     * 	Initialize the info array (array of LDAP values) that will be used to call LDAP functions
2382
     *
2383
     * 	@return		array		Tableau info des attributs
2384
     */
2385
    function _load_ldap_info()
2386
    {
2387
// phpcs:enable
2388
        //global $conf, Globals::$langs;
2389
2390
        $info = array();
2391
        $keymodified = false;
2392
2393
// Object classes
2394
        $info["objectclass"] = explode(',', Globals::$conf->global->LDAP_USER_OBJECT_CLASS);
2395
2396
        $this->fullname = $this->getFullName(Globals::$langs);
2397
2398
// Possible LDAP KEY (constname => varname)
2399
        $ldapkey = array(
2400
            'LDAP_FIELD_FULLNAME' => 'fullname',
2401
            'LDAP_FIELD_NAME' => 'lastname',
2402
            'LDAP_FIELD_FIRSTNAME' => 'firstname',
2403
            'LDAP_FIELD_LOGIN' => 'login',
2404
            'LDAP_FIELD_LOGIN_SAMBA' => 'login',
2405
            'LDAP_FIELD_PHONE' => 'office_phone',
2406
            'LDAP_FIELD_MOBILE' => 'user_mobile',
2407
            'LDAP_FIELD_FAX' => 'office_fax',
2408
            'LDAP_FIELD_MAIL' => 'email',
2409
            'LDAP_FIELD_SID' => 'ldap_sid',
2410
            'LDAP_FIELD_SKYPE' => 'skype',
2411
            'LDAP_FIELD_TWITTER' => 'twitter',
2412
            'LDAP_FIELD_FACEBOOK' => 'facebook'
2413
        );
2414
2415
// Champs
2416
        foreach ($ldapkey as $constname => $varname) {
2417
            if (!empty($this->$varname) && !empty($conf->global->$constname)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
2418
                $info[$conf->global->$constname] = $this->$varname;
2419
2420
// Check if it is the LDAP key and if its value has been changed
2421
                if (!empty($conf->global->LDAP_KEY_USERS) && Globals::$conf->global->LDAP_KEY_USERS == Globals::$conf->global->$constname) {
2422
                    if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
2423
                        $keymodified = true; // For check if LDAP key has been modified
2424
                    }
2425
                }
2426
            }
2427
        }
2428
        if ($this->address && !empty($conf->global->LDAP_FIELD_ADDRESS)) {
2429
            $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address;
2430
        }
2431
        if ($this->zip && !empty($conf->global->LDAP_FIELD_ZIP)) {
2432
            $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip;
2433
        }
2434
        if ($this->town && !empty($conf->global->LDAP_FIELD_TOWN)) {
2435
            $info[$conf->global->LDAP_FIELD_TOWN] = $this->town;
2436
        }
2437
        if ($this->note_public && !empty($conf->global->LDAP_FIELD_DESCRIPTION)) {
2438
            $info[$conf->global->LDAP_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_public, 2);
2439
        }
2440
        if ($this->socid > 0) {
2441
            $soc = new Societe(Config::$dbEngine);
2442
            $soc->fetch($this->socid);
2443
2444
            $info[$conf->global->LDAP_FIELD_COMPANY] = $soc->name;
2445
            if ($soc->client == 1) {
2446
                $info["businessCategory"] = "Customers";
2447
            }
2448
            if ($soc->client == 2) {
2449
                $info["businessCategory"] = "Prospects";
2450
            }
2451
            if ($soc->fournisseur == 1) {
2452
                $info["businessCategory"] = "Suppliers";
2453
            }
2454
        }
2455
2456
// When password is modified
2457
        if (!empty($this->pass)) {
2458
            if (!empty($conf->global->LDAP_FIELD_PASSWORD)) {
2459
                $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte
2460
            }
2461
            if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
2462
                $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption)
2463
            }
2464
        }
2465
// Set LDAP password if possible
2466
        elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') { // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
2467
            if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
2468
// Just for the default MD5 !
2469
                if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) {
2470
                    if ($this->pass_indatabase_crypted && !empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
2471
                        $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase_crypted, 5); // Create OpenLDAP MD5 password from Dolibarr MD5 password
2472
                    }
2473
                }
2474
            }
2475
// Use $this->pass_indatabase value if exists
2476
            elseif (!empty($this->pass_indatabase)) {
2477
                if (!empty($conf->global->LDAP_FIELD_PASSWORD)) {
2478
                    $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte
2479
                }
2480
                if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) {
2481
                    $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption
2482
                }
2483
            }
2484
        }
2485
2486
        if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') {
2487
            $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
2488
2489
            $info['uidnumber'] = $this->id;
2490
2491
            $info['phpgwTz'] = 0;
2492
            $info['phpgwMailType'] = 'INTERNET';
2493
            $info['phpgwMailHomeType'] = 'INTERNET';
2494
2495
            $info["phpgwContactTypeId"] = 'n';
2496
            $info["phpgwContactCatId"] = 0;
2497
            $info["phpgwContactAccess"] = "public";
2498
2499
            if (dol_strlen($this->egroupware_id) == 0) {
2500
                $this->egroupware_id = 1;
2501
            }
2502
2503
            $info["phpgwContactOwner"] = $this->egroupware_id;
2504
2505
            if ($this->email) {
2506
                $info["rfc822Mailbox"] = $this->email;
2507
            }
2508
            if ($this->phone_mobile) {
2509
                $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
2510
            }
2511
        }
2512
2513
        return $info;
2514
    }
2515
2516
    /**
2517
     *  Initialise an instance with random values.
2518
     *  Used to build previews or test instances.
2519
     * 	id must be 0 if object instance is a specimen.
2520
     *
2521
     *  @return	void
2522
     */
2523
    function initAsSpecimen()
2524
    {
2525
        // global Globals::$user, Globals::$langs;
2526
2527
        $now = dol_now();
2528
2529
// Initialise parametres
2530
        $this->id = 0;
2531
        $this->ref = 'SPECIMEN';
2532
        $this->specimen = 1;
2533
2534
        $this->lastname = 'DOLIBARR';
2535
        $this->firstname = 'SPECIMEN';
2536
        $this->gender = 'man';
2537
        $this->note = 'This is a note';
2538
        $this->email = '[email protected]';
2539
        $this->skype = 'skypepseudo';
2540
        $this->twitter = 'twitterpseudo';
2541
        $this->facebook = 'facebookpseudo';
2542
        $this->office_phone = '0999999999';
2543
        $this->office_fax = '0999999998';
2544
        $this->user_mobile = '0999999997';
2545
        $this->admin = 0;
2546
        $this->login = 'dolibspec';
2547
        $this->pass = 'dolibspec';
2548
//$this->pass_indatabase='dolibspec';									Set after a fetch
2549
//$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab';	Set after a fetch
2550
        $this->datec = $now;
2551
        $this->datem = $now;
2552
2553
        $this->datelastlogin = $now;
2554
        $this->datepreviouslogin = $now;
2555
        $this->statut = 1;
2556
2557
//$this->societe_id = 1;	For external users
2558
//$this->contact_id = 1;	For external users
2559
        $this->entity = 1;
2560
    }
2561
2562
    /**
2563
     *  Load info of user object
2564
     *
2565
     *  @param  int		$id     Id of user to load
2566
     *  @return	void
2567
     */
2568
    function info($id)
2569
    {
2570
        $sql = "SELECT u.rowid, u.login as ref, u.datec,";
2571
        $sql .= " u.tms as date_modification, u.entity";
2572
        $sql .= " FROM " . MAIN_DB_PREFIX . "user as u";
2573
        $sql .= " WHERE u.rowid = " . $id;
2574
2575
        $result = Config::$dbEngine->query($sql);
2576
        if ($result) {
2577
            if (Config::$dbEngine->num_rows($result)) {
2578
                $obj = Config::$dbEngine->fetch_object($result);
2579
2580
                $this->id = $obj->rowid;
2581
2582
                $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2583
                $this->date_creation = Config::$dbEngine->jdate($obj->datec);
2584
                $this->date_modification = Config::$dbEngine->jdate($obj->date_modification);
2585
                $this->entity = $obj->entity;
2586
            }
2587
2588
            Config::$dbEngine->free($result);
2589
        } else {
2590
            dol_print_error(Config::$dbEngine);
2591
        }
2592
    }
2593
2594
    /**
2595
     *    Return number of mass Emailing received by this contacts with its email
2596
     *
2597
     *    @return       int     Number of EMailings
2598
     */
2599
    function getNbOfEMailings()
2600
    {
2601
        $sql = "SELECT count(mc.email) as nb";
2602
        $sql .= " FROM " . MAIN_DB_PREFIX . "mailing_cibles as mc";
2603
        $sql .= " WHERE mc.email = '" . Config::$dbEngine->escape($this->email) . "'";
2604
        $sql .= " AND mc.statut NOT IN (-1,0)";      // -1 erreur, 0 non envoye, 1 envoye avec succes
2605
2606
        $resql = Config::$dbEngine->query($sql);
2607
        if ($resql) {
2608
            $obj = Config::$dbEngine->fetch_object($resql);
2609
            $nb = $obj->nb;
2610
2611
            Config::$dbEngine->free($resql);
2612
            return $nb;
2613
        } else {
2614
            $this->error = Config::$dbEngine->error();
2615
            return -1;
2616
        }
2617
    }
2618
2619
    /**
2620
     *  Return number of existing users
2621
     *
2622
     *  @param	string	$limitTo	Limit to '' or 'active'
2623
     *  @param	string	$option		'superadmin' = return for entity 0 only
2624
     *  @param	int		$admin		Filter on admin tag
2625
     *  @return int  				Number of users
2626
     */
2627
    function getNbOfUsers($limitTo, $option = '', $admin = -1)
2628
    {
2629
        global $conf;
2630
2631
        $sql = "SELECT count(rowid) as nb";
2632
        $sql .= " FROM " . MAIN_DB_PREFIX . "user";
2633
        if ($option == 'superadmin') {
2634
            $sql .= " WHERE entity = 0";
2635
            if ($admin >= 0) {
2636
                $sql .= " AND admin = " . $admin;
2637
            }
2638
        } else {
2639
            $sql .= " WHERE entity IN (" . getEntity('user', 0) . ")";
2640
            if ($limitTo == 'active') {
2641
                $sql .= " AND statut = 1";
2642
            }
2643
            if ($admin >= 0) {
2644
                $sql .= " AND admin = " . $admin;
2645
            }
2646
        }
2647
2648
        $resql = Config::$dbEngine->query($sql);
2649
        if ($resql) {
2650
            $obj = Config::$dbEngine->fetch_object($resql);
2651
            $nb = $obj->nb;
2652
2653
            Config::$dbEngine->free($resql);
2654
            return $nb;
2655
        } else {
2656
            $this->error = Config::$dbEngine->lasterror();
2657
            return -1;
2658
        }
2659
    }
2660
2661
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2662
    /**
2663
     *  Update user using data from the LDAP
2664
     *
2665
     *  @param	ldapuser	$ldapuser	Ladp User
2666
     *
2667
     *  @return int  				<0 if KO, >0 if OK
2668
     */
2669
    function update_ldap2dolibarr(&$ldapuser)
2670
    {
2671
// phpcs:enable
2672
// TODO: Voir pourquoi le update met à jour avec toutes les valeurs vide (global Globals::$user écrase ?)
2673
        //global Globals::$user, $conf;
2674
2675
        $this->firstname = $ldapuser->{$conf->global->LDAP_FIELD_FIRSTNAME};
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
2676
        $this->lastname = $ldapuser->{$conf->global->LDAP_FIELD_NAME};
2677
        $this->login = $ldapuser->{$conf->global->LDAP_FIELD_LOGIN};
2678
        $this->pass = $ldapuser->{$conf->global->LDAP_FIELD_PASSWORD};
2679
        $this->pass_indatabase_crypted = $ldapuser->{$conf->global->LDAP_FIELD_PASSWORD_CRYPTED};
2680
2681
        $this->office_phone = $ldapuser->{$conf->global->LDAP_FIELD_PHONE};
2682
        $this->user_mobile = $ldapuser->{$conf->global->LDAP_FIELD_MOBILE};
2683
        $this->office_fax = $ldapuser->{$conf->global->LDAP_FIELD_FAX};
2684
        $this->email = $ldapuser->{$conf->global->LDAP_FIELD_MAIL};
2685
        $this->skype = $ldapuser->{$conf->global->LDAP_FIELD_SKYPE};
2686
        $this->twitter = $ldapuser->{$conf->global->LDAP_FIELD_TWITTER};
2687
        $this->facebook = $ldapuser->{$conf->global->LDAP_FIELD_FACEBOOK};
2688
        $this->ldap_sid = $ldapuser->{$conf->global->LDAP_FIELD_SID};
2689
2690
        $this->job = $ldapuser->{$conf->global->LDAP_FIELD_TITLE};
2691
        $this->note = $ldapuser->{$conf->global->LDAP_FIELD_DESCRIPTION};
2692
2693
        $result = $this->update(Globals::$user);
2694
2695
        DolUtils::dol_syslog(get_class($this) . "::update_ldap2dolibarr result=" . $result, LOG_DEBUG);
2696
2697
        return $result;
2698
    }
2699
2700
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2701
    /**
2702
     * Return and array with all instanciated first level children users of current user
2703
     *
2704
     * @return	void
2705
     * @see getAllChildIds
2706
     */
2707
    function get_children()
2708
    {
2709
// phpcs:enable
2710
        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "user";
2711
        $sql .= " WHERE fk_user = " . $this->id;
2712
2713
        DolUtils::dol_syslog(get_class($this) . "::get_children result=" . $result, LOG_DEBUG);
2714
        $res = Config::$dbEngine->query($sql);
2715
        if ($res) {
2716
            $this->users = array();
2717
            while ($rec = Config::$dbEngine->fetch_array($res)) {
2718
                Globals::$user = new User(Config::$dbEngine);
2719
                Globals::$user->fetch($rec['rowid']);
2720
                $this->users[] = Globals::$user;
2721
            }
2722
            return $this->users;
2723
        } else {
2724
            dol_print_error(Config::$dbEngine);
2725
            return -1;
2726
        }
2727
    }
2728
2729
    /**
2730
     * 	Load this->parentof that is array(id_son=>id_parent, ...)
2731
     *
2732
     * 	@return		int		<0 if KO, >0 if OK
2733
     */
2734
    private function loadParentOf()
2735
    {
2736
        global $conf;
2737
2738
        $this->parentof = array();
2739
2740
// Load array[child]=parent
2741
        $sql = "SELECT fk_user as id_parent, rowid as id_son";
2742
        $sql .= " FROM " . MAIN_DB_PREFIX . "user";
2743
        $sql .= " WHERE fk_user <> 0";
2744
        $sql .= " AND entity IN (" . getEntity('user') . ")";
2745
2746
        DolUtils::dol_syslog(get_class($this) . "::loadParentOf", LOG_DEBUG);
2747
        $resql = Config::$dbEngine->query($sql);
2748
        if ($resql) {
2749
            while ($obj = Config::$dbEngine->fetch_object($resql)) {
2750
                $this->parentof[$obj->id_son] = $obj->id_parent;
2751
            }
2752
            return 1;
2753
        } else {
2754
            dol_print_error(Config::$dbEngine);
2755
            return -1;
2756
        }
2757
    }
2758
2759
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2760
    /**
2761
     * 	Reconstruit l'arborescence hierarchique des users sous la forme d'un tableau
2762
     * 	Set and return this->users that is an array sorted according to tree with arrays of:
2763
     * 				id = id user
2764
     * 				lastname
2765
     * 				firstname
2766
     * 				fullname = nom avec chemin complet du user
2767
     * 				fullpath = chemin complet compose des id: "_grandparentid_parentid_id"
2768
     *
2769
     *  @param      int		$deleteafterid      Removed all users including the leaf $deleteafterid (and all its child) in user tree.
2770
     *  @param		string	$filter				SQL filter on users
2771
     * 	@return		array		      		  	Array of users $this->users. Note: $this->parentof is also set.
2772
     */
2773
    function get_full_tree($deleteafterid = 0, $filter = '')
2774
    {
2775
// phpcs:enable
2776
        //global $conf, Globals::$user;
2777
        //global $hookmanager;
2778
// Actions hooked (by external module)
2779
        $hookmanager->initHooks(array('userdao'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $hookmanager seems to be never defined.
Loading history...
2780
2781
        $this->users = array();
2782
2783
// Init this->parentof that is array(id_son=>id_parent, ...)
2784
        $this->loadParentOf();
2785
2786
// Init $this->users array
2787
        $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
2788
        $sql .= " FROM " . MAIN_DB_PREFIX . "user as u";
2789
// Add fields from hooks
2790
        $parameters = array();
2791
        $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters);    // Note that $action and $object may have been modified by hook
2792
        if ($reshook > 0) {
2793
            $sql .= $hookmanager->resPrint;
2794
        } else {
2795
            $sql .= " WHERE u.entity IN (" . getEntity('user') . ")";
2796
        }
2797
        if ($filter) {
2798
            $sql .= " AND " . $filter;
2799
        }
2800
2801
        DolUtils::dol_syslog(get_class($this) . "::get_full_tree get user list", LOG_DEBUG);
2802
        $resql = Config::$dbEngine->query($sql);
2803
        if ($resql) {
2804
            $i = 0;
2805
            while ($obj = Config::$dbEngine->fetch_object($resql)) {
2806
                $this->users[$obj->rowid]['rowid'] = $obj->rowid;
2807
                $this->users[$obj->rowid]['id'] = $obj->rowid;
2808
                $this->users[$obj->rowid]['fk_user'] = $obj->fk_user;
2809
                $this->users[$obj->rowid]['fk_soc'] = $obj->fk_soc;
2810
                $this->users[$obj->rowid]['firstname'] = $obj->firstname;
2811
                $this->users[$obj->rowid]['lastname'] = $obj->lastname;
2812
                $this->users[$obj->rowid]['login'] = $obj->login;
2813
                $this->users[$obj->rowid]['statut'] = $obj->statut;
2814
                $this->users[$obj->rowid]['entity'] = $obj->entity;
2815
                $this->users[$obj->rowid]['email'] = $obj->email;
2816
                $this->users[$obj->rowid]['gender'] = $obj->gender;
2817
                $this->users[$obj->rowid]['admin'] = $obj->admin;
2818
                $this->users[$obj->rowid]['photo'] = $obj->photo;
2819
                $i++;
2820
            }
2821
        } else {
2822
            dol_print_error(Config::$dbEngine);
2823
            return -1;
2824
        }
2825
2826
// We add the fullpath property to each elements of first level (no parent exists)
2827
        DolUtils::dol_syslog(get_class($this) . "::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
2828
        foreach ($this->users as $key => $val) {
2829
            $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
2830
            if ($result < 0) {
2831
                $this->error = 'ErrorLoopInHierarchy';
2832
                return -1;
2833
            }
2834
        }
2835
2836
// Exclude leaf including $deleteafterid from tree
2837
        if ($deleteafterid) {
2838
//print "Look to discard user ".$deleteafterid."\n";
2839
            $keyfilter1 = '^' . $deleteafterid . '$';
2840
            $keyfilter2 = '_' . $deleteafterid . '$';
2841
            $keyfilter3 = '^' . $deleteafterid . '_';
2842
            $keyfilter4 = '_' . $deleteafterid . '_';
2843
            foreach ($this->users as $key => $val) {
2844
                if (preg_match('/' . $keyfilter1 . '/', $val['fullpath']) || preg_match('/' . $keyfilter2 . '/', $val['fullpath']) || preg_match('/' . $keyfilter3 . '/', $val['fullpath']) || preg_match('/' . $keyfilter4 . '/', $val['fullpath'])) {
2845
                    unset($this->users[$key]);
2846
                }
2847
            }
2848
        }
2849
2850
        DolUtils::dol_syslog(get_class($this) . "::get_full_tree dol_sort_array", LOG_DEBUG);
2851
        $this->users = dol_sort_array($this->users, 'fullname', 'asc', true, false);
2852
2853
//var_dump($this->users);
2854
2855
        return $this->users;
2856
    }
2857
2858
    /**
2859
     * 	Return list of all child users id in herarchy (all sublevels).
2860
     *  Note: Calling this function also reset full list of users into $this->users.
2861
     *
2862
     *  @param      int      $addcurrentuser    1=Add also current user id to the list.
2863
     * 	@return		array		      		  	Array of user id lower than user (all levels under user). This overwrite this->users.
2864
     *  @see get_children
2865
     */
2866
    function getAllChildIds($addcurrentuser = 0)
2867
    {
2868
        $childids = array();
2869
2870
        if (isset($this->cache_childids[$this->id])) {
2871
            $childids = $this->cache_childids[$this->id];
2872
        } else {
2873
// Init this->users
2874
            $this->get_full_tree();
2875
2876
            $idtoscan = $this->id;
2877
2878
            DolUtils::dol_syslog("Build childid for id = " . $idtoscan);
2879
            foreach ($this->users as $id => $val) {
2880
//var_dump($val['fullpath']);
2881
                if (preg_match('/_' . $idtoscan . '_/', $val['fullpath'])) {
2882
                    $childids[$val['id']] = $val['id'];
2883
                }
2884
            }
2885
        }
2886
        $this->cache_childids[$this->id] = $childids;
2887
2888
        if ($addcurrentuser) {
2889
            $childids[$this->id] = $this->id;
2890
        }
2891
2892
        return $childids;
2893
    }
2894
2895
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2896
    /**
2897
     * 	For user id_user and its childs available in this->users, define property fullpath and fullname.
2898
     *  Function called by get_full_tree().
2899
     *
2900
     * 	@param		int		$id_user		id_user entry to update
2901
     * 	@param		int		$protection		Deep counter to avoid infinite loop (no more required, a protection is added with array useridfound)
2902
     * 	@return		int                     < 0 if KO (infinit loop), >= 0 if OK
2903
     */
2904
    function build_path_from_id_user($id_user, $protection = 0)
2905
    {
2906
// phpcs:enable
2907
        DolUtils::dol_syslog(get_class($this) . "::build_path_from_id_user id_user=" . $id_user . " protection=" . $protection, LOG_DEBUG);
2908
2909
        if (!empty($this->users[$id_user]['fullpath'])) {
2910
// Already defined
2911
            DolUtils::dol_syslog(get_class($this) . "::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
2912
            return 0;
2913
        }
2914
2915
// Define fullpath and fullname
2916
        $this->users[$id_user]['fullpath'] = '_' . $id_user;
2917
        $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
2918
        $i = 0;
2919
        $cursor_user = $id_user;
2920
2921
        Globals::$useridfound = array($id_user);
2922
        while (!empty($this->parentof[$cursor_user])) {
2923
            if (in_array($this->parentof[$cursor_user], Globals::$useridfound)) {
2924
                DolUtils::dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
2925
                return -1;     // Should not happen. Protection against looping hierarchy
2926
            }
2927
            Globals::$useridfound[] = $this->parentof[$cursor_user];
2928
            $this->users[$id_user]['fullpath'] = '_' . $this->parentof[$cursor_user] . $this->users[$id_user]['fullpath'];
2929
            $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'] . ' >> ' . $this->users[$id_user]['fullname'];
2930
            $i++;
2931
            $cursor_user = $this->parentof[$cursor_user];
2932
        }
2933
2934
// We count number of _ to have level
2935
        $this->users[$id_user]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->users[$id_user]['fullpath']));
2936
2937
        return 1;
2938
    }
2939
2940
    /**
2941
     * Function used to replace a thirdparty id with another one.
2942
     *
2943
     * @param DoliDB $db Database handler
2944
     * @param int $origin_id Old thirdparty id
2945
     * @param int $dest_id New thirdparty id
2946
     * @return bool
2947
     */
2948
    public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
2949
    {
2950
        $tables = array(
2951
            'user',
2952
        );
2953
2954
        return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2955
    }
2956
2957
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2958
    /**
2959
     *      Charge indicateurs this->nb pour le tableau de bord
2960
     *
2961
     *      @return     int         <0 if KO, >0 if OK
2962
     */
2963
    function load_state_board()
2964
    {
2965
// phpcs:enable
2966
       // global $conf;
2967
2968
        $this->nb = array();
2969
2970
        $sql = "SELECT count(u.rowid) as nb";
2971
        $sql .= " FROM " . MAIN_DB_PREFIX . "user as u";
2972
        $sql .= " WHERE u.statut > 0";
2973
//$sql.= " AND employee != 0";
2974
        $sql .= " AND u.entity IN (" . getEntity('user') . ")";
2975
2976
        $resql = Config::$dbEngine->query($sql);
2977
        if ($resql) {
2978
            while ($obj = Config::$dbEngine->fetch_object($resql)) {
2979
                $this->nb["users"] = $obj->nb;
2980
            }
2981
            Config::$dbEngine->free($resql);
2982
            return 1;
2983
        } else {
2984
            dol_print_error(Config::$dbEngine);
2985
            $this->error = Config::$dbEngine->error();
2986
            return -1;
2987
        }
2988
    }
2989
2990
    /**
2991
     *  Create a document onto disk according to template module.
2992
     *
2993
     * 	@param	    string		$modele			Force model to use ('' to not force)
2994
     * 	@param		Translate	$outputlangs	Object langs to use for output
2995
     *  @param      int			$hidedetails    Hide details of lines
2996
     *  @param      int			$hidedesc       Hide description
2997
     *  @param      int			$hideref        Hide ref
2998
     *  @param   null|array  $moreparams     Array to provide more information
2999
     * 	@return     int         				0 if KO, 1 if OK
3000
     */
3001
    public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3002
    {
3003
        //global $conf, Globals::$user, Globals::$langs;
3004
3005
        Globals::$langs->load("user");
3006
3007
// Positionne le modele sur le nom du modele a utiliser
3008
        if (!dol_strlen($modele)) {
3009
            if (!empty($conf->global->USER_ADDON_PDF)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
3010
                $modele = Globals::$conf->global->USER_ADDON_PDF;
3011
            } else {
3012
                $modele = 'bluesky';
3013
            }
3014
        }
3015
3016
        $modelpath = "core/modules/user/doc/";
3017
3018
        return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3019
    }
3020
3021
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3022
    /**
3023
     *  Return property of user from its id
3024
     *
3025
     *  @param	int		$rowid      id of contact
3026
     *  @param  string	$mode       'email' or 'mobile'
3027
     *  @return string  			Email of user with format: "Full name <email>"
3028
     */
3029
    function user_get_property($rowid, $mode)
3030
    {
3031
// phpcs:enable
3032
        $this->user_property = '';
3033
3034
        if (empty($rowid)) {
3035
            return '';
3036
        }
3037
3038
        $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
3039
        $sql .= " FROM " . MAIN_DB_PREFIX . "user";
3040
        $sql .= " WHERE rowid = '" . $rowid . "'";
3041
3042
        $resql = Config::$dbEngine->query($sql);
3043
        if ($resql) {
3044
            $nump = Config::$dbEngine->num_rows($resql);
3045
3046
            if ($nump) {
3047
                $obj = Config::$dbEngine->fetch_object($resql);
3048
3049
                if ($mode == 'email') {
3050
                    $this->user_property = dolGetFirstLastname($obj->firstname, $obj->lastname) . " <" . $obj->email . ">";
3051
                } else if ($mode == 'mobile') {
3052
                    $this->user_property = $obj->user_mobile;
3053
                }
3054
            }
3055
            return $this->user_property;
3056
        } else {
3057
            dol_print_error(Config::$dbEngine);
3058
        }
3059
    }
3060
3061
    /**
3062
     * 	Load all objects into $this->users
3063
     *
3064
     *  @param	string		$sortorder		sort order
3065
     *  @param	string		$sortfield		sort field
3066
     *  @param	int			$limit			limit page
3067
     *  @param	int			$offset			page
3068
     *  @param	array		$filter			Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
3069
     *  @param  string      $filtermode		Filter mode (AND or OR)
3070
     *  @return int							<0 if KO, >0 if OK
3071
     */
3072
    function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = array(), $filtermode = 'AND')
3073
    {
3074
        global $conf;
3075
3076
        $sql = "SELECT t.rowid";
3077
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t ';
3078
        $sql .= " WHERE 1";
3079
3080
// Manage filter
3081
        $sqlwhere = array();
3082
        if (!empty($filter)) {
3083
            foreach ($filter as $key => $value) {
3084
                if ($key == 't.rowid') {
3085
                    $sqlwhere[] = $key . '=' . $value;
3086
                } elseif (strpos($key, 'date') !== false) {
3087
                    $sqlwhere[] = $key . ' = \'' . Config::$dbEngine->idate($value) . '\'';
3088
                } elseif ($key == 'customsql') {
3089
                    $sqlwhere[] = $value;
3090
                } else {
3091
                    $sqlwhere[] = $key . ' LIKE \'%' . Config::$dbEngine->escape($value) . '%\'';
3092
                }
3093
            }
3094
        }
3095
        if (count($sqlwhere) > 0) {
3096
            $sql .= ' AND (' . implode(' ' . $filtermode . ' ', $sqlwhere) . ')';
3097
        }
3098
        $sql .= Config::$dbEngine->order($sortfield, $sortorder);
0 ignored issues
show
The method order() does not exist on Alxarafe\Database\Engine. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

3098
        $sql .= Config::$dbEngine->/** @scrutinizer ignore-call */ order($sortfield, $sortorder);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3099
        if ($limit) {
3100
            $sql .= Config::$dbEngine->plimit($limit + 1, $offset);
0 ignored issues
show
The method plimit() does not exist on Alxarafe\Database\Engine. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

3100
            $sql .= Config::$dbEngine->/** @scrutinizer ignore-call */ plimit($limit + 1, $offset);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3101
        }
3102
3103
        DolUtils::dol_syslog(get_class($this) . "::" . __METHOD__, LOG_DEBUG);
3104
3105
        $resql = Config::$dbEngine->query($sql);
3106
        if ($resql) {
3107
            $this->users = array();
3108
            $num = Config::$dbEngine->num_rows($resql);
3109
            if ($num) {
3110
                while ($obj = Config::$dbEngine->fetch_object($resql)) {
3111
                    $line = new self(Config::$dbEngine);
3112
                    $result = $line->fetch($obj->rowid);
3113
                    if ($result > 0 && !empty($line->id)) {
3114
                        $this->users[$obj->rowid] = clone $line;
3115
                    }
3116
                }
3117
                Config::$dbEngine->free($resql);
3118
            }
3119
            return $num;
3120
        } else {
3121
            $this->errors[] = Config::$dbEngine->lasterror();
3122
            return -1;
3123
        }
3124
    }
3125
}
3126