Passed
Branch develop (01f96b)
by
unknown
30:45
created

Users::index()   F

Complexity

Conditions 14
Paths 345

Size

Total Lines 73
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 14
eloc 40
c 2
b 0
f 0
nc 345
nop 7
dl 0
loc 73
rs 3.6208

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2015   Jean-François Ferry     <[email protected]>
3
/* Copyright (C) 2030   Thibault FOUCART     	<[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
use Luracast\Restler\RestException;
20
21
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
22
require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
23
24
/**
25
 * API class for users
26
 *
27
 * @access protected
28
 * @class  DolibarrApiAccess {@requires user,external}
29
 */
30
class Users extends DolibarrApi
31
{
32
	/**
33
	 *
34
	 * @var array   $FIELDS     Mandatory fields, checked when create and update object
35
	 */
36
	static $FIELDS = array(
37
		'login',
38
	);
39
40
	/**
41
	 * @var User $user {@type User}
42
	 */
43
	public $useraccount;
44
45
	/**
46
	 * Constructor
47
	 */
48
    public function __construct()
49
    {
50
		global $db, $conf;
51
		$this->db = $db;
52
		$this->useraccount = new User($this->db);
53
	}
54
55
56
	/**
57
	 * List Users
58
	 *
59
	 * Get a list of Users
60
	 *
61
	 * @param string	$sortfield	Sort field
62
	 * @param string	$sortorder	Sort order
63
	 * @param int		$limit		Limit for list
64
	 * @param int		$page		Page number
65
	 * @param string   	$user_ids   User ids filter field. Example: '1' or '1,2,3'          {@pattern /^[0-9,]*$/i}
66
     * @param  int    $category   Use this param to filter list by category
67
     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
68
	 * @return  array               Array of User objects
69
	 */
70
    public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $category = 0, $sqlfilters = '')
71
    {
72
	    global $db, $conf;
73
74
	    $obj_ret = array();
75
76
		if (!DolibarrApiAccess::$user->rights->user->user->lire) {
77
	        throw new RestException(401, "You are not allowed to read list of users");
78
	    }
79
80
	    // case of external user, $societe param is ignored and replaced by user's socid
81
	    //$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $societe;
82
83
	    $sql = "SELECT t.rowid";
84
	    $sql .= " FROM ".MAIN_DB_PREFIX."user as t";
85
        if ($category > 0) {
86
            $sql .= ", ".MAIN_DB_PREFIX."categorie_user as c";
87
        }
88
	    $sql .= ' WHERE t.entity IN ('.getEntity('user').')';
89
	    if ($user_ids) $sql .= " AND t.rowid IN (".$user_ids.")";
90
91
    	// Select products of given category
92
    	if ($category > 0) {
93
			$sql .= " AND c.fk_categorie = ".$db->escape($category);
94
			$sql .= " AND c.fk_user = t.rowid ";
95
    	}
96
97
	    // Add sql filters
98
        if ($sqlfilters)
99
        {
100
            if (!DolibarrApi::_checkFilters($sqlfilters))
101
            {
102
                throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
103
            }
104
	        $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
105
            $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
106
        }
107
108
	    $sql .= $db->order($sortfield, $sortorder);
109
	    if ($limit) {
110
	        if ($page < 0)
111
	        {
112
	            $page = 0;
113
	        }
114
	        $offset = $limit * $page;
115
116
	        $sql .= $db->plimit($limit + 1, $offset);
117
	    }
118
119
	    $result = $db->query($sql);
120
121
	    if ($result)
122
	    {
123
	        $i = 0;
124
	        $num = $db->num_rows($result);
125
	        $min = min($num, ($limit <= 0 ? $num : $limit));
126
	        while ($i < $min)
127
	        {
128
	            $obj = $db->fetch_object($result);
129
	            $user_static = new User($db);
130
	            if ($user_static->fetch($obj->rowid)) {
131
	                $obj_ret[] = $this->_cleanObjectDatas($user_static);
132
	            }
133
	            $i++;
134
	        }
135
	    }
136
	    else {
137
	        throw new RestException(503, 'Error when retrieve User list : '.$db->lasterror());
138
	    }
139
	    if (!count($obj_ret)) {
140
	        throw new RestException(404, 'No User found');
141
	    }
142
	    return $obj_ret;
143
	}
144
145
	/**
146
	 * Get properties of an user object
147
	 * Return an array with user informations
148
	 *
149
	 * @param 	int 	$id 					ID of user
150
	 * @param	int		$includepermissions	Set this to 1 to have the array of permissions loaded (not done by default for performance purpose)
151
	 * @return 	array|mixed data without useless information
152
	 *
153
	 * @throws 	RestException
154
	 */
155
    public function get($id, $includepermissions = 0)
156
    {
157
		//if (!DolibarrApiAccess::$user->rights->user->user->lire) {
158
			//throw new RestException(401);
159
		//}
160
161
		$result = $this->useraccount->fetch($id);
162
		if (!$result)
163
		{
164
			throw new RestException(404, 'User not found');
165
		}
166
167
		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
168
		{
169
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
170
		}
171
172
		if ($includepermissions) {
173
			$this->useraccount->getRights();
174
		}
175
176
		return $this->_cleanObjectDatas($this->useraccount);
177
	}
178
179
    /**
180
     * Get properties of user connected
181
     *
182
     * @url	GET /info
183
     *
184
     * @return  array|mixed Data without useless information
185
     *
186
     * @throws RestException 401     Insufficient rights
187
     * @throws RestException 404     User or group not found
188
     */
189
    public function getInfo()
190
    {
191
        $apiUser = DolibarrApiAccess::$user;
192
193
        $result = $this->useraccount->fetch($apiUser->id);
194
        if (!$result) {
195
            throw new RestException(404, 'User not found');
196
        }
197
198
        if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
199
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
200
        }
201
202
        $usergroup = new UserGroup($this->db);
203
        $userGroupList = $usergroup->listGroupsForUser($apiUser->id, false);
204
        if (!is_array($userGroupList)) {
205
            throw new RestException(404, 'User group not found');
206
        }
207
208
        $this->useraccount->user_group_list = $this->_cleanUserGroupListDatas($userGroupList);
0 ignored issues
show
Bug introduced by
The property user_group_list does not seem to exist on User.
Loading history...
209
210
        return $this->_cleanObjectDatas($this->useraccount);
211
    }
212
213
	/**
214
	 * Create user account
215
	 *
216
	 * @param array $request_data New user data
217
	 * @return int
218
	 */
219
    public function post($request_data = null)
220
    {
221
	    // check user authorization
222
	    //if(! DolibarrApiAccess::$user->rights->user->creer) {
223
	    //   throw new RestException(401, "User creation not allowed");
224
	    //}
225
	    // check mandatory fields
226
	    /*if (!isset($request_data["login"]))
227
	        throw new RestException(400, "login field missing");
228
	    if (!isset($request_data["password"]))
229
	        throw new RestException(400, "password field missing");
230
	    if (!isset($request_data["lastname"]))
231
	         throw new RestException(400, "lastname field missing");*/
232
	    //assign field values
233
        foreach ($request_data as $field => $value)
234
	    {
235
	          $this->useraccount->$field = $value;
236
	    }
237
238
	    if ($this->useraccount->create(DolibarrApiAccess::$user) < 0) {
239
             throw new RestException(500, 'Error creating', array_merge(array($this->useraccount->error), $this->useraccount->errors));
240
	    }
241
	    return $this->useraccount->id;
242
    }
243
244
245
	/**
246
	 * Update account
247
	 *
248
	 * @param int   $id             Id of account to update
249
	 * @param array $request_data   Datas
250
	 * @return array
251
     *
252
     * @throws 	RestException
253
	 */
254
    public function put($id, $request_data = null)
255
    {
256
		//if (!DolibarrApiAccess::$user->rights->user->user->creer) {
257
			//throw new RestException(401);
258
		//}
259
260
		$result = $this->useraccount->fetch($id);
261
		if (!$result)
262
		{
263
			throw new RestException(404, 'Account not found');
264
		}
265
266
		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
267
		{
268
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
269
		}
270
271
		foreach ($request_data as $field => $value)
272
		{
273
			if ($field == 'id') continue;
274
			// The status must be updated using setstatus() because it
275
			// is not handled by the update() method.
276
			if ($field == 'statut') {
277
				$result = $this->useraccount->setstatus($value);
278
				if ($result < 0) {
279
				    throw new RestException(500, 'Error when updating status of user: '.$this->useraccount->error);
280
				}
281
			} else {
282
			    $this->useraccount->$field = $value;
283
			}
284
		}
285
286
		// If there is no error, update() returns the number of affected
287
		// rows so if the update is a no op, the return value is zezo.
288
		if ($this->useraccount->update(DolibarrApiAccess::$user) >= 0)
289
		{
290
			return $this->get($id);
291
		}
292
		else
293
		{
294
			throw new RestException(500, $this->useraccount->error);
295
		}
296
    }
297
298
299
	/**
300
	 * List the groups of a user
301
	 *
302
	 * @param int $id     Id of user
303
	 * @return array      Array of group objects
304
	 *
305
	 * @throws RestException 403 Not allowed
306
     * @throws RestException 404 Not found
307
	 *
308
	 * @url GET {id}/groups
309
	 */
310
	public function getGroups($id)
311
	{
312
		$obj_ret = array();
313
314
		if (!DolibarrApiAccess::$user->rights->user->user->lire) {
315
			throw new RestException(403);
316
		}
317
318
		$user = new User($this->db);
319
		$result = $user->fetch($id);
320
		if (!$result) {
321
			throw new RestException(404, 'user not found');
322
		}
323
324
		$usergroup = new UserGroup($this->db);
325
		$groups = $usergroup->listGroupsForUser($id, false);
326
		$obj_ret = array();
327
		foreach ($groups as $group) {
328
			$obj_ret[] = $this->_cleanObjectDatas($group);
329
		}
330
		return $obj_ret;
331
	}
332
333
334
    /**
335
	 * Add a user into a group
336
	 *
337
	 * @param   int     $id        User ID
338
	 * @param   int     $group     Group ID
339
	 * @param   int     $entity    Entity ID (valid only for superadmin in multicompany transverse mode)
340
	 * @return  int                1 if success
341
     *
342
	 * @url	GET {id}/setGroup/{group}
343
	 */
344
    public function setGroup($id, $group, $entity = 1)
345
    {
346
347
		global $conf;
348
349
		//if (!DolibarrApiAccess::$user->rights->user->user->supprimer) {
350
			//throw new RestException(401);
351
		//}
352
		$result = $this->useraccount->fetch($id);
353
		if (!$result)
354
		{
355
			throw new RestException(404, 'User not found');
356
		}
357
358
		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
359
		{
360
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
361
		}
362
363
		if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && !empty(DolibarrApiAccess::$user->admin) && empty(DolibarrApiAccess::$user->entity))
364
		{
365
			$entity = (!empty($entity) ? $entity : $conf->entity);
366
		}
367
		else
368
		{
369
			// When using API, action is done on entity of logged user because a user of entity X with permission to create user should not be able to
370
			// hack the security by giving himself permissions on another entity.
371
			$entity = (DolibarrApiAccess::$user->entity > 0 ? DolibarrApiAccess::$user->entity : $conf->entity);
372
		}
373
374
		$result = $this->useraccount->SetInGroup($group, $entity);
375
		if (!($result > 0))
376
		{
377
			throw new RestException(500, $this->useraccount->error);
378
		}
379
380
		return 1;
381
	}
382
383
	/**
384
	 * List Groups
385
	 *
386
	 * Return an array with a list of Groups
387
	 *
388
	 * @url	GET /groups
389
	 *
390
	 * @param string	$sortfield	Sort field
391
	 * @param string	$sortorder	Sort order
392
	 * @param int		$limit		Limit for list
393
	 * @param int		$page		Page number
394
	 * @param string   	$group_ids   Groups ids filter field. Example: '1' or '1,2,3'          {@pattern /^[0-9,]*$/i}
395
	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
396
	 * @return  array               Array of User objects
397
	 */
398
    public function listGroups($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $group_ids = 0, $sqlfilters = '')
399
    {
400
	    global $db, $conf;
401
402
	    $obj_ret = array();
403
404
		if (!DolibarrApiAccess::$user->rights->user->group_advance->read) {
405
	        throw new RestException(401, "You are not allowed to read list of groups");
406
	    }
407
408
	    // case of external user, $societe param is ignored and replaced by user's socid
409
	    //$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $societe;
410
411
	    $sql = "SELECT t.rowid";
412
	    $sql .= " FROM ".MAIN_DB_PREFIX."usergroup as t";
413
	    $sql .= ' WHERE t.entity IN ('.getEntity('user').')';
414
	    if ($group_ids) $sql .= " AND t.rowid IN (".$group_ids.")";
415
	    // Add sql filters
416
        if ($sqlfilters)
417
        {
418
            if (!DolibarrApi::_checkFilters($sqlfilters))
419
            {
420
                throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
421
            }
422
	        $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
423
            $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
424
        }
425
426
	    $sql .= $db->order($sortfield, $sortorder);
427
	    if ($limit) {
428
	        if ($page < 0)
429
	        {
430
	            $page = 0;
431
	        }
432
	        $offset = $limit * $page;
433
434
	        $sql .= $db->plimit($limit + 1, $offset);
435
	    }
436
437
	    $result = $db->query($sql);
438
439
	    if ($result)
440
	    {
441
	        $i = 0;
442
	        $num = $db->num_rows($result);
443
	        $min = min($num, ($limit <= 0 ? $num : $limit));
444
	        while ($i < $min)
445
	        {
446
	            $obj = $db->fetch_object($result);
447
	            $group_static = new UserGroup($this->db);
448
	            if ($group_static->fetch($obj->rowid)) {
449
	                $obj_ret[] = $this->_cleanObjectDatas($group_static);
450
	            }
451
	            $i++;
452
	        }
453
	    }
454
	    else {
455
	        throw new RestException(503, 'Error when retrieve Group list : '.$db->lasterror());
456
	    }
457
	    if (!count($obj_ret)) {
458
	        throw new RestException(404, 'No Group found');
459
	    }
460
	    return $obj_ret;
461
	}
462
463
	/**
464
	 * Get properties of an group object
465
	 *
466
	 * Return an array with group informations
467
	 *
468
	 * @url	GET /groups/{group}
469
	 *
470
	 * @param 	int 	$group ID of group
471
	 * @param int       $load_members     Load members list or not {@min 0} {@max 1}
472
	 * @return  array               Array of User objects
473
	 */
474
    public function infoGroups($group, $load_members = 0)
475
    {
476
	    global $db, $conf;
477
478
		if (!DolibarrApiAccess::$user->rights->user->group_advance->read) {
479
	        throw new RestException(401, "You are not allowed to read groups");
480
	    }
481
482
	            $group_static = new UserGroup($this->db);
483
	            $result = $group_static->fetch($group, '', $load_members);
484
485
		if (!$result)
486
		{
487
			throw new RestException(404, 'Group not found');
488
		}
489
490
	    return $this->_cleanObjectDatas($group_static);
491
	}
492
493
	/**
494
	 * Delete account
495
	 *
496
	 * @param   int     $id Account ID
497
	 * @return  array
498
	 */
499
    public function delete($id)
500
    {
501
		//if (!DolibarrApiAccess::$user->rights->user->user->supprimer) {
502
			//throw new RestException(401);
503
		//}
504
		$result = $this->useraccount->fetch($id);
505
		if (!$result)
506
		{
507
			throw new RestException(404, 'User not found');
508
		}
509
510
		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
511
		{
512
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
513
		}
514
        $this->useraccount->oldcopy = clone $this->useraccount;
515
		return $this->useraccount->delete(DolibarrApiAccess::$user);
516
	}
517
518
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
519
	/**
520
	 * Clean sensible object datas
521
	 *
522
	 * @param   object  $object    Object to clean
523
	 * @return  array    			Array of cleaned object properties
524
	 */
525
	protected function _cleanObjectDatas($object)
526
	{
527
        // phpcs:enable
528
		global $conf;
529
530
	    $object = parent::_cleanObjectDatas($object);
531
532
	    unset($object->default_values);
533
	    unset($object->lastsearch_values);
534
	    unset($object->lastsearch_values_tmp);
535
536
	    unset($object->total_ht);
537
	    unset($object->total_tva);
538
	    unset($object->total_localtax1);
539
	    unset($object->total_localtax2);
540
	    unset($object->total_ttc);
541
542
	    unset($object->label_incoterms);
543
	    unset($object->location_incoterms);
544
545
	    unset($object->fk_delivery_address);
546
	    unset($object->fk_incoterms);
547
	    unset($object->all_permissions_are_loaded);
548
	    unset($object->shipping_method_id);
549
	    unset($object->nb_rights);
550
	    unset($object->search_sid);
551
	    unset($object->ldap_sid);
552
	    unset($object->clicktodial_loaded);
553
554
	    // List of properties never returned by API, whatever are permissions
555
	    unset($object->pass);
556
	    unset($object->pass_indatabase);
557
	    unset($object->pass_indatabase_crypted);
558
	    unset($object->pass_temp);
559
	    unset($object->api_key);
560
	    unset($object->clicktodial_password);
561
	    unset($object->openid);
562
563
	    unset($object->lines);
564
	    unset($object->modelpdf);
565
	    unset($object->skype);
566
	    unset($object->twitter);
567
	    unset($object->facebook);
568
	    unset($object->linkedin);
569
570
	    $canreadsalary = ((!empty($conf->salaries->enabled) && !empty(DolibarrApiAccess::$user->rights->salaries->read))
571
	    	|| (!empty($conf->hrm->enabled) && !empty(DolibarrApiAccess::$user->rights->hrm->employee->read)));
572
573
		if (!$canreadsalary)
574
		{
575
			unset($object->salary);
576
			unset($object->salaryextra);
577
			unset($object->thm);
578
			unset($object->tjm);
579
		}
580
581
	    return $object;
582
	}
583
584
    /**
585
     * Clean sensible user group list datas
586
     *
587
     * @param   array  $objectList   Array of object to clean
588
     * @return  array                Array of cleaned object properties
589
     */
590
    private function _cleanUserGroupListDatas($objectList)
591
    {
592
        $cleanObjectList = array();
593
594
        foreach ($objectList as $object) {
595
            $cleanObject = parent::_cleanObjectDatas($object);
596
597
            unset($cleanObject->default_values);
598
            unset($cleanObject->lastsearch_values);
599
            unset($cleanObject->lastsearch_values_tmp);
600
601
            unset($cleanObject->total_ht);
602
            unset($cleanObject->total_tva);
603
            unset($cleanObject->total_localtax1);
604
            unset($cleanObject->total_localtax2);
605
            unset($cleanObject->total_ttc);
606
607
            unset($cleanObject->libelle_incoterms);
608
            unset($cleanObject->location_incoterms);
609
610
            unset($cleanObject->fk_delivery_address);
611
            unset($cleanObject->fk_incoterms);
612
            unset($cleanObject->all_permissions_are_loaded);
613
            unset($cleanObject->shipping_method_id);
614
            unset($cleanObject->nb_rights);
615
            unset($cleanObject->search_sid);
616
            unset($cleanObject->ldap_sid);
617
            unset($cleanObject->clicktodial_loaded);
618
619
            unset($cleanObject->datec);
620
            unset($cleanObject->datem);
621
            unset($cleanObject->members);
622
            unset($cleanObject->note);
623
            unset($cleanObject->note_private);
624
625
            $cleanObjectList[] = $cleanObject;
626
        }
627
628
        return $cleanObjectList;
629
    }
630
631
	/**
632
	 * Validate fields before create or update object
633
     *
634
	 * @param   array|null     $data   Data to validate
635
	 * @return  array
636
	 * @throws RestException
637
     */
638
    private function _validate($data)
639
    {
640
        $account = array();
641
        foreach (Users::$FIELDS as $field) {
642
            if (!isset($data[$field]))
643
                throw new RestException(400, "$field field missing");
644
            $account[$field] = $data[$field];
645
        }
646
        return $account;
647
    }
648
}
649