View source
<?php
namespace Drupal\user\Form;
use Drupal\Component\Utility\EmailValidatorInterface;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Flood\FloodInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Render\Element\Email;
use Drupal\Core\TypedData\TypedDataManagerInterface;
use Drupal\user\UserInterface;
use Drupal\user\UserStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class UserPasswordForm extends FormBase {
protected $userStorage;
protected $languageManager;
protected $flood;
protected $typedDataManager;
protected $emailValidator;
public function __construct(UserStorageInterface $user_storage, LanguageManagerInterface $language_manager, ConfigFactory $config_factory, FloodInterface $flood, TypedDataManagerInterface $typed_data_manager = NULL, EmailValidatorInterface $email_validator = NULL) {
$this->userStorage = $user_storage;
$this->languageManager = $language_manager;
$this->configFactory = $config_factory;
$this->flood = $flood;
if (is_null($typed_data_manager)) {
@trigger_error('Calling ' . __METHOD__ . ' without the $typed_data_manager argument is deprecated in drupal:9.2.0 and will be required in drupal:10.0.0. See https://www.drupal.org/node/3189310', E_USER_DEPRECATED);
$typed_data_manager = \Drupal::typedDataManager();
}
$this->typedDataManager = $typed_data_manager;
if (is_null($email_validator)) {
@trigger_error('Calling ' . __METHOD__ . ' without the $email_validator argument is deprecated in drupal:9.2.0 and will be required in drupal:10.0.0. See https://www.drupal.org/node/3189310', E_USER_DEPRECATED);
$email_validator = \Drupal::service('email.validator');
}
$this->emailValidator = $email_validator;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager')
->getStorage('user'), $container
->get('language_manager'), $container
->get('config.factory'), $container
->get('flood'), $container
->get('typed_data_manager'), $container
->get('email.validator'));
}
public function getFormId() {
return 'user_pass';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['name'] = [
'#type' => 'textfield',
'#title' => $this
->t('Username or email address'),
'#size' => 60,
'#maxlength' => max(UserInterface::USERNAME_MAX_LENGTH, Email::EMAIL_MAX_LENGTH),
'#required' => TRUE,
'#attributes' => [
'autocorrect' => 'off',
'autocapitalize' => 'off',
'spellcheck' => 'false',
'autofocus' => 'autofocus',
],
];
$user = $this
->currentUser();
if ($user
->isAuthenticated()) {
$form['name']['#type'] = 'value';
$form['name']['#value'] = $user
->getEmail();
$form['mail'] = [
'#prefix' => '<p>',
'#markup' => $this
->t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the email.', [
'%email' => $user
->getEmail(),
]),
'#suffix' => '</p>',
];
}
else {
$form['mail'] = [
'#prefix' => '<p>',
'#markup' => $this
->t('Password reset instructions will be sent to your registered email address.'),
'#suffix' => '</p>',
];
$form['name']['#default_value'] = $this
->getRequest()->query
->get('name');
}
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Submit'),
];
$form['#cache']['contexts'][] = 'url.query_args';
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
$flood_config = $this->configFactory
->get('user.flood');
if (!$this->flood
->isAllowed('user.password_request_ip', $flood_config
->get('ip_limit'), $flood_config
->get('ip_window'))) {
$form_state
->setErrorByName('name', $this
->t('Too many password recovery requests from your IP address. It is temporarily blocked. Try again later or contact the site administrator.'));
return;
}
$this->flood
->register('user.password_request_ip', $flood_config
->get('ip_window'));
$name = trim($form_state
->getValue('name'));
$definition = BaseFieldDefinition::create('string')
->addConstraint('UserName', []);
$data = $this->typedDataManager
->create($definition);
$data
->setValue($name);
$violations = $data
->validate();
if ($violations
->count() > 0 && !$this->emailValidator
->isValid($name)) {
$form_state
->setErrorByName('name', $this
->t("The username or email address is invalid."));
return;
}
$users = $this->userStorage
->loadByProperties([
'mail' => $name,
]);
if (empty($users)) {
$users = $this->userStorage
->loadByProperties([
'name' => $name,
]);
}
$account = reset($users);
if ($account && $account
->id() && $account
->isActive()) {
$identifier = $account
->id();
if (!$this->flood
->isAllowed('user.password_request_user', $flood_config
->get('user_limit'), $flood_config
->get('user_window'), $identifier)) {
return;
}
$this->flood
->register('user.password_request_user', $flood_config
->get('user_window'), $identifier);
$form_state
->setValueForElement([
'#parents' => [
'account',
],
], $account);
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$account = $form_state
->getValue('account');
if ($account) {
$mail = _user_mail_notify('password_reset', $account);
if (!empty($mail)) {
$this
->logger('user')
->notice('Password reset instructions mailed to %name at %email.', [
'%name' => $account
->getAccountName(),
'%email' => $account
->getEmail(),
]);
}
}
else {
$this
->logger('user')
->notice('Password reset form was submitted with an unknown or inactive account: %name.', [
'%name' => $form_state
->getValue('name'),
]);
}
$this
->messenger()
->addStatus($this
->t('If %identifier is a valid account, an email will be sent with instructions to reset your password.', [
'%identifier' => $form_state
->getValue('name'),
]));
$form_state
->setRedirect('<front>');
}
}