email_registration-8.x-1.1/email_registration.module
email_registration.module
<?php
/**
* @file
* Allows users to register with an email address as their username.
*/
use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Email;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\user\UserInterface;
/**
* Implements hook_help().
*/
function email_registration_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.email_registration':
$text = file_get_contents(__DIR__ . '/README.md');
if (!\Drupal::moduleHandler()->moduleExists('markdown')) {
return '<pre>' . Html::escape($text) . '</pre>';
}
else {
// Use the Markdown filter to render the README.
$filter_manager = \Drupal::service('plugin.manager.filter');
$settings = \Drupal::configFactory()->get('markdown.settings')->getRawData();
$config = ['settings' => $settings];
$filter = $filter_manager->createInstance('markdown', $config);
return $filter->process($text, 'en');
}
}
return NULL;
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function email_registration_user_presave(UserInterface $account) {
$newAccountName = $accountName = $account->getAccountName();
// Other modules (including this one) might want to alter the username:
Drupal::moduleHandler()->alter('email_registration_name', $newAccountName, $account);
// Only set the new name, if it was altered:
if ($accountName !== $newAccountName) {
// Ensure it is unique:
$newAccountName = email_registration_unique_username($newAccountName, (int) $account->id());
$account->setUsername($newAccountName);
}
// @deprecated START:
// @todo Remove in 3.x.
// Don't create a new username if one is already set.
if (empty($accountName) || str_starts_with($accountName, 'email_registration_')) {
// Other modules may implement hook_email_registration_name($edit, $account)
// to generate a username (return a string to be used as the username, NULL
// to have email_registration generate it).
$names = Drupal::moduleHandler()->invokeAll('email_registration_name', [$account]);
// Remove any empty entries.
$names = array_filter($names);
if (!empty($names)) {
// One would expect a single implementation of the hook, but if there
// are multiples out there use the last one.
// If validation is required, the modules need to implement it themselves.
$newAccountName = array_pop($names);
$account->setUsername($newAccountName);
@trigger_error('"hook_email_registration_name()" is deprecated in email_registration:2.0.0 and is removed from email_registration:3.0.0. Use hook_email_registration_name_alter instead. See https://www.drupal.org/project/email_registration/issues/3396028', E_USER_DEPRECATED);
}
}
// @deprecated END.
}
/**
* Implements hook_email_registration_name_alter().
*/
function email_registration_email_registration_name_alter(string &$newAccountName, UserInterface $account) {
if (empty($newAccountName) || str_starts_with($newAccountName, 'email_registration_')) {
// Strip and clean the mail and use it as the new username:
$newAccountName = email_registration_strip_mail_and_cleanup($account->getEmail());
}
}
/**
* Makes the username unique.
*
* Given a starting point for a Drupal username (e.g. the name portion of an
* email address) return a legal, unique Drupal username. This function is
* designed to work on the results of the /user/register or /admin/people/create
* forms which have already called user_validate_name, valid_email_address
* or a similar function. If your custom code is creating users, you should
* ensure that the email/name is already validated using something like that.
*
* @param string $name
* A name from which to base the final user name.
* May contain illegal characters; these will be stripped.
* @param int $uid
* (optional) Uid to ignore when searching for unique user
* (e.g. if we update the username after the {users} row is inserted).
*
* @return string
* A unique user name based on $name.
*
* @see user_validate_name()
*/
function email_registration_unique_username($name, $uid = 0) {
// Iterate until we find a unique name.
$i = 0;
$database = \Drupal::database();
do {
$new_name = empty($i) ? $name : $name . '_' . $i;
$found = $database->queryRange("SELECT uid from {users_field_data} WHERE uid <> :uid AND name = :name", 0, 1, [
':uid' => $uid,
':name' => $new_name,
])->fetchAssoc();
$i++;
} while (!empty($found));
return $new_name;
}
/**
* Cleans up username.
*
* Run username sanitation, e.g.:
* Replace two or more spaces with a single underscore
* Strip illegal characters.
*
* @param string $name
* The username to be cleaned up.
*
* @return string
* Cleaned up username.
*/
function email_registration_cleanup_username($name) {
// Strip illegal characters.
$name = preg_replace('/[^\x{80}-\x{F7} a-zA-Z0-9@_.\'-]/', '', $name);
// Strip leading and trailing spaces.
$name = trim($name);
// Convert any other series of spaces to a single underscore.
$name = preg_replace('/\s+/', '_', $name);
// If there's nothing left use a default.
$name = ('' === $name) ? t('user') : $name;
// Truncate to a reasonable size.
$name = (mb_strlen($name) > (UserInterface::USERNAME_MAX_LENGTH - 10)) ? mb_substr($name, 0, UserInterface::USERNAME_MAX_LENGTH - 11) : $name;
return $name;
}
/**
* Strips down the email-address to a username and cleans it up.
*
* Strips everything after and including the '@' and cleans the username (e.g.
* stripping illegal characters, spaces, etc.).
*
* @param string $mail
* The email-address to be stripped and cleaned up.
*
* @return string
* A username converted from an email-address.
*/
function email_registration_strip_mail_and_cleanup($mail) {
// Strip the email:
$username = preg_replace('/@.*$/', '', $mail);
// Clean up the resulting username:
return email_registration_cleanup_username($username);
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function email_registration_form_user_form_alter(&$form, FormStateInterface $form_state) {
if (isset($form['account']['name']) && isset($form['account']['mail'])) {
// Make the mail field always required with this module:
$form['account']['mail']['#required'] = TRUE;
$currentUser = \Drupal::currentUser();
/** @var \Drupal\user\UserInterface $user */
$user = $form_state->getFormObject()->getEntity();
// See if the current user has the name edit permissions:
$hasUsernameEditPermissions = ($currentUser->hasPermission('change own username') && $currentUser->id() === $user->id()) || $currentUser->hasPermission('administer users');
// Disallow users to edit a username if they don't have the right
// permissions:
if (!$hasUsernameEditPermissions) {
// Disable the username field:
$form['account']['name']['#type'] = 'value';
}
// If the user is new, we can be sure, we are on the user create page:
if ($user->isNew()) {
// Modify the form validation, so we are able to leave the name value
// empty:
array_unshift($form['#validate'], 'email_registration_validate_user_form_name');
$form['account']['name']['#required'] = FALSE;
// If the user has the permissions to edit the username field, let them
// know, what to expect:
if ($hasUsernameEditPermissions) {
$form['account']['name']['#description'] = t('Leave empty to generate the username from the email address.<br>') . $form['account']['name']['#description'];
}
}
}
}
/**
* The email_registration_form_user_form_alter validation callback.
*
* This is used to set a temporary username, if the username is empty. Since
* core doesn't allow us to have the username empty.
*/
function email_registration_validate_user_form_name(&$form, FormStateInterface $form_state) {
$username = $form_state->getValue('name');
if (empty($username)) {
// Create a temporary username:
$form_state->setValue('name', \Drupal::service('email_registration.username_generator')->generateRandomUsername());
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function email_registration_form_user_pass_alter(&$form, FormStateInterface $form_state) {
$loginWithBoth = \Drupal::config('email_registration.settings')->get('login_with_username');
if (!$loginWithBoth) {
$form['name']['#title'] = t('Email address');
// Only convert textfields to email fields. This field is a hidden value
// when you are already logged in.
if ($form['name']['#type'] === 'textfield') {
// Allow client side validation of input format.
$form['name']['#type'] = 'email';
$form['name']['#maxlength'] = Email::EMAIL_MAX_LENGTH;
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function email_registration_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
$config = \Drupal::config('email_registration.settings');
$login_with_username = $config->get('login_with_username');
$form['name']['#title'] = $login_with_username ? t('Email address or username') : t('Email address');
$form['name']['#description'] = $login_with_username ? t('Enter your email address or username.') : t('Enter your email address.');
$form['name']['#element_validate'][] = 'email_registration_user_login_validate';
$form['pass']['#description'] = t('Enter the password that accompanies your email address.');
// Allow client side validation of input format.
$form['name']['#type'] = $login_with_username ? 'textfield' : 'email';
$form['name']['#maxlength'] = Email::EMAIL_MAX_LENGTH;
// Make sure the login form cache is invalidated when the setting changes.
$form['#cache']['tags'][] = 'config:email_registration.settings';
}
/**
* Form element validation handler for the user login form.
*
* Allows users to authenticate by email, which is our preferred method.
*/
function email_registration_user_login_validate($form, FormStateInterface $form_state) {
$email = trim($form_state->getValue('name') ?? '');
if (!empty($email)) {
$user = user_load_by_mail($email);
$config = \Drupal::config('email_registration.settings');
if ($user) {
if (!$user->isActive()) {
$form_state->setErrorByName(
'name',
t('The account with email address %name has not been activated or is blocked.', ['%name' => $email])
);
}
$form_state->setValue('name', $user->getAccountName());
}
elseif (!$config->get('login_with_username')) {
$user_input = $form_state->getUserInput();
$query = isset($user_input['name']) ? ['name' => $user_input['name']] : [];
$form_state->setErrorByName(
'name',
t('Unrecognized email address or password. <a href=":password">Forgot your password?</a>', [
':password' => Url::fromRoute('user.pass', [], ['query' => $query])->toString(),
])
);
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function email_registration_form_user_admin_settings_alter(&$form, FormStateInterface $form_state) {
$config = \Drupal::config('email_registration.settings');
$form['email_registration'] = [
'#type' => 'details',
'#title' => t('Email Registration'),
'#open' => TRUE,
];
$form['email_registration']['login_with_username'] = [
'#type' => 'checkbox',
'#title' => t('Allow log in with email address or username.'),
'#description' => t('Allow users to log in with either their email address or their username.'),
'#default_value' => $config->get('login_with_username'),
];
$form['#submit'][] = 'email_registration_form_user_admin_settings_submit';
}
/**
* Submit function for user_admin_settings to save our variable.
*
* @see email_registration_form_user_admin_settings_alter()
*/
function email_registration_form_user_admin_settings_submit(array &$form, FormStateInterface $form_state) {
\Drupal::configFactory()->getEditable('email_registration.settings')
->set('login_with_username', $form_state->getValue('login_with_username'))
->save();
}
