Elgg  Version 7.1
Accounts.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Users;
4 
5 use Elgg\Config;
6 use Elgg\Email;
15 use Symfony\Component\Mime\Address;
16 
20 class Accounts {
21 
32  public function __construct(
33  protected Config $config,
34  protected Translator $translator,
35  protected PasswordService $passwords,
36  protected EventsService $events,
37  protected EmailService $email,
38  protected PersistentLoginService $persistentLogin,
39  ) {
40  }
41 
55  public function validateAccountData(string $username, string|array $password, string $name, string $email, bool $allow_multiple_emails = false): ValidationResults {
57 
58  if (empty($name)) {
59  $error = $this->translator->translate('registration:noname');
60  $results->fail('name', $name, $error);
61  } else {
62  $results->pass('name', $name);
63  }
64 
65  try {
66  $this->assertValidEmail($email, !$allow_multiple_emails);
67 
68  $results->pass('email', $email);
69  } catch (RegistrationException $ex) {
70  $results->fail('email', $email, $ex->getMessage());
71  }
72 
73  try {
74  $this->assertValidPassword($password);
75 
76  $results->pass('password', $password);
77  } catch (RegistrationException $ex) {
78  $results->fail('password', $password, $ex->getMessage());
79  }
80 
81  try {
82  $this->assertValidUsername($username, true);
83 
84  $results->pass('username', $username);
85  } catch (RegistrationException $ex) {
86  $results->fail('username', $username, $ex->getMessage());
87  }
88 
89  return $results;
90  }
91 
104  public function assertValidAccountData(string $username, string|array $password, string $name, string $email, bool $allow_multiple_emails = false): void {
105  $results = $this->validateAccountData($username, $password, $name, $email, $allow_multiple_emails);
106 
107  foreach ($results->all() as $result) {
108  if (!$result->isValid()) {
109  throw new RegistrationException($result->getError());
110  }
111  }
112  }
113 
130  public function register(array $params = []): \ElggUser {
131  $username = (string) elgg_extract('username', $params);
132  $password = (string) elgg_extract('password', $params);
133  $name = (string) elgg_extract('name', $params);
134  $email = (string) elgg_extract('email', $params);
135  $subtype = elgg_extract('subtype', $params);
136  $language = (string) elgg_extract('language', $params, $this->translator->getCurrentLanguage());
137  $allow_multiple_emails = (bool) elgg_extract('allow_multiple_emails', $params, false);
138  $validated = (bool) elgg_extract('validated', $params, true);
139 
140  $this->assertValidAccountData($username, $password, $name, $email, $allow_multiple_emails);
141 
142  // Create user
143  $constructor = \ElggUser::class;
144  if (isset($subtype)) {
146  if ($class && class_exists($class) && is_subclass_of($class, \ElggUser::class)) {
147  $constructor = $class;
148  }
149  }
150 
152  $user = new $constructor();
153 
154  if (isset($subtype)) {
155  $user->setSubtype($subtype);
156  }
157 
158  $user->username = $username;
159  $user->email = $email;
160  $user->name = $name;
161  $user->language = $language;
162 
163  if (!$user->save()) {
164  throw new RegistrationException($this->translator->translate('registerbad'));
165  }
166 
167  // doing this after save to prevent metadata save notices on unwritable metadata password_hash
168  $user->setPassword($password);
169 
170  // Turn on email notifications by default
171  $user->setNotificationSetting('email', true);
172 
173  if ($validated) {
174  $user->setValidationStatus(true, 'on_create');
175  }
176 
177  return $user;
178  }
179 
191  public function assertValidUsername(string $username, bool $assert_unregistered = false): void {
192  if (elgg_strlen($username) < $this->config->minusername) {
193  $msg = $this->translator->translate('registration:usernametooshort', [$this->config->minusername]);
194  throw new RegistrationException($msg);
195  }
196 
197  // username in the database has a limit of 128 characters
198  if (strlen($username) > 128) {
199  $msg = $this->translator->translate('registration:usernametoolong', [128]);
200  throw new RegistrationException($msg);
201  }
202 
203  // Whitelist all supported route characters
204  // @see Elgg\Router\RouteRegistrationService::register()
205  // @link https://github.com/Elgg/Elgg/issues/12518
206  // @link https://github.com/Elgg/Elgg/issues/14239
207  $invalid_chars = [];
208  if (preg_match_all('/[^\p{L}\p{M}\p{Nd}._-]+/iu', $username, $invalid_chars)) {
209  throw new RegistrationException($this->translator->translate('registration:invalidchars:route', [implode(',', $invalid_chars[0])]));
210  }
211 
212  // Belts and braces
213  // @todo Tidy into main unicode
214  $blacklist2 = '\'/\\"*& ?#%^(){}[]~?<>;|¬`@+=,:';
215 
216  $blacklist2 = $this->events->triggerResults(
217  'username:character_blacklist',
218  'user',
219  ['blacklist' => $blacklist2],
220  $blacklist2
221  );
222 
223  for ($n = 0; $n < elgg_strlen($blacklist2); $n++) {
224  if (elgg_strpos($username, $blacklist2[$n]) !== false) {
225  $msg = $this->translator->translate('registration:invalidchars', [$blacklist2[$n], $blacklist2]);
226  $msg = htmlspecialchars($msg, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
227  throw new RegistrationException($msg);
228  }
229  }
230 
231  $result = $this->events->triggerResults(
232  'registeruser:validate:username',
233  'all',
234  ['username' => $username],
235  true
236  );
237 
238  if (!$result) {
239  throw new RegistrationException($this->translator->translate('registration:usernamenotvalid'));
240  }
241 
242  if ($assert_unregistered) {
243  $exists = elgg_call(ELGG_IGNORE_ACCESS | ELGG_SHOW_DISABLED_ENTITIES | ELGG_SHOW_DELETED_ENTITIES, function () use ($username) {
244  return elgg_get_user_by_username($username);
245  });
246 
247  if ($exists instanceof \ElggUser) {
248  throw new RegistrationException($this->translator->translate('registration:userexists'));
249  }
250  }
251  }
252 
262  public function assertValidPassword(string|array $password): void {
263  if (is_array($password)) {
264  list($password, $password2) = $password;
265 
266  if (empty($password) || empty($password2)) {
267  throw new RegistrationException(elgg_echo('RegistrationException:EmptyPassword'));
268  }
269 
270  if (strcmp($password, $password2) != 0) {
271  throw new RegistrationException(elgg_echo('RegistrationException:PasswordMismatch'));
272  }
273  }
274 
275  $result = $this->events->triggerResults(
276  'registeruser:validate:password',
277  'all',
278  ['password' => $password],
279  !empty($password)
280  );
281 
282  if (!$result) {
283  throw new RegistrationException($this->translator->translate('registration:passwordnotvalid'));
284  }
285  }
286 
296  public function assertCurrentPassword(\ElggUser $user, string $password): void {
297  if (!$this->passwords->verify($password, $user->password_hash)) {
298  throw new RegistrationException($this->translator->translate('LoginException:PasswordFailure'));
299  }
300  }
301 
311  public function assertValidEmail(string $address, bool $assert_unregistered = false): void {
312  if (!$this->isValidEmail($address)) {
313  throw new RegistrationException($this->translator->translate('registration:notemail'));
314  }
315 
316  $result = $this->events->triggerResults(
317  'registeruser:validate:email',
318  'all',
319  ['email' => $address],
320  true
321  );
322 
323  if (!$result) {
324  throw new RegistrationException($this->translator->translate('registration:emailnotvalid'));
325  }
326 
327  if ($assert_unregistered) {
328  $exists = elgg_call(ELGG_IGNORE_ACCESS | ELGG_SHOW_DISABLED_ENTITIES | ELGG_SHOW_DELETED_ENTITIES, function () use ($address) {
329  return elgg_get_user_by_email($address);
330  });
331 
332  if ($exists instanceof \ElggUser) {
333  throw new RegistrationException($this->translator->translate('registration:dupeemail'));
334  }
335  }
336  }
337 
345  public function isValidEmail(string $address): bool {
346  return filter_var($address, FILTER_VALIDATE_EMAIL) === $address;
347  }
348 
358  public function requestNewEmailValidation(\ElggUser $user, string $email): bool {
359  if (!$this->isValidEmail($email)) {
360  throw new InvalidArgumentException($this->translator->translate('registration:notemail'));
361  }
362 
363  $site = elgg_get_site_entity();
364 
365  $user->new_email = $email;
366 
367  $url = elgg_generate_url('account:email:confirm', [
368  'guid' => $user->guid,
369  ]);
370  $url = elgg_http_get_signed_url($url, '+1 hour');
371 
372  $notification = Email::factory([
373  'from' => $site,
374  'to' => new Address($email, $user->getDisplayName()),
375  'subject' => $this->translator->translate('email:request:email:subject', [], $user->getLanguage()),
376  'body' => $this->translator->translate('email:request:email:body', [
377  $site->getDisplayName(),
378  $url,
379  ], $user->getLanguage()),
380  ]);
381 
382  return $this->email->send($notification);
383  }
384 
393  public function registerAuthenticationFailure(\ElggUser $user): void {
394  $fails = (int) $user->authentication_failures;
395  $fails++;
396 
397  $user->authentication_failures = $fails;
398  $user->{"authentication_failure_{$fails}"} = time();
399  }
400 
409  public function resetAuthenticationFailures(\ElggUser $user): void {
410  $fails = (int) $user->authentication_failures;
411  if (empty($fails)) {
412  return;
413  }
414 
415  for ($n = 1; $n <= $fails; $n++) {
416  unset($user->{"authentication_failure_{$n}"});
417  }
418 
419  unset($user->authentication_failures);
420  }
421 
432  public function isAuthenticationFailureLimitReached(\ElggUser $user, ?int $limit = null, ?int $lifetime = null): bool {
433  $limit = $limit ?? $this->config->authentication_failures_limit;
434  $lifetime = $lifetime ?? $this->config->authentication_failures_lifetime;
435 
436  $fails = (int) $user->authentication_failures;
437  if (empty($fails) || $fails < $limit) {
438  return false;
439  }
440 
441  $failure_count = 0;
442  $min_time = time() - $lifetime;
443  for ($n = $fails; $n > 0; $n--) {
444  $failure_timestamp = $user->{"authentication_failure_{$n}"};
445  if ($failure_timestamp > $min_time) {
446  $failure_count++;
447  }
448 
449  if ($failure_count === $limit) {
450  // Limit reached
451  return true;
452  }
453  }
454 
455  return false;
456  }
457 
467  public function changePassword(\ElggUser $user, string $password): void {
468  $user->setPassword($password);
469  $this->persistentLogin->handlePasswordChange($user);
470  }
471 }
$error
Bad request error.
Definition: 400.php:6
$email
Definition: change_email.php:7
$username
Definition: delete.php:23
if(! $user||! $user->canDelete()) $name
Definition: delete.php:22
$subtype
Definition: delete.php:22
$params
Saves global plugin settings.
Definition: save.php:13
$language
Definition: useradd.php:17
$class
Definition: summary.php:44
$user
Elgg user account settings.
Definition: ban.php:7
Email service.
Events service.
Could not register a new user for whatever reason.
Exception thrown if an argument is not of the expected type.
Password service.
\Elgg\PersistentLoginService
User accounts service.
Definition: Accounts.php:20
assertValidUsername(string $username, bool $assert_unregistered=false)
Simple function which ensures that a username contains only valid characters.
Definition: Accounts.php:191
validateAccountData(string $username, string|array $password, string $name, string $email, bool $allow_multiple_emails=false)
Validate registration details to ensure they can be used to register a new user account.
Definition: Accounts.php:55
assertValidPassword(string|array $password)
Simple validation of a password.
Definition: Accounts.php:262
assertValidAccountData(string $username, string|array $password, string $name, string $email, bool $allow_multiple_emails=false)
Assert that given registration details are valid and can be used to register the user.
Definition: Accounts.php:104
__construct(protected Config $config, protected Translator $translator, protected PasswordService $passwords, protected EventsService $events, protected EmailService $email, protected PersistentLoginService $persistentLogin,)
Constructor.
Definition: Accounts.php:32
assertValidEmail(string $address, bool $assert_unregistered=false)
Simple validation of an email.
Definition: Accounts.php:311
Represents a set of validated parameters.
$config
Advanced site settings, debugging section.
Definition: debugging.php:6
elgg_extract($key, $array, $default=null, bool $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:246
elgg_get_entity_class(string $type, string $subtype)
Return the class name registered as a constructor for an entity of a given type and subtype.
Definition: entities.php:19
elgg_strlen()
Wrapper function for mb_strlen().
Definition: mb_wrapper.php:53
if(! $user||! $user->canEdit()) $password
if(parse_url(elgg_get_site_url(), PHP_URL_PATH) !=='/') if(file_exists(elgg_get_root_path() . 'robots.txt'))
Set robots.txt.
Definition: robots.php:10
$results
Definition: content.php:22