/
Users_model.php
480 lines (416 loc) · 13.3 KB
/
Users_model.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
<?php defined('BASEPATH') or exit('No direct script access allowed');
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.0.0
* ---------------------------------------------------------------------------- */
/**
* Users model.
*
* Handles all the database operations of the user resource.
*
* @package Models
*/
class Users_model extends EA_Model {
/**
* @var array
*/
protected $casts = [
'id' => 'integer',
'id_roles' => 'integer',
];
/**
* @var array
*/
protected $api_resource = [
'id' => 'id',
'firstName' => 'first_name',
'lastName' => 'last_name',
'email' => 'email',
'mobile' => 'mobile_number',
'phone' => 'phone_number',
'address' => 'address',
'city' => 'city',
'state' => 'state',
'zip' => 'zip_code',
'timezone' => 'timezone',
'language' => 'language',
'notes' => 'notes',
'roleId' => 'id_roles',
];
/**
* Save (insert or update) a user.
*
* @param array $user Associative array with the user data.
*
* @return int Returns the user ID.
*
* @throws InvalidArgumentException
*/
public function save(array $user): int
{
$this->validate($user);
if (empty($user['id']))
{
return $this->insert($user);
}
else
{
return $this->update($user);
}
}
/**
* Validate the user data.
*
* @param array $user Associative array with the user data.
*
* @throws InvalidArgumentException
*/
public function validate(array $user)
{
// If a user ID is provided then check whether the record really exists in the database.
if ( ! empty($user['id']))
{
$count = $this->db->get_where('users', ['id' => $user['id']])->num_rows();
if ( ! $count)
{
throw new InvalidArgumentException('The provided user ID does not exist in the database: ' . $user['id']);
}
}
// Make sure all required fields are provided.
if (
empty($user['first_name'])
|| empty($user['last_name'])
|| empty($user['email'])
|| empty($user['phone_number'])
)
{
throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($user, TRUE));
}
}
/**
* Insert a new user into the database.
*
* @param array $user Associative array with the user data.
*
* @return int Returns the user ID.
*
* @throws RuntimeException
*/
protected function insert(array $user): int
{
$user['create_datetime'] = date('Y-m-d H:i:s');
$user['update_datetime'] = date('Y-m-d H:i:s');
$settings = $user['settings'];
unset($user['settings']);
if ( ! $this->db->insert('users', $user))
{
throw new RuntimeException('Could not insert user.');
}
$user['id'] = $this->db->insert_id();
$settings['salt'] = generate_salt();
$settings['password'] = hash_password($settings['salt'], $settings['password']);
$this->save_settings($user['id'], $settings);
return $user['id'];
}
/**
* Update an existing user.
*
* @param array $user Associative array with the user data.
*
* @return int Returns the user ID.
*
* @throws RuntimeException
*/
protected function update(array $user): int
{
$user['update_datetime'] = date('Y-m-d H:i:s');
$settings = $user['settings'];
unset($user['settings']);
if (isset($settings['password']))
{
$existing_settings = $this->db->get_where('user_settings', ['id_users' => $user['id']])->row_array();
if (empty($existing_settings))
{
throw new RuntimeException('No settings record found for user with ID: ' . $user['id']);
}
$settings['password'] = hash_password($existing_settings['salt'], $settings['password']);
}
if ( ! $this->db->update('users', $user, ['id' => $user['id']]))
{
throw new RuntimeException('Could not update user.');
}
$this->save_settings($user['id'], $settings);
return $user['id'];
}
/**
* Remove an existing user from the database.
*
* @param int $user_id User ID.
* @param bool $force_delete Override soft delete.
*
* @throws RuntimeException
*/
public function delete(int $user_id, bool $force_delete = FALSE)
{
if ($force_delete)
{
$this->db->delete('users', ['id' => $user_id]);
}
else
{
$this->db->update('users', ['delete_datetime' => date('Y-m-d H:i:s')], ['id' => $user_id]);
}
}
/**
* Get a specific user from the database.
*
* @param int $user_id The ID of the record to be returned.
* @param bool $with_trashed
*
* @return array Returns an array with the user data.
*
* @throws InvalidArgumentException
*/
public function find(int $user_id, bool $with_trashed = FALSE): array
{
if ( ! $with_trashed)
{
$this->db->where('delete_datetime IS NULL');
}
$user = $this->db->get_where('users', ['id' => $user_id])->row_array();
if ( ! $user)
{
throw new InvalidArgumentException('The provided user ID was not found in the database: ' . $user_id);
}
$this->cast($user);
$user['settings'] = $this->db->get_where('user_settings', ['id_users' => $user_id])->row_array();
unset(
$user['settings']['id_users'],
$user['settings']['password'],
$user['settings']['salt'],
);
return $user;
}
/**
* Get a specific field value from the database.
*
* @param int $user_id User ID.
* @param string $field Name of the value to be returned.
*
* @return string Returns the selected user value from the database.
*
* @throws InvalidArgumentException
*/
public function value(int $user_id, string $field): string
{
if (empty($field))
{
throw new InvalidArgumentException('The field argument is cannot be empty.');
}
if (empty($user_id))
{
throw new InvalidArgumentException('The user ID argument cannot be empty.');
}
// Check whether the user exists.
$query = $this->db->get_where('users', ['id' => $user_id]);
if ( ! $query->num_rows())
{
throw new InvalidArgumentException('The provided user ID was not found in the database: ' . $user_id);
}
// Check if the required field is part of the user data.
$user = $query->row_array();
$this->cast($user);
if ( ! array_key_exists($field, $user))
{
throw new InvalidArgumentException('The requested field was not found in the user data: ' . $field);
}
return $user[$field];
}
/**
* Get all users that match the provided criteria.
*
* @param array|string $where Where conditions
* @param int|null $limit Record limit.
* @param int|null $offset Record offset.
* @param string|null $order_by Order by.
* @param bool $with_trashed
*
* @return array Returns an array of users.
*/
public function get($where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL, bool $with_trashed = FALSE): array
{
if ($where !== NULL)
{
$this->db->where($where);
}
if ($order_by !== NULL)
{
$this->db->order_by($order_by);
}
if ( ! $with_trashed)
{
$this->db->where('delete_datetime IS NULL');
}
$users = $this->db->get('users', $limit, $offset)->result_array();
foreach ($users as &$user)
{
$this->cast($user);
$user['settings'] = $this->db->get_where('user_settings', ['id_users' => $user['id']])->row_array();
unset(
$user['settings']['id_users'],
$user['settings']['password'],
$user['settings']['salt']
);
}
return $users;
}
/**
* Save the user settings.
*
* @param int $user_id User ID.
* @param array $settings Associative array with the settings data.
*
* @throws InvalidArgumentException
*/
protected function save_settings(int $user_id, array $settings)
{
if (empty($settings))
{
throw new InvalidArgumentException('The settings argument cannot be empty.');
}
// Make sure the settings record exists in the database.
$count = $this->db->get_where('user_settings', ['id_users' => $user_id])->num_rows();
if ( ! $count)
{
$this->db->insert('user_settings', ['id_users' => $user_id]);
}
foreach ($settings as $name => $value)
{
$this->set_setting($user_id, $name, $value);
}
}
/**
* Set the value of a user setting.
*
* @param int $user_id User ID.
* @param string $name Setting name.
* @param string $value Setting value.
*/
public function set_setting(int $user_id, string $name, string $value)
{
if ( ! $this->db->update('user_settings', [$name => $value], ['id_users' => $user_id]))
{
throw new RuntimeException('Could not set the new user setting value: ' . $name);
}
}
/**
* Get the value of a user setting.
*
* @param int $user_id User ID.
* @param string $name Setting name.
*
* @return string Returns the value of the requested user setting.
*/
public function get_setting(int $user_id, string $name): string
{
$settings = $this->db->get_where('user_settings', ['id_users' => $user_id])->row_array();
if (empty($settings[$name]))
{
throw new RuntimeException('The requested setting value was not found: ' . $user_id);
}
return $settings[$name];
}
/**
* Get the query builder interface, configured for use with the users table.
*
* @return CI_DB_query_builder
*/
public function query(): CI_DB_query_builder
{
return $this->db->from('users');
}
/**
* Search users by the provided keyword.
*
* @param string $keyword Search keyword.
* @param int|null $limit Record limit.
* @param int|null $offset Record offset.
* @param string|null $order_by Order by.
* @param bool $with_trashed
*
* @return array Returns an array of settings.
*/
public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL, bool $with_trashed = FALSE): array
{
if ( ! $with_trashed)
{
$this->db->where('delete_datetime IS NULL');
}
$users = $this
->db
->select()
->from('users')
->group_start()
->like('first_name', $keyword)
->or_like('last_name', $keyword)
->or_like('email', $keyword)
->or_like('phone_number', $keyword)
->or_like('mobile_number', $keyword)
->or_like('address', $keyword)
->or_like('city', $keyword)
->or_like('state', $keyword)
->or_like('zip_code', $keyword)
->or_like('notes', $keyword)
->group_end()
->limit($limit)
->offset($offset)
->order_by($order_by)
->get()
->result_array();
foreach ($users as &$user)
{
$this->cast($user);
$user['settings'] = $this->db->get_where('user_settings', ['id_users' => $user['id']])->row_array();
unset(
$user['settings']['id_users'],
$user['settings']['password'],
$user['settings']['salt']
);
}
return $users;
}
/**
* Load related resources to a user.
*
* @param array $user Associative array with the user data.
* @param array $resources Resource names to be attached.
*
* @throws InvalidArgumentException
*/
public function load(array &$user, array $resources)
{
// Users do not currently have any related resources.
}
/**
* Validate the username.
*
* @param string $username Username.
* @param int|null $user_id Exclude user ID.
*
* @return bool Returns the validation result.
*/
public function validate_username(string $username, int $user_id = NULL): bool
{
if ( ! empty($user_id))
{
$this->db->where('id_users !=', $user_id);
}
return $this->db->get_where('user_settings', ['username' => $username])->num_rows() === 0;
}
}