AccountForm.php 15.8 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\user;

5
use Drupal\Component\Datetime\TimeInterface;
6
use Drupal\Core\Entity\ContentEntityForm;
7
use Drupal\Core\Entity\EntityConstraintViolationListInterface;
8
use Drupal\Core\Entity\EntityRepositoryInterface;
9
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
10
use Drupal\Core\Form\FormStateInterface;
11
use Drupal\Core\Language\LanguageInterface;
12 13 14
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\language\ConfigurableLanguageManagerInterface;
use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUser;
15
use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUserAdmin;
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17 18 19 20

/**
 * Form controller for the user account forms.
 */
21
abstract class AccountForm extends ContentEntityForm {
22

23 24 25
  /**
   * The language manager.
   *
26
   * @var \Drupal\Core\Language\LanguageManagerInterface
27 28 29 30
   */
  protected $languageManager;

  /**
31
   * Constructs a new EntityForm object.
32
   *
33 34
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository.
35
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
36
   *   The language manager.
37 38 39 40
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
41
   */
42 43
  public function __construct(EntityRepositoryInterface $entity_repository, LanguageManagerInterface $language_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
44 45 46 47 48 49 50 51
    $this->languageManager = $language_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
52
      $container->get('entity.repository'),
53
      $container->get('language_manager'),
54 55
      $container->get('entity_type.bundle.info'),
      $container->get('datetime.time')
56 57 58
    );
  }

59
  /**
60
   * {@inheritdoc}
61
   */
62
  public function form(array $form, FormStateInterface $form_state) {
63
    /** @var \Drupal\user\UserInterface $account */
64
    $account = $this->entity;
65
    $user = $this->currentUser();
66
    $config = \Drupal::config('user.settings');
67
    $form['#cache']['tags'] = $config->getCacheTags();
68

69
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();
70 71

    // Check for new account.
72
    $register = $account->isAnonymous();
73 74 75 76 77 78 79 80 81 82

    // For a new account, there are 2 sub-cases:
    // $self_register: A user creates their own, new, account
    //   (path '/user/register')
    // $admin_create: An administrator creates a new account for another user
    //   (path '/admin/people/create')
    // If the current user is logged in and has permission to create users
    // then it must be the second case.
    $admin_create = $register && $account->access('create');
    $self_register = $register && !$admin_create;
83 84

    // Account information.
85
    $form['account'] = [
86 87
      '#type'   => 'container',
      '#weight' => -10,
88
    ];
89 90 91

    // The mail field is NOT required if account originally had no mail set
    // and the user performing the edit has 'administer users' permission.
92
    // This allows users without email address to be edited and deleted.
93
    // Also see \Drupal\user\Plugin\Validation\Constraint\UserMailRequired.
94
    $form['account']['mail'] = [
95
      '#type' => 'email',
96 97
      '#title' => $this->t('Email address'),
      '#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.'),
98
      '#required' => !(!$account->getEmail() && $user->hasPermission('administer users')),
99
      '#default_value' => (!$register ? $account->getEmail() : ''),
100
    ];
101 102

    // Only show name field on registration form or user can change own username.
103
    $form['account']['name'] = [
104 105
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
106
      '#maxlength' => UserInterface::USERNAME_MAX_LENGTH,
107
      '#description' => $this->t("Several special characters are allowed, including space, period (.), hyphen (-), apostrophe ('), underscore (_), and the @ sign."),
108
      '#required' => TRUE,
109 110
      '#attributes' => [
        'class' => ['username'],
111 112 113
        'autocorrect' => 'off',
        'autocapitalize' => 'off',
        'spellcheck' => 'false',
114
      ],
115
      '#default_value' => (!$register ? $account->getAccountName() : ''),
116
      '#access' => $account->name->access('edit'),
117
    ];
118 119 120 121

    // Display password field only for existing users or when user is allowed to
    // assign a password during registration.
    if (!$register) {
122
      $form['account']['pass'] = [
123 124
        '#type' => 'password_confirm',
        '#size' => 25,
125
        '#description' => $this->t('To change the current user password, enter the new password in both fields.'),
126
      ];
127 128

      // To skip the current password field, the user must have logged in via a
129 130
      // one-time link and have the token in the URL. Store this in $form_state
      // so it persists even on subsequent Ajax requests.
131 132
      if (!$form_state->get('user_pass_reset') && ($token = $this->getRequest()->get('pass-reset-token'))) {
        $session_key = 'pass_reset_' . $account->id();
133
        $user_pass_reset = isset($_SESSION[$session_key]) && hash_equals($_SESSION[$session_key], $token);
134 135
        $form_state->set('user_pass_reset', $user_pass_reset);
      }
136

137
      // The user must enter their current password to change to a new one.
138
      if ($user->id() == $account->id()) {
139
        $form['account']['current_pass'] = [
140
          '#type' => 'password',
141
          '#title' => $this->t('Current password'),
142
          '#size' => 25,
143
          '#access' => !$form_state->get('user_pass_reset'),
144
          '#weight' => -5,
145 146 147
          // Do not let web browsers remember this password, since we are
          // trying to confirm that the person submitting the form actually
          // knows the current one.
148 149
          '#attributes' => ['autocomplete' => 'off'],
        ];
150
        $form_state->set('user', $account);
151 152 153 154

        // The user may only change their own password without their current
        // password if they logged in via a one-time login link.
        if (!$form_state->get('user_pass_reset')) {
155
          $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>.', [
156 157
            '%mail' => $form['account']['mail']['#title'],
            '%pass' => $this->t('Password'),
158
            ':request_new_url' => $this->url('user.pass'),
159
          ]);
160
        }
161 162
      }
    }
163
    elseif (!$config->get('verify_mail') || $admin_create) {
164
      $form['account']['pass'] = [
165 166
        '#type' => 'password_confirm',
        '#size' => 25,
167
        '#description' => $this->t('Provide a password for the new account in both fields.'),
168
        '#required' => TRUE,
169
      ];
170 171
    }

172 173
    // When not building the user registration form, prevent web browsers from
    // autofilling/prefilling the email, username, and password fields.
174
    if (!$register) {
175
      foreach (['mail', 'name', 'pass'] as $key) {
176 177 178 179 180 181
        if (isset($form['account'][$key])) {
          $form['account'][$key]['#attributes']['autocomplete'] = 'off';
        }
      }
    }

182
    if (!$self_register) {
183
      $status = $account->get('status')->value;
184 185
    }
    else {
186
      $status = $config->get('register') == UserInterface::REGISTER_VISITORS ? 1 : 0;
187 188
    }

189
    $form['account']['status'] = [
190
      '#type' => 'radios',
191
      '#title' => $this->t('Status'),
192
      '#default_value' => $status,
193
      '#options' => [$this->t('Blocked'), $this->t('Active')],
194
      '#access' => $account->status->access('edit'),
195
    ];
196

197
    $roles = array_map(['\Drupal\Component\Utility\Html', 'escape'], user_role_names(TRUE));
198

199
    $form['account']['roles'] = [
200
      '#type' => 'checkboxes',
201
      '#title' => $this->t('Roles'),
202
      '#default_value' => (!$register ? $account->getRoles() : []),
203
      '#options' => $roles,
204
      '#access' => $roles && $user->hasPermission('administer permissions'),
205
    ];
206 207

    // Special handling for the inevitable "Authenticated user" role.
208
    $form['account']['roles'][RoleInterface::AUTHENTICATED_ID] = [
209 210
      '#default_value' => TRUE,
      '#disabled' => TRUE,
211
    ];
212

213
    $form['account']['notify'] = [
214
      '#type' => 'checkbox',
215
      '#title' => $this->t('Notify user of new account'),
216
      '#access' => $admin_create,
217
    ];
218

219
    $user_preferred_langcode = $register ? $language_interface->getId() : $account->getPreferredLangcode();
220

221
    $user_preferred_admin_langcode = $register ? $language_interface->getId() : $account->getPreferredAdminLangcode(FALSE);
222

223 224
    // Is the user preferred language added?
    $user_language_added = FALSE;
225 226
    if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
      $negotiator = $this->languageManager->getNegotiator();
227
      $user_language_added = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUser::METHOD_ID, LanguageInterface::TYPE_INTERFACE);
228
    }
229
    $form['language'] = [
230
      '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container',
231
      '#title' => $this->t('Language settings'),
232
      '#open' => TRUE,
233 234
      // Display language selector when either creating a user on the admin
      // interface or editing a user account.
235
      '#access' => !$self_register,
236
    ];
237

238
    $form['language']['preferred_langcode'] = [
239
      '#type' => 'language_select',
240
      '#title' => $this->t('Site language'),
241
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
242
      '#default_value' => $user_preferred_langcode,
243
      '#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."),
244 245 246 247
      // This is used to explain that user preferred language and entity
      // language are synchronized. It can be removed if a different behavior is
      // desired.
      '#pre_render' => ['user_langcode' => [$this, 'alterPreferredLangcodeDescription']],
248
    ];
249

250 251 252
    // Only show the account setting for Administration pages language to users
    // if one of the detection and selection methods uses it.
    $show_admin_language = FALSE;
253 254 255
    if ($account->hasPermission('access administration pages') && $this->languageManager instanceof ConfigurableLanguageManagerInterface) {
      $negotiator = $this->languageManager->getNegotiator();
      $show_admin_language = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUserAdmin::METHOD_ID);
256
    }
257
    $form['language']['preferred_admin_langcode'] = [
258
      '#type' => 'language_select',
259
      '#title' => $this->t('Administration pages language'),
260
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
261
      '#default_value' => $user_preferred_admin_langcode,
262
      '#access' => $show_admin_language,
263 264
      '#empty_option' => $this->t('- No preference -'),
      '#empty_value' => '',
265
    ];
266

267 268 269 270
    // User entities contain both a langcode property (for identifying the
    // language of the entity data) and a preferred_langcode property (see
    // above). Rather than provide a UI forcing the user to choose both
    // separately, assume that the user profile data is in the user's preferred
271 272 273
    // language. This entity builder provides that synchronization. For
    // use-cases where this synchronization is not desired, a module can alter
    // or remove this item.
274
    $form['#entity_builders']['sync_user_langcode'] = '::syncUserLangcode';
275 276 277 278

    return parent::form($form, $form_state, $account);
  }

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
  /**
   * Alters the preferred language widget description.
   *
   * @param array $element
   *   The preferred language form element.
   *
   * @return array
   *   The preferred language form element.
   */
  public function alterPreferredLangcodeDescription(array $element) {
    // Only add to the description if the form element has a description.
    if (isset($element['#description'])) {
      $element['#description'] .= ' ' . $this->t("This is also assumed to be the primary language of this account's profile information.");
    }
    return $element;
  }

  /**
   * Synchronizes preferred language and entity language.
   *
   * @param string $entity_type_id
   *   The entity type identifier.
   * @param \Drupal\user\UserInterface $user
   *   The entity updated with the submitted values.
   * @param array $form
   *   The complete form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function syncUserLangcode($entity_type_id, UserInterface $user, array &$form, FormStateInterface &$form_state) {
309
    $user->getUntranslated()->langcode = $user->preferred_langcode;
310 311
  }

312 313 314
  /**
   * {@inheritdoc}
   */
315
  public function buildEntity(array $form, FormStateInterface $form_state) {
316 317 318 319 320
    // Change the roles array to a list of enabled roles.
    // @todo: Alter the form state as the form values are directly extracted and
    //   set on the field, which throws an exception as the list requires
    //   numeric keys. Allow to override this per field. As this function is
    //   called twice, we have to prevent it from getting the array keys twice.
321

322 323
    if (is_string(key($form_state->getValue('roles')))) {
      $form_state->setValue('roles', array_keys(array_filter($form_state->getValue('roles'))));
324
    }
325 326 327 328 329

    /** @var \Drupal\user\UserInterface $account */
    $account = parent::buildEntity($form, $form_state);

    // Translate the empty value '' of language selects to an unset field.
330
    foreach (['preferred_langcode', 'preferred_admin_langcode'] as $field_name) {
331 332 333 334
      if ($form_state->getValue($field_name) === '') {
        $account->$field_name = NULL;
      }
    }
335 336

    // Set existing password if set in the form state.
337 338
    $current_pass = trim($form_state->getValue('current_pass'));
    if (strlen($current_pass) > 0) {
339 340 341
      $account->setExistingPassword($current_pass);
    }

342 343 344 345
    // Skip the protected user field constraint if the user came from the
    // password recovery page.
    $account->_skipProtectedUserFieldConstraint = $form_state->get('user_pass_reset');

346
    return $account;
347 348
  }

349
  /**
350
   * {@inheritdoc}
351
   */
352
  protected function getEditedFieldNames(FormStateInterface $form_state) {
353
    return array_merge([
354 355 356 357 358 359
      'name',
      'pass',
      'mail',
      'timezone',
      'langcode',
      'preferred_langcode',
360
      'preferred_admin_langcode',
361
    ], parent::getEditedFieldNames($form_state));
362
  }
363

364 365 366 367 368 369 370
  /**
   * {@inheritdoc}
   */
  protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
    // Manually flag violations of fields not handled by the form display. This
    // is necessary as entity form displays only flag violations for fields
    // contained in the display.
371
    $field_names = [
372
      'name',
373
      'pass',
374 375 376 377
      'mail',
      'timezone',
      'langcode',
      'preferred_langcode',
378
      'preferred_admin_langcode',
379
    ];
380 381 382
    foreach ($violations->getByFields($field_names) as $violation) {
      list($field_name) = explode('.', $violation->getPropertyPath(), 2);
      $form_state->setErrorByName($field_name, $violation->getMessage());
383
    }
384
    parent::flagViolations($violations, $form, $form_state);
385
  }
386

387 388 389
  /**
   * {@inheritdoc}
   */
390 391
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
392 393 394 395

    $user = $this->getEntity($form_state);
    // If there's a session set to the users id, remove the password reset tag
    // since a new password was saved.
396 397
    if (isset($_SESSION['pass_reset_' . $user->id()])) {
      unset($_SESSION['pass_reset_' . $user->id()]);
398 399
    }
  }
400

401
}