Completed
Branch develop (1d6b4c)
by
unknown
24:51
created

Users::_cleanObjectDatas()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2015   Jean-François Ferry     <[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
18
use Luracast\Restler\RestException;
19
20
//require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
21
22
/**
23
 * API class for users
24
 *
25
 * @access protected 
26
 * @class  DolibarrApiAccess {@requires user,external}
27
 */
28
class Users extends DolibarrApi
29
{
30
	/**
31
	 *
32
	 * @var array   $FIELDS     Mandatory fields, checked when create and update object 
33
	 */
34
	static $FIELDS = array(
35
		'login'
36
	);
37
38
	/**
39
	 * @var User $user {@type User}
40
	 */
41
	public $useraccount;
42
43
	/**
44
	 * Constructor
45
	 */
46
	function __construct() {
47
		global $db, $conf;
48
		$this->db = $db;
49
		$this->useraccount = new User($this->db);
50
	}
51
52
	
53
	/**
54
	 * List Users
55
	 *
56
	 * Get a list of Users
57
	 *
58
	 * @param string	$sortfield	Sort field
59
	 * @param string	$sortorder	Sort order
60
	 * @param int		$limit		Limit for list
61
	 * @param int		$page		Page number
62
	 * @param string   	$user_ids   User ids filter field. Example: '1' or '1,2,3'          {@pattern /^[0-9,]*$/i}
63
     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
64
	 * @return  array               Array of User objects
65
	 */
66
	function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $user_ids = 0, $sqlfilters = '') {
67
	    global $db, $conf;
68
	
69
	    $obj_ret = array();
70
	
71
		if(! DolibarrApiAccess::$user->rights->user->user->lire) {
72
	       throw new RestException(401, "You are not allowed to read list of users");
73
	    }
74
	     
75
	    // case of external user, $societe param is ignored and replaced by user's socid
76
	    //$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $societe;
77
	
78
	    $sql = "SELECT t.rowid";
79
	    $sql.= " FROM ".MAIN_DB_PREFIX."user as t";
80
	    $sql.= ' WHERE t.entity IN ('.getEntity('user', 1).')';
81
	    if ($user_ids) $sql.=" AND t.rowid IN (".$user_ids.")";
82
	    // Add sql filters
83
        if ($sqlfilters) 
84
        {
85
            if (! DolibarrApi::_checkFilters($sqlfilters))
86
            {
87
                throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
88
            }
89
	        $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
90
            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
91
        }
92
	    
93
	    $sql.= $db->order($sortfield, $sortorder);
94
	    if ($limit)	{
95
	        if ($page < 0)
96
	        {
97
	            $page = 0;
98
	        }
99
	        $offset = $limit * $page;
100
	
101
	        $sql.= $db->plimit($limit + 1, $offset);
102
	    }
103
	
104
	    $result = $db->query($sql);
105
	
106
	    if ($result)
107
	    {
108
	        $num = $db->num_rows($result);
109
	        while ($i < min($num, ($limit <= 0 ? $num : $limit)))
0 ignored issues
show
Bug introduced by
The variable $i does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
110
	        {
111
	            $obj = $db->fetch_object($result);
112
	            $user_static = new User($db);
113
	            if($user_static->fetch($obj->rowid)) {
114
	                $obj_ret[] = $this->_cleanObjectDatas($user_static);
115
	            }
116
	            $i++;
117
	        }
118
	    }
119
	    else {
120
	        throw new RestException(503, 'Error when retrieve User list : '.$db->lasterror());
121
	    }
122
	    if( ! count($obj_ret)) {
123
	        throw new RestException(404, 'No User found');
124
	    }
125
	    return $obj_ret;
126
	}
127
	
128
	/**
129
	 * Get properties of an user object
130
	 *
131
	 * Return an array with user informations
132
	 *
133
	 * @param 	int 	$id ID of user
134
	 * @return 	array|mixed data without useless information
135
	 * 
136
	 * @throws 	RestException
137
	 */
138
	function get($id) {
139
		//if (!DolibarrApiAccess::$user->rights->user->user->lire) {
140
			//throw new RestException(401);
141
		//}
142
143
		$result = $this->useraccount->fetch($id);
144
		if (!$result)
145
		{
146
			throw new RestException(404, 'User not found');
147
		}
148
149
		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
150
		{
151
			throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
152
		}
153
154
		return $this->_cleanObjectDatas($this->useraccount);
155
	}
156
	
157
	
158
	/**
159
	 * Create user account
160
	 *
161
	 * @param array $request_data New user data
162
	 * @return int
163
	 */
164
	function post($request_data = NULL) {
165
	    // check user authorization
166
	    //if(! DolibarrApiAccess::$user->rights->user->creer) {
167
	    //   throw new RestException(401, "User creation not allowed");
168
	    //}
169
	    // check mandatory fields
170
	    /*if (!isset($request_data["login"]))
171
	        throw new RestException(400, "login field missing");
172
	    if (!isset($request_data["password"]))
173
	        throw new RestException(400, "password field missing");
174
	    if (!isset($request_data["lastname"]))
175
	         throw new RestException(400, "lastname field missing");*/
176
	    //assign field values
177
        foreach ($request_data as $field => $value)
178
	    {
179
	          $this->useraccount->$field = $value;
180
	    }
181
182
	    if ($this->useraccount->create(DolibarrApiAccess::$user) < 0) {
183
             throw new RestException(500, 'Error creating', array_merge(array($this->useraccount->error), $this->useraccount->errors));
184
	    }
185
	    return $this->useraccount->id;
186
    }
187
	
188
    
189
	/**
190
	 * Update account
191
	 *
192
	 * @param int   $id             Id of account to update
193
	 * @param array $request_data   Datas   
194
	 * @return int 
195
	 */
196
	function put($id, $request_data = NULL) {
197
		//if (!DolibarrApiAccess::$user->rights->user->user->creer) {
198
			//throw new RestException(401);
199
		//}
200
201
		$result = $this->useraccount->fetch($id);
202
		if (!$result)
203
		{
204
			throw new RestException(404, 'Account not found');
205
		}
206
207
		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
208
		{
209
			throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
210
		}
211
212
		foreach ($request_data as $field => $value)
213
		{
214
            if ($field == 'id') continue;
215
		    $this->useraccount->$field = $value;
216
		}
217
218
		if ($this->useraccount->update(DolibarrApiAccess::$user, 1))
219
			return $this->get($id);
220
221
        return false;
222
    }
223
224
    /**
225
	 * add user to group
226
	 *
227
	 * @param   int     $id User ID
228
	 * @param   int     $group Group ID
229
	 * @return  int
230
     * 
231
	 * @url	GET {id}/setGroup/{group}
232
	 */
233
	function setGroup($id, $group) {
234
		//if (!DolibarrApiAccess::$user->rights->user->user->supprimer) {
235
			//throw new RestException(401);
236
		//}
237
        $result = $this->useraccount->fetch($id);
238
        if (!$result)
239
        {
240
          throw new RestException(404, 'User not found');
241
        }
242
    
243
        if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
244
        {
245
          throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
246
        }
247
    
248
        return $this->useraccount->SetInGroup($group,1);
249
    }
250
251
	/**
252
	 * Delete account
253
	 *
254
	 * @param   int     $id Account ID
255
	 * @return  array
256
	 */
257
	function delete($id) {
258
		//if (!DolibarrApiAccess::$user->rights->user->user->supprimer) {
259
			//throw new RestException(401);
260
		//}
261
		$result = $this->useraccount->fetch($id);
262
		if (!$result)
263
		{
264
			throw new RestException(404, 'User not found');
265
		}
266
267
		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
268
		{
269
			throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
270
		}
271
272
		return $this->useraccount->delete($id);
273
	}
274
275
	/**
276
	 * Clean sensible object datas
277
	 *
278
	 * @param   object  $object    Object to clean
279
	 * @return    array    Array of cleaned object properties
280
	 */
281
	function _cleanObjectDatas($object) {
282
	
283
	    $object = parent::_cleanObjectDatas($object);
284
	
285
	    unset($object->default_values);
286
	    unset($object->lastsearch_values);
287
	    unset($object->lastsearch_values_tmp);
288
	     
289
	    return $object;
290
	}	
291
	
292
	/**
293
	 * Validate fields before create or update object
294
     * 
295
	 * @param   array|null     $data   Data to validate
296
	 * @return  array
297
	 * @throws RestException
298
	 */
299
	function _validate($data) {
300
		$account = array();
301
		foreach (Users::$FIELDS as $field)
302
		{
303
			if (!isset($data[$field]))
304
				throw new RestException(400, "$field field missing");
305
			$account[$field] = $data[$field];
306
		}
307
		return $account;
308
	}
309
}
310