forked from openemr/openemr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserService.php
382 lines (348 loc) · 12.3 KB
/
UserService.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
<?php
/**
* UserService
*
* @package OpenEMR
* @link http://www.open-emr.org
* @author Matthew Vita <[email protected]>
* @author Victor Kofia <[email protected]>
* @author Ken Chapple <[email protected]>
* @copyright Copyright (c) 2017 Matthew Vita <[email protected]>
* @copyright Copyright (c) 2017 Victor Kofia <[email protected]>
* @copyright Copyright (c) 2021 Ken Chapple <[email protected]>
* @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
*/
namespace OpenEMR\Services;
use OpenEMR\Common\Database\QueryUtils;
use OpenEMR\Common\Uuid\UuidRegistry;
use OpenEMR\Services\Search\FhirSearchWhereClauseBuilder;
use OpenEMR\Validators\ProcessingResult;
class UserService
{
private $_includeUsername;
/**
* The name of the system user used for api requests.
*/
const SYSTEM_USER_USERNAME = 'oe-system';
/**
* Default constructor.
*/
public function __construct()
{
$this->_includeUsername = false;
}
/**
* Sensitive fields in the database that are excluded by default from the service can be included here.
* Things such as username are normally excluded.
* @param $fields
* @return void
*/
public function toggleSensitiveFields($fields)
{
foreach ($fields as $field) {
switch ($field) {
case 'username':
$this->_includeUsername = !$this->_includeUsername;
break;
}
}
}
public function getUuidFields()
{
return ['uuid'];
}
/**
* Given a username, check to ensure user is in a group (and collect the group name)
* Returns the group name if successful, or false if failure
*
* @param $username
* @return string|bool
*/
public static function getAuthGroupForUser($username)
{
$return = false;
$result = privQuery("select `name` from `groups` where BINARY `user` = ?", [$username]);
if ($result !== false && !empty($result['name'])) {
$return = $result['name'];
}
return $return;
}
/**
* @return array hydrated user object
*/
public function getUser($userId)
{
// TODO: look at deserializing uuid with createResultRecordFromDatabaseResult here
$record = sqlQuery("SELECT * FROM `users` WHERE `id` = ?", [$userId]);
return $this->createResultRecordFromDatabaseResult($record);
}
/**
* @return array hydrated user object
*/
public function getUserByUsername($username)
{
$record = sqlQuery("SELECT * FROM `users` WHERE BINARY `username` = ?", [$username]);
if (!empty($record)) {
return $this->createResultRecordFromDatabaseResult($record);
}
return $record;
}
/**
* Retrieves the API System User if it exists, returns null if the user does not exist.
* @return array
*/
public function getSystemUser()
{
$user = $this->getUserByUsername(self::SYSTEM_USER_USERNAME);
if (!empty($user)) {
if (empty($user['uuid'])) {
// we should always have this setup, but create them just in case.
UuidRegistry::createMissingUuidsForTables(['users']);
}
}
return $user;
}
/**
* @return array active users (fully hydrated)
*/
public function getActiveUsers()
{
$users = [];
$user = sqlStatement("SELECT * FROM `users` WHERE (`username` != '' AND `username` IS NOT NULL) AND `active` = 1 ORDER BY `lname` ASC, `fname` ASC, `mname` ASC");
while ($row = sqlFetchArray($user)) {
// TODO: look at deserializing uuid with createResultRecordFromDatabaseResult here
$users[] = $row;
}
return $users;
}
/**
* @return array
*/
public function getCurrentlyLoggedInUser()
{
// TODO: look at deserializing uuid with createResultRecordFromDatabaseResult here
return sqlQuery("SELECT * FROM `users` WHERE `id` = ?", [$_SESSION['authUserID']]);
}
/**
* Returns a user by the given UUID. Can take a byte string or a UUID in string format.
* @param $userId string
*/
public function getUserByUUID($uuid)
{
if (is_string($uuid)) {
$uuid = UuidRegistry::uuidToBytes($uuid);
}
$user = sqlQuery("SELECT * FROM `users` WHERE `uuid` = ?", [$uuid]);
// this is very annoying...
if (!empty($user)) {
$user = $this->createResultRecordFromDatabaseResult($user);
}
return $user;
}
/**
* Retrieves a single user that is authorized for the calendar
* @param $userId
* @return array|null
*/
public function getUserForCalendar($userId)
{
// TODO: eventually we'd like to leverage the inner search piece here and combine these methods
return $this->searchUsersForCalendar("", $userId);
}
/**
* Retrieves all the users that have been set to show up on the calendar optionally filtered by the facility if one
* is provided.
* @param string $facility
* @return array|null
*/
public function getUsersForCalendar($facility = "")
{
return $this->searchUsersForCalendar($facility);
}
private function searchUsersForCalendar($facility = "", $userId = null)
{
// this originally came from patient.inc.php::getProviderInfo()
$param1 = " AND authorized = 1 AND calendar = 1 ";
$bind = [];
if (!empty($userId)) {
$param1 .= " AND id = ? ";
$bind[] = $userId;
}
//--------------------------------
//(CHEMED) facility filter
$param2 = "";
if (!empty($facility)) {
if ($GLOBALS['restrict_user_facility']) {
$param2 = " AND (facility_id = ? OR ? IN (select facility_id from users_facility where tablename = 'users' and table_id = id))";
$bind[] = $facility;
$bind[] = $facility;
} else {
$param2 = " AND facility_id = ? ";
$bind[] = $facility;
}
}
$query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
"from users where username != '' " . $param1 . $param2;
// sort by last name -- JRM June 2008
$query .= " ORDER BY lname, fname ";
$records = QueryUtils::fetchRecords($query, $bind);
//if only one result returned take the key/value pairs in array [0] and merge them down into
// the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
if (count($records) == 1) {
$akeys = array_keys($records[0]);
foreach ($akeys as $key) {
$records[0][$key] = $records[0][$key];
}
}
return ($records ?? null);
}
public function search($search, $isAndCondition = true)
{
$sql = "SELECT id,
uuid,
users.title as title,
fname,
lname,
mname,
federaltaxid,
federaldrugid,
upin,
facility_id,
facility,
npi,
email,
active,
specialty,
billname,
url,
assistant,
organization,
valedictory,
street,
streetb,
city,
state,
zip,
phone,
fax,
phonew1,
phonecell,
users.notes,
state_license_number,
abook.title as abook_title";
if ($this->_includeUsername) {
$sql .= ", username";
}
$sql .= "
FROM users
LEFT JOIN list_options as abook ON abook.option_id = users.abook_type";
$whereClause = FhirSearchWhereClauseBuilder::build($search, $isAndCondition);
$sql .= $whereClause->getFragment();
$sqlBindArray = $whereClause->getBoundValues();
$statementResults = QueryUtils::sqlStatementThrowException($sql, $sqlBindArray);
$processingResult = new ProcessingResult();
while ($row = sqlFetchArray($statementResults)) {
$resultRecord = $this->createResultRecordFromDatabaseResult($row);
$processingResult->addData($resultRecord);
}
return $processingResult;
}
/**
* Returns a list of users matching optional search criteria.
* Search criteria is conveyed by array where key = field/column name, value = field value.
* If no search criteria is provided, all records are returned.
*
* @param $search search array parameters
* @param $isAndCondition specifies if AND condition is used for multiple criteria. Defaults to true.
* @return array of users that matched the results.
*/
public function getAll($search = array(), $isAndCondition = true)
{
$sqlBindArray = array();
$sql = "SELECT id,
uuid,
users.title as title,
fname,
lname,
mname,
federaltaxid,
federaldrugid,
upin,
facility_id,
facility,
npi,
email,
active,
specialty,
billname,
url,
assistant,
organization,
valedictory,
street,
streetb,
city,
state,
zip,
phone,
fax,
phonew1,
phonecell,
users.notes,
state_license_number,
abook.title as abook_title";
if ($this->_includeUsername) {
$sql .= ", username";
}
$sql .= "
FROM users
LEFT JOIN list_options as abook ON abook.option_id = users.abook_type";
if (!empty($search)) {
$sql .= ' AND ';
$whereClauses = array();
foreach ($search as $fieldName => $fieldValue) {
array_push($whereClauses, $fieldName . ' = ?');
array_push($sqlBindArray, $fieldValue);
}
$sqlCondition = ($isAndCondition == true) ? 'AND' : 'OR';
$sql .= implode(' ' . $sqlCondition . ' ', $whereClauses);
}
$statementResults = sqlStatement($sql, $sqlBindArray);
$results = [];
while ($row = sqlFetchArray($statementResults)) {
$results[] = $this->createResultRecordFromDatabaseResult($row);
}
return $results;
}
/**
* @return array id of User
*/
public function getIdByUsername($username)
{
$id = sqlQuery("SELECT `id` FROM `users` WHERE BINARY `username` = ?", [$username]);
if (!empty($id['id'])) {
return $id['id'];
} else {
return false;
}
}
/**
* Allows any mapping data conversion or other properties needed by a service to be returned.
* @param $row The record returned from the database
*/
protected function createResultRecordFromDatabaseResult($row)
{
$uuidFields = $this->getUuidFields();
if (empty($uuidFields)) {
return $row;
} else {
// convert all of our byte columns to strings
foreach ($uuidFields as $fieldName) {
if (isset($row[$fieldName])) {
$row[$fieldName] = UuidRegistry::uuidToString($row[$fieldName]);
}
}
}
return $row;
}
}