-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.power
More file actions
445 lines (396 loc) · 12.4 KB
/
code.power
File metadata and controls
445 lines (396 loc) · 12.4 KB
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
/**
* Save user details by either creating a new user or updating an existing user.
*
* @param array $credentials User credentials including 'name', 'username', 'email', 'password', and 'password2'.
* @param int $autologin Flag to determine whether to auto-login the user after registration.
* @param array $params Parameters for user activation, password sending, and user registration allowance.
* @param int $mode Mode of registration: 1 = Site Registration, 0 = Admin Registration, 2 = Custom Helper Method.
*
* @return int User ID on success.
*
* @throws \InvalidArgumentException If required credentials are missing.
* @throws \RuntimeException If the user update or creation fails.
* @throws NoUserIdFoundException If the user is not found.
*
* @since 5.0.3
*/
public static function save(array $credentials, int $autologin = 0,
array $params = ['useractivation' => 0, 'sendpassword' => 1], int $mode = 1): int
{
// can not continue without an email
if (empty($credentials['email']))
{
throw new \InvalidArgumentException(Text::_('Can not save user without email value.'));
}
// Ensure the 'username' key exists in the credentials array, set to an empty string if not provided.
$username = $credentials['username'] ?? $credentials['email'];
// If the user's ID is set and valid, handle the update logic.
if (!empty($credentials['id']) && $credentials['id'] > 0)
{
$userId = $credentials['id'];
$email = $credentials['email'];
// Fetch existing user by email and username.
$existingEmailUserId = static::getUserIdByEmail($email);
$existingUsernameId = static::getUserIdByUsername($username);
// Validate that we aren't attempting to update other users or reuse another user's email/username.
if (
($existingEmailUserId && $existingEmailUserId != $userId) ||
($existingUsernameId && $existingUsernameId != $userId) ||
($existingEmailUserId && $existingUsernameId && $existingEmailUserId != $existingUsernameId)
) {
throw new NoUserIdFoundException(
Text::sprintf(
'User ID mismatch detected when trying to save %s (%s) credentials.',
$username,
$email
)
);
}
// Update the existing user.
return static::update($credentials);
}
// Create a new user if no existing user is found.
return static::create($credentials, $autologin, $params, $mode);
}
/**
* Create a user and update the given table.
*
* @param array $credentials User credentials including 'name', 'username', 'email', 'password', and 'password2'.
* @param int $autologin Flag to determine whether to auto-login the user after registration.
* @param array $params Parameters for user activation, password sending, and user registration allowance.
* @param int $mode Mode of registration: 1 = Site Registration, 0 = Admin Registration, 2 = Custom Helper Method.
*
* @return int User ID on success.
*
* @throws \RuntimeException If user creation fails.
* @throws NoUserIdFoundException If the user is not found.
*
* @since 5.0.3
*/
public static function create(array $credentials, int $autologin = 0,
array $params = ['useractivation' => 0, 'sendpassword' => 1], int $mode = 1): int
{
$lang = Factory::getLanguage();
$lang->load('com_users', JPATH_SITE, 'en-GB', true);
// Handle custom registration mode
if ($mode === 2 && method_exists(ComponentbuilderHelper::class, 'registerUser'))
{
$params['autologin'] = $autologin;
$userId = ComponentbuilderHelper::registerUser($credentials, $params);
if (is_numeric($userId))
{
return $userId;
}
throw new NoUserIdFoundException(Text::_('User creation failed!'));
}
// Check if we have params/config
if (ArrayHelper::check($params))
{
// Make changes to user config
foreach ($params as $param => $set)
{
// If you know of a better path, let me know
$params[$param] = Component::setParams($param, $set, 'com_users');
}
}
// Fallback to Site Registrations if mode is set to 2 but the method doesn't exist
$mode = $mode === 2 ? 1 : $mode;
// Load the appropriate user model
$model = static::getModelByMode($mode);
// Set default values for missing credentials
$credentials['username'] = $credentials['username'] ?? $credentials['email'];
// Prepare user data
$data = static::prepareUserData($credentials, $mode);
// Set form path (bug fix for Joomla)
static::setFormPathForUserClass($mode);
// Handle user creation
$userId = $mode === 1 ? $model->register($data) : static::adminRegister($model, $data);
// Check if we have params
if (ArrayHelper::check($params))
{
// Change user params/config back
foreach ($params as $param => $set)
{
// If you know of a better path, let me know
Component::setParams($param, $set, 'com_users');
}
}
if (!$userId)
{
$current_user = Factory::getApplication()->getIdentity();
// only allow those with access to Users to ignore errors
if ($current_user->authorise('core.manage', 'com_users'))
{
$userId = static::getUserIdByUsername($credentials['username']);
}
}
if (is_numeric($userId) && $userId > 0)
{
// Handle post-registration processes
return static::handlePostRegistration($userId, $autologin, $credentials);
}
$error_messages = '';
if (method_exists($model, 'getError'))
{
$errors = $model->getError();
if (!empty($errors))
{
if (is_array($errors))
{
$error_messages = '<br>' . implode('<br>', $errors);
}
elseif (is_string($errors))
{
$error_messages = '<br>' . $errors;
}
}
}
throw new NoUserIdFoundException(
Text::sprintf('User %s (%s) creation failed!%s',
(string) $credentials['username'],
(string) $credentials['email'],
$error_messages
)
);
}
/**
* Update user details.
*
* @param array $userDetails Array containing user details to be updated.
*
* @return int Updated user ID on success.
*
* @throws \RuntimeException If user update fails.
*
* @since 5.0.3
*/
public static function update(array $userDetails): int
{
$lang = Factory::getLanguage();
$lang->load('com_users', JPATH_ADMINISTRATOR, 'en-GB', true);
$model = Component::getModel('User', 'Administrator', 'com_users');
// Set default values for missing credentials
$userDetails['username'] = $userDetails['username'] ?? $userDetails['email'];
// Prepare user data for update
$data = [
'id' => $userDetails['id'],
'username' => $userDetails['username'],
'name' => $userDetails['name'],
'email' => $userDetails['email'],
'password' => $userDetails['password'] ?? null,
'password2' => $userDetails['password2'] ?? null,
'block' => 0
];
// set groups if found
if (isset($userDetails['groups']) && ArrayHelper::check($userDetails['groups']))
{
$data['groups'] = $userDetails['groups'];
}
// Update the user
if ($model->save($data))
{
return $userDetails['id'];
}
$error_messages = '';
if (method_exists($model, 'getError'))
{
$errors = $model->getError();
if (!empty($errors))
{
if (is_array($errors))
{
$error_messages = '<br>' . implode('<br>', $errors);
}
elseif (is_string($errors))
{
$error_messages = '<br>' . $errors;
}
}
}
throw new \RuntimeException(
Text::sprintf('Update of user %s (%s) failed!%s',
(string) $userDetails['username'],
(string) $userDetails['email'],
(string) $error_messages
)
);
}
/**
* Method to get an instance of a user for the given id.
*
* @param int $id The id
*
* @return User
*
* @since 5.0.3
*/
public static function getUserById(int $id): User
{
return new User($id);
}
/**
* Retrieve the user ID by username.
*
* @param string $username The username to check.
*
* @return int|null The user ID if the user exists, null otherwise.
*
* @since 5.0.3
*/
public static function getUserIdByUsername(string $username): ?int
{
$userId = JoomlaUserHelper::getUserId($username);
return $userId ?: null;
}
/**
* Retrieve the user ID by email.
*
* @param string $email The email address to check.
*
* @return int|null The user ID if the user exists, null otherwise.
*
* @since 5.0.3
*/
public static function getUserIdByEmail(string $email): ?int
{
// Initialise some variables
$db = Factory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('id'))
->from($db->quoteName('#__users'))
->where($db->quoteName('email') . ' = :email')
->bind(':email', $email)
->setLimit(1);
$db->setQuery($query);
$userId = $db->loadResult();
return $userId ?: null;
}
/**
* Load the correct user model based on the registration mode.
*
* @param int $mode The registration mode.
*
* @return BaseDatabaseModel The appropriate user model.
*
* @since 5.0.3
*/
protected static function getModelByMode(int $mode): BaseDatabaseModel
{
if ($mode === 1)
{
return Component::getModel('Registration', 'Site', 'com_users');
}
return Component::getModel('User', 'Administrator', 'com_users');
}
/**
* Prepare user data array for registration or update.
*
* @param array $credentials User credentials.
* @param int $mode The registration mode.
*
* @return array The prepared user data array.
*
* @since 5.0.3
*/
protected static function prepareUserData(array $credentials, int $mode)
{
$data = [
'username' => $credentials['username'],
'name' => $credentials['name'],
'block' => 0
];
if ($mode === 1)
{
$data['email1'] = $credentials['email'];
}
else
{
$data['email'] = $credentials['email'];
$data['registerDate'] = Factory::getDate()->toSql();
}
if ($mode === 1 && empty($credentials['password']))
{
$credentials['password'] = StringHelper::random(10);
$credentials['password2'] = $credentials['password'];
}
if (!empty($credentials['password']) && !empty($credentials['password2']))
{
$data['password1'] = $credentials['password'];
$data['password2'] = $credentials['password2'];
}
if ($mode === 0 && isset($credentials['groups']) && ArrayHelper::check($credentials['groups']))
{
$data['groups'] = $credentials['groups'];
}
return $data;
}
/**
* Handle the registration process for admin mode.
*
* @param BaseDatabaseModel $model The user model.
* @param array $data The user data.
*
* @return int The ID of the created user.
*
* @since 5.0.3
*/
private static function adminRegister(BaseDatabaseModel $model, array $data): int
{
$model->save($data);
return $model->getState('user.id', 0);
}
/**
* Handle post-registration processes like auto-login.
*
* @param int $userId The ID of the created user.
* @param int $autologin Flag to determine whether to auto-login the user.
* @param array $credentials The user credentials.
*
* @return int The user ID on success.
*
* @since 5.0.3
*/
private static function handlePostRegistration(int $userId, int $autologin, array $credentials): int
{
// make sure user is it the correct groups
if ($userId > 0 && !empty($credentials['groups']))
{
try
{
JoomlaUserHelper::setUserGroups($userId, $credentials['groups']);
}
catch (\Exception $e)
{
// we might need say something
}
}
if ($autologin && !empty($credentials['password']))
{
try
{
Factory::getApplication()->login($credentials);
}
catch (\Exception $e)
{
// we might need to redirect here?
}
}
return $userId;
}
/**
* Address bug on \Joomla\CMS\MVC\Model\FormBehaviorTrait Line 76
* The use of JPATH_COMPONENT cause it to load the
* active component forms and fields, which breaks the registration model.
*
* @param int $mode
*
* @since 5.0.3
*/
private static function setFormPathForUserClass(int $mode): void
{
if ($mode == 1) // 1 = use of the Registration Model
{
// Get the form.
Form::addFormPath(JPATH_ROOT . '/components/com_users/forms');
}
}