annotate core/modules/user/src/AccountForm.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\user;
Chris@0 4
Chris@0 5 use Drupal\Component\Datetime\TimeInterface;
Chris@0 6 use Drupal\Component\Utility\Crypt;
Chris@0 7 use Drupal\Core\Entity\ContentEntityForm;
Chris@0 8 use Drupal\Core\Entity\EntityConstraintViolationListInterface;
Chris@17 9 use Drupal\Core\Entity\EntityRepositoryInterface;
Chris@0 10 use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
Chris@0 11 use Drupal\Core\Form\FormStateInterface;
Chris@0 12 use Drupal\Core\Language\LanguageInterface;
Chris@0 13 use Drupal\Core\Language\LanguageManagerInterface;
Chris@0 14 use Drupal\language\ConfigurableLanguageManagerInterface;
Chris@0 15 use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUser;
Chris@0 16 use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUserAdmin;
Chris@0 17 use Symfony\Component\DependencyInjection\ContainerInterface;
Chris@0 18
Chris@0 19 /**
Chris@0 20 * Form controller for the user account forms.
Chris@0 21 */
Chris@0 22 abstract class AccountForm extends ContentEntityForm {
Chris@0 23
Chris@0 24 /**
Chris@0 25 * The language manager.
Chris@0 26 *
Chris@0 27 * @var \Drupal\Core\Language\LanguageManagerInterface
Chris@0 28 */
Chris@0 29 protected $languageManager;
Chris@0 30
Chris@0 31 /**
Chris@0 32 * Constructs a new EntityForm object.
Chris@0 33 *
Chris@17 34 * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
Chris@17 35 * The entity repository.
Chris@0 36 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
Chris@0 37 * The language manager.
Chris@0 38 * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
Chris@0 39 * The entity type bundle service.
Chris@0 40 * @param \Drupal\Component\Datetime\TimeInterface $time
Chris@0 41 * The time service.
Chris@0 42 */
Chris@17 43 public function __construct(EntityRepositoryInterface $entity_repository, LanguageManagerInterface $language_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
Chris@17 44 parent::__construct($entity_repository, $entity_type_bundle_info, $time);
Chris@0 45 $this->languageManager = $language_manager;
Chris@0 46 }
Chris@0 47
Chris@0 48 /**
Chris@0 49 * {@inheritdoc}
Chris@0 50 */
Chris@0 51 public static function create(ContainerInterface $container) {
Chris@0 52 return new static(
Chris@17 53 $container->get('entity.repository'),
Chris@0 54 $container->get('language_manager'),
Chris@0 55 $container->get('entity_type.bundle.info'),
Chris@0 56 $container->get('datetime.time')
Chris@0 57 );
Chris@0 58 }
Chris@0 59
Chris@0 60 /**
Chris@0 61 * {@inheritdoc}
Chris@0 62 */
Chris@0 63 public function form(array $form, FormStateInterface $form_state) {
Chris@0 64 /** @var \Drupal\user\UserInterface $account */
Chris@0 65 $account = $this->entity;
Chris@0 66 $user = $this->currentUser();
Chris@0 67 $config = \Drupal::config('user.settings');
Chris@0 68 $form['#cache']['tags'] = $config->getCacheTags();
Chris@0 69
Chris@0 70 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
Chris@18 71
Chris@18 72 // Check for new account.
Chris@0 73 $register = $account->isAnonymous();
Chris@18 74
Chris@18 75 // For a new account, there are 2 sub-cases:
Chris@18 76 // $self_register: A user creates their own, new, account
Chris@18 77 // (path '/user/register')
Chris@18 78 // $admin_create: An administrator creates a new account for another user
Chris@18 79 // (path '/admin/people/create')
Chris@18 80 // If the current user is logged in and has permission to create users
Chris@18 81 // then it must be the second case.
Chris@18 82 $admin_create = $register && $account->access('create');
Chris@18 83 $self_register = $register && !$admin_create;
Chris@0 84
Chris@0 85 // Account information.
Chris@0 86 $form['account'] = [
Chris@0 87 '#type' => 'container',
Chris@0 88 '#weight' => -10,
Chris@0 89 ];
Chris@0 90
Chris@0 91 // The mail field is NOT required if account originally had no mail set
Chris@0 92 // and the user performing the edit has 'administer users' permission.
Chris@0 93 // This allows users without email address to be edited and deleted.
Chris@0 94 // Also see \Drupal\user\Plugin\Validation\Constraint\UserMailRequired.
Chris@0 95 $form['account']['mail'] = [
Chris@0 96 '#type' => 'email',
Chris@0 97 '#title' => $this->t('Email address'),
Chris@0 98 '#description' => $this->t('A valid email address. All emails from the system will be sent to this address. The email address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by email.'),
Chris@18 99 '#required' => !(!$account->getEmail() && $user->hasPermission('administer users')),
Chris@0 100 '#default_value' => (!$register ? $account->getEmail() : ''),
Chris@0 101 ];
Chris@0 102
Chris@0 103 // Only show name field on registration form or user can change own username.
Chris@0 104 $form['account']['name'] = [
Chris@0 105 '#type' => 'textfield',
Chris@0 106 '#title' => $this->t('Username'),
Chris@18 107 '#maxlength' => UserInterface::USERNAME_MAX_LENGTH,
Chris@0 108 '#description' => $this->t("Several special characters are allowed, including space, period (.), hyphen (-), apostrophe ('), underscore (_), and the @ sign."),
Chris@0 109 '#required' => TRUE,
Chris@0 110 '#attributes' => [
Chris@0 111 'class' => ['username'],
Chris@0 112 'autocorrect' => 'off',
Chris@0 113 'autocapitalize' => 'off',
Chris@0 114 'spellcheck' => 'false',
Chris@0 115 ],
Chris@0 116 '#default_value' => (!$register ? $account->getAccountName() : ''),
Chris@18 117 '#access' => $account->name->access('edit'),
Chris@0 118 ];
Chris@0 119
Chris@0 120 // Display password field only for existing users or when user is allowed to
Chris@0 121 // assign a password during registration.
Chris@0 122 if (!$register) {
Chris@0 123 $form['account']['pass'] = [
Chris@0 124 '#type' => 'password_confirm',
Chris@0 125 '#size' => 25,
Chris@0 126 '#description' => $this->t('To change the current user password, enter the new password in both fields.'),
Chris@0 127 ];
Chris@0 128
Chris@0 129 // To skip the current password field, the user must have logged in via a
Chris@0 130 // one-time link and have the token in the URL. Store this in $form_state
Chris@0 131 // so it persists even on subsequent Ajax requests.
Chris@0 132 if (!$form_state->get('user_pass_reset') && ($token = $this->getRequest()->get('pass-reset-token'))) {
Chris@0 133 $session_key = 'pass_reset_' . $account->id();
Chris@0 134 $user_pass_reset = isset($_SESSION[$session_key]) && Crypt::hashEquals($_SESSION[$session_key], $token);
Chris@0 135 $form_state->set('user_pass_reset', $user_pass_reset);
Chris@0 136 }
Chris@0 137
Chris@0 138 // The user must enter their current password to change to a new one.
Chris@0 139 if ($user->id() == $account->id()) {
Chris@0 140 $form['account']['current_pass'] = [
Chris@0 141 '#type' => 'password',
Chris@0 142 '#title' => $this->t('Current password'),
Chris@0 143 '#size' => 25,
Chris@0 144 '#access' => !$form_state->get('user_pass_reset'),
Chris@0 145 '#weight' => -5,
Chris@0 146 // Do not let web browsers remember this password, since we are
Chris@0 147 // trying to confirm that the person submitting the form actually
Chris@0 148 // knows the current one.
Chris@0 149 '#attributes' => ['autocomplete' => 'off'],
Chris@0 150 ];
Chris@0 151 $form_state->set('user', $account);
Chris@0 152
Chris@0 153 // The user may only change their own password without their current
Chris@0 154 // password if they logged in via a one-time login link.
Chris@0 155 if (!$form_state->get('user_pass_reset')) {
Chris@0 156 $form['account']['current_pass']['#description'] = $this->t('Required if you want to change the %mail or %pass below. <a href=":request_new_url" title="Send password reset instructions via email.">Reset your password</a>.', [
Chris@0 157 '%mail' => $form['account']['mail']['#title'],
Chris@0 158 '%pass' => $this->t('Password'),
Chris@0 159 ':request_new_url' => $this->url('user.pass'),
Chris@0 160 ]);
Chris@0 161 }
Chris@0 162 }
Chris@0 163 }
Chris@18 164 elseif (!$config->get('verify_mail') || $admin_create) {
Chris@0 165 $form['account']['pass'] = [
Chris@0 166 '#type' => 'password_confirm',
Chris@0 167 '#size' => 25,
Chris@0 168 '#description' => $this->t('Provide a password for the new account in both fields.'),
Chris@0 169 '#required' => TRUE,
Chris@0 170 ];
Chris@0 171 }
Chris@0 172
Chris@0 173 // When not building the user registration form, prevent web browsers from
Chris@0 174 // autofilling/prefilling the email, username, and password fields.
Chris@17 175 if (!$register) {
Chris@0 176 foreach (['mail', 'name', 'pass'] as $key) {
Chris@0 177 if (isset($form['account'][$key])) {
Chris@0 178 $form['account'][$key]['#attributes']['autocomplete'] = 'off';
Chris@0 179 }
Chris@0 180 }
Chris@0 181 }
Chris@0 182
Chris@18 183 if (!$self_register) {
Chris@0 184 $status = $account->get('status')->value;
Chris@0 185 }
Chris@0 186 else {
Chris@18 187 $status = $config->get('register') == UserInterface::REGISTER_VISITORS ? 1 : 0;
Chris@0 188 }
Chris@0 189
Chris@0 190 $form['account']['status'] = [
Chris@0 191 '#type' => 'radios',
Chris@0 192 '#title' => $this->t('Status'),
Chris@0 193 '#default_value' => $status,
Chris@0 194 '#options' => [$this->t('Blocked'), $this->t('Active')],
Chris@18 195 '#access' => $account->status->access('edit'),
Chris@0 196 ];
Chris@0 197
Chris@0 198 $roles = array_map(['\Drupal\Component\Utility\Html', 'escape'], user_role_names(TRUE));
Chris@0 199
Chris@0 200 $form['account']['roles'] = [
Chris@0 201 '#type' => 'checkboxes',
Chris@0 202 '#title' => $this->t('Roles'),
Chris@0 203 '#default_value' => (!$register ? $account->getRoles() : []),
Chris@0 204 '#options' => $roles,
Chris@0 205 '#access' => $roles && $user->hasPermission('administer permissions'),
Chris@0 206 ];
Chris@0 207
Chris@0 208 // Special handling for the inevitable "Authenticated user" role.
Chris@0 209 $form['account']['roles'][RoleInterface::AUTHENTICATED_ID] = [
Chris@0 210 '#default_value' => TRUE,
Chris@0 211 '#disabled' => TRUE,
Chris@0 212 ];
Chris@0 213
Chris@0 214 $form['account']['notify'] = [
Chris@0 215 '#type' => 'checkbox',
Chris@0 216 '#title' => $this->t('Notify user of new account'),
Chris@18 217 '#access' => $admin_create,
Chris@0 218 ];
Chris@0 219
Chris@0 220 $user_preferred_langcode = $register ? $language_interface->getId() : $account->getPreferredLangcode();
Chris@0 221
Chris@0 222 $user_preferred_admin_langcode = $register ? $language_interface->getId() : $account->getPreferredAdminLangcode(FALSE);
Chris@0 223
Chris@0 224 // Is the user preferred language added?
Chris@0 225 $user_language_added = FALSE;
Chris@0 226 if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
Chris@0 227 $negotiator = $this->languageManager->getNegotiator();
Chris@0 228 $user_language_added = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUser::METHOD_ID, LanguageInterface::TYPE_INTERFACE);
Chris@0 229 }
Chris@0 230 $form['language'] = [
Chris@0 231 '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container',
Chris@0 232 '#title' => $this->t('Language settings'),
Chris@0 233 '#open' => TRUE,
Chris@0 234 // Display language selector when either creating a user on the admin
Chris@0 235 // interface or editing a user account.
Chris@18 236 '#access' => !$self_register,
Chris@0 237 ];
Chris@0 238
Chris@0 239 $form['language']['preferred_langcode'] = [
Chris@0 240 '#type' => 'language_select',
Chris@0 241 '#title' => $this->t('Site language'),
Chris@0 242 '#languages' => LanguageInterface::STATE_CONFIGURABLE,
Chris@0 243 '#default_value' => $user_preferred_langcode,
Chris@0 244 '#description' => $user_language_added ? $this->t("This account's preferred language for emails and site presentation.") : $this->t("This account's preferred language for emails."),
Chris@0 245 // This is used to explain that user preferred language and entity
Chris@0 246 // language are synchronized. It can be removed if a different behavior is
Chris@0 247 // desired.
Chris@0 248 '#pre_render' => ['user_langcode' => [$this, 'alterPreferredLangcodeDescription']],
Chris@0 249 ];
Chris@0 250
Chris@0 251 // Only show the account setting for Administration pages language to users
Chris@0 252 // if one of the detection and selection methods uses it.
Chris@0 253 $show_admin_language = FALSE;
Chris@0 254 if ($account->hasPermission('access administration pages') && $this->languageManager instanceof ConfigurableLanguageManagerInterface) {
Chris@0 255 $negotiator = $this->languageManager->getNegotiator();
Chris@0 256 $show_admin_language = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUserAdmin::METHOD_ID);
Chris@0 257 }
Chris@0 258 $form['language']['preferred_admin_langcode'] = [
Chris@0 259 '#type' => 'language_select',
Chris@0 260 '#title' => $this->t('Administration pages language'),
Chris@0 261 '#languages' => LanguageInterface::STATE_CONFIGURABLE,
Chris@0 262 '#default_value' => $user_preferred_admin_langcode,
Chris@0 263 '#access' => $show_admin_language,
Chris@0 264 '#empty_option' => $this->t('- No preference -'),
Chris@0 265 '#empty_value' => '',
Chris@0 266 ];
Chris@0 267
Chris@0 268 // User entities contain both a langcode property (for identifying the
Chris@0 269 // language of the entity data) and a preferred_langcode property (see
Chris@0 270 // above). Rather than provide a UI forcing the user to choose both
Chris@0 271 // separately, assume that the user profile data is in the user's preferred
Chris@0 272 // language. This entity builder provides that synchronization. For
Chris@0 273 // use-cases where this synchronization is not desired, a module can alter
Chris@0 274 // or remove this item.
Chris@0 275 $form['#entity_builders']['sync_user_langcode'] = '::syncUserLangcode';
Chris@0 276
Chris@0 277 return parent::form($form, $form_state, $account);
Chris@0 278 }
Chris@0 279
Chris@0 280 /**
Chris@0 281 * Alters the preferred language widget description.
Chris@0 282 *
Chris@0 283 * @param array $element
Chris@0 284 * The preferred language form element.
Chris@0 285 *
Chris@0 286 * @return array
Chris@0 287 * The preferred language form element.
Chris@0 288 */
Chris@0 289 public function alterPreferredLangcodeDescription(array $element) {
Chris@0 290 // Only add to the description if the form element has a description.
Chris@0 291 if (isset($element['#description'])) {
Chris@0 292 $element['#description'] .= ' ' . $this->t("This is also assumed to be the primary language of this account's profile information.");
Chris@0 293 }
Chris@0 294 return $element;
Chris@0 295 }
Chris@0 296
Chris@0 297 /**
Chris@0 298 * Synchronizes preferred language and entity language.
Chris@0 299 *
Chris@0 300 * @param string $entity_type_id
Chris@0 301 * The entity type identifier.
Chris@0 302 * @param \Drupal\user\UserInterface $user
Chris@0 303 * The entity updated with the submitted values.
Chris@0 304 * @param array $form
Chris@0 305 * The complete form array.
Chris@0 306 * @param \Drupal\Core\Form\FormStateInterface $form_state
Chris@0 307 * The current state of the form.
Chris@0 308 */
Chris@0 309 public function syncUserLangcode($entity_type_id, UserInterface $user, array &$form, FormStateInterface &$form_state) {
Chris@0 310 $user->getUntranslated()->langcode = $user->preferred_langcode;
Chris@0 311 }
Chris@0 312
Chris@0 313 /**
Chris@0 314 * {@inheritdoc}
Chris@0 315 */
Chris@0 316 public function buildEntity(array $form, FormStateInterface $form_state) {
Chris@0 317 // Change the roles array to a list of enabled roles.
Chris@0 318 // @todo: Alter the form state as the form values are directly extracted and
Chris@0 319 // set on the field, which throws an exception as the list requires
Chris@0 320 // numeric keys. Allow to override this per field. As this function is
Chris@0 321 // called twice, we have to prevent it from getting the array keys twice.
Chris@0 322
Chris@0 323 if (is_string(key($form_state->getValue('roles')))) {
Chris@0 324 $form_state->setValue('roles', array_keys(array_filter($form_state->getValue('roles'))));
Chris@0 325 }
Chris@0 326
Chris@0 327 /** @var \Drupal\user\UserInterface $account */
Chris@0 328 $account = parent::buildEntity($form, $form_state);
Chris@0 329
Chris@0 330 // Translate the empty value '' of language selects to an unset field.
Chris@0 331 foreach (['preferred_langcode', 'preferred_admin_langcode'] as $field_name) {
Chris@0 332 if ($form_state->getValue($field_name) === '') {
Chris@0 333 $account->$field_name = NULL;
Chris@0 334 }
Chris@0 335 }
Chris@0 336
Chris@0 337 // Set existing password if set in the form state.
Chris@0 338 $current_pass = trim($form_state->getValue('current_pass'));
Chris@0 339 if (strlen($current_pass) > 0) {
Chris@0 340 $account->setExistingPassword($current_pass);
Chris@0 341 }
Chris@0 342
Chris@0 343 // Skip the protected user field constraint if the user came from the
Chris@0 344 // password recovery page.
Chris@0 345 $account->_skipProtectedUserFieldConstraint = $form_state->get('user_pass_reset');
Chris@0 346
Chris@0 347 return $account;
Chris@0 348 }
Chris@0 349
Chris@0 350 /**
Chris@0 351 * {@inheritdoc}
Chris@0 352 */
Chris@0 353 protected function getEditedFieldNames(FormStateInterface $form_state) {
Chris@0 354 return array_merge([
Chris@0 355 'name',
Chris@0 356 'pass',
Chris@0 357 'mail',
Chris@0 358 'timezone',
Chris@0 359 'langcode',
Chris@0 360 'preferred_langcode',
Chris@17 361 'preferred_admin_langcode',
Chris@0 362 ], parent::getEditedFieldNames($form_state));
Chris@0 363 }
Chris@0 364
Chris@0 365 /**
Chris@0 366 * {@inheritdoc}
Chris@0 367 */
Chris@0 368 protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
Chris@0 369 // Manually flag violations of fields not handled by the form display. This
Chris@0 370 // is necessary as entity form displays only flag violations for fields
Chris@0 371 // contained in the display.
Chris@0 372 $field_names = [
Chris@0 373 'name',
Chris@0 374 'pass',
Chris@0 375 'mail',
Chris@0 376 'timezone',
Chris@0 377 'langcode',
Chris@0 378 'preferred_langcode',
Chris@17 379 'preferred_admin_langcode',
Chris@0 380 ];
Chris@0 381 foreach ($violations->getByFields($field_names) as $violation) {
Chris@0 382 list($field_name) = explode('.', $violation->getPropertyPath(), 2);
Chris@0 383 $form_state->setErrorByName($field_name, $violation->getMessage());
Chris@0 384 }
Chris@0 385 parent::flagViolations($violations, $form, $form_state);
Chris@0 386 }
Chris@0 387
Chris@0 388 /**
Chris@0 389 * {@inheritdoc}
Chris@0 390 */
Chris@0 391 public function submitForm(array &$form, FormStateInterface $form_state) {
Chris@0 392 parent::submitForm($form, $form_state);
Chris@0 393
Chris@0 394 $user = $this->getEntity($form_state);
Chris@0 395 // If there's a session set to the users id, remove the password reset tag
Chris@0 396 // since a new password was saved.
Chris@0 397 if (isset($_SESSION['pass_reset_' . $user->id()])) {
Chris@0 398 unset($_SESSION['pass_reset_' . $user->id()]);
Chris@0 399 }
Chris@0 400 }
Chris@0 401
Chris@0 402 }