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

namespace Drupal\user;

5
use Drupal\Component\Utility\Crypt;
6
use Drupal\Core\Entity\ContentEntityForm;
7
use Drupal\Core\Entity\EntityConstraintViolationListInterface;
8
use Drupal\Core\Entity\EntityManagerInterface;
9
use Drupal\Core\Entity\Query\QueryFactory;
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
   */
  protected $languageManager;

30 31 32 33 34 35 36
  /**
   * The entity query factory service.
   *
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
  protected $entityQuery;

37
  /**
38
   * Constructs a new EntityForm object.
39
   *
40 41
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
42
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
43
   *   The language manager.
44
   * @param \Drupal\Core\Entity\Query\QueryFactory $entity_query
45
   *   The entity query factory.
46
   */
47
  public function __construct(EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, QueryFactory $entity_query) {
48
    parent::__construct($entity_manager);
49
    $this->languageManager = $language_manager;
50
    $this->entityQuery = $entity_query;
51 52 53 54 55 56 57
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
58
      $container->get('entity.manager'),
59 60
      $container->get('language_manager'),
      $container->get('entity.query')
61 62 63
    );
  }

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

74
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();
75
    $register = $account->isAnonymous();
76
    $admin = $user->hasPermission('administer users');
77 78 79 80 81 82 83 84 85

    // Account information.
    $form['account'] = array(
      '#type'   => 'container',
      '#weight' => -10,
    );

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

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

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

      // To skip the current password field, the user must have logged in via a
123 124
      // one-time link and have the token in the URL. Store this in $form_state
      // so it persists even on subsequent Ajax requests.
125 126 127
      if (!$form_state->get('user_pass_reset') && ($token = $this->getRequest()->get('pass-reset-token'))) {
        $session_key = 'pass_reset_' . $account->id();
        $user_pass_reset = isset($_SESSION[$session_key]) && Crypt::hashEquals($_SESSION[$session_key], $token);
128 129
        $form_state->set('user_pass_reset', $user_pass_reset);
      }
130

131
      // The user must enter their current password to change to a new one.
132
      if ($user->id() == $account->id()) {
133 134
        $form['account']['current_pass'] = array(
          '#type' => 'password',
135
          '#title' => $this->t('Current password'),
136
          '#size' => 25,
137
          '#access' => !$form_state->get('user_pass_reset'),
138
          '#weight' => -5,
139 140 141
          // 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.
142 143
          '#attributes' => array('autocomplete' => 'off'),
        );
144
        $form_state->set('user', $account);
145 146 147 148

        // 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')) {
149
          $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>.', array(
150 151
            '%mail' => $form['account']['mail']['#title'],
            '%pass' => $this->t('Password'),
152
            ':request_new_url' => $this->url('user.pass'),
153 154
          ));
        }
155 156
      }
    }
157
    elseif (!$config->get('verify_mail') || $admin) {
158 159 160
      $form['account']['pass'] = array(
        '#type' => 'password_confirm',
        '#size' => 25,
161
        '#description' => $this->t('Provide a password for the new account in both fields.'),
162 163 164 165
        '#required' => TRUE,
      );
    }

166 167 168 169 170 171 172 173 174 175
    // When not building the user registration form, prevent web browsers from
    // autofilling/prefilling the email, username, and password fields.
    if ($this->getOperation() != 'register') {
      foreach (array('mail', 'name', 'pass') as $key) {
        if (isset($form['account'][$key])) {
          $form['account'][$key]['#attributes']['autocomplete'] = 'off';
        }
      }
    }

176 177
    if ($admin || !$register) {
      $status = $account->get('status')->value;
178 179
    }
    else {
180
      $status = $config->get('register') == USER_REGISTER_VISITORS ? 1 : 0;
181 182 183 184
    }

    $form['account']['status'] = array(
      '#type' => 'radios',
185
      '#title' => $this->t('Status'),
186
      '#default_value' => $status,
187
      '#options' => array($this->t('Blocked'), $this->t('Active')),
188 189 190
      '#access' => $admin,
    );

191
    $roles = array_map(array('\Drupal\Component\Utility\Html', 'escape'), user_role_names(TRUE));
192 193 194

    $form['account']['roles'] = array(
      '#type' => 'checkboxes',
195
      '#title' => $this->t('Roles'),
196
      '#default_value' => (!$register ? $account->getRoles() : array()),
197
      '#options' => $roles,
198
      '#access' => $roles && $user->hasPermission('administer permissions'),
199 200 201
    );

    // Special handling for the inevitable "Authenticated user" role.
202
    $form['account']['roles'][RoleInterface::AUTHENTICATED_ID] = array(
203 204
      '#default_value' => TRUE,
      '#disabled' => TRUE,
205 206 207 208
    );

    $form['account']['notify'] = array(
      '#type' => 'checkbox',
209
      '#title' => $this->t('Notify user of new account'),
210 211 212
      '#access' => $register && $admin,
    );

213
    $user_preferred_langcode = $register ? $language_interface->getId() : $account->getPreferredLangcode();
214

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

217 218
    // Is the user preferred language added?
    $user_language_added = FALSE;
219 220
    if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
      $negotiator = $this->languageManager->getNegotiator();
221
      $user_language_added = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUser::METHOD_ID, LanguageInterface::TYPE_INTERFACE);
222
    }
223
    $form['language'] = array(
224
      '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container',
225
      '#title' => $this->t('Language settings'),
226
      '#open' => TRUE,
227 228
      // Display language selector when either creating a user on the admin
      // interface or editing a user account.
229
      '#access' => !$register || $user->hasPermission('administer users'),
230
    );
231

232 233
    $form['language']['preferred_langcode'] = array(
      '#type' => 'language_select',
234
      '#title' => $this->t('Site language'),
235
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
236
      '#default_value' => $user_preferred_langcode,
237
      '#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."),
238 239 240 241
      // 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']],
242
    );
243

244 245 246
    // 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;
247 248 249
    if ($account->hasPermission('access administration pages') && $this->languageManager instanceof ConfigurableLanguageManagerInterface) {
      $negotiator = $this->languageManager->getNegotiator();
      $show_admin_language = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUserAdmin::METHOD_ID);
250
    }
251 252
    $form['language']['preferred_admin_langcode'] = array(
      '#type' => 'language_select',
253
      '#title' => $this->t('Administration pages language'),
254
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
255
      '#default_value' => $user_preferred_admin_langcode,
256
      '#access' => $show_admin_language,
257 258
      '#empty_option' => $this->t('- No preference -'),
      '#empty_value' => '',
259
    );
260

261 262 263 264
    // 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
265 266 267
    // language. This entity builder provides that synchronization. For
    // use-cases where this synchronization is not desired, a module can alter
    // or remove this item.
268
    $form['#entity_builders']['sync_user_langcode'] = '::syncUserLangcode';
269 270 271 272

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

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
  /**
   * 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) {
303
    $user->getUntranslated()->langcode = $user->preferred_langcode;
304 305
  }

306 307 308
  /**
   * {@inheritdoc}
   */
309
  public function buildEntity(array $form, FormStateInterface $form_state) {
310 311 312 313 314
    // 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.
315

316 317
    if (is_string(key($form_state->getValue('roles')))) {
      $form_state->setValue('roles', array_keys(array_filter($form_state->getValue('roles'))));
318
    }
319 320 321 322 323 324 325 326 327 328

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

    // Translate the empty value '' of language selects to an unset field.
    foreach (array('preferred_langcode', 'preferred_admin_langcode') as $field_name) {
      if ($form_state->getValue($field_name) === '') {
        $account->$field_name = NULL;
      }
    }
329 330

    // Set existing password if set in the form state.
331 332
    $current_pass = trim($form_state->getValue('current_pass'));
    if (strlen($current_pass) > 0) {
333 334 335
      $account->setExistingPassword($current_pass);
    }

336 337 338 339
    // Skip the protected user field constraint if the user came from the
    // password recovery page.
    $account->_skipProtectedUserFieldConstraint = $form_state->get('user_pass_reset');

340
    return $account;
341 342
  }

343
  /**
344
   * {@inheritdoc}
345
   */
346 347 348 349 350 351 352 353 354 355 356
  protected function getEditedFieldNames(FormStateInterface $form_state) {
    return array_merge(array(
      'name',
      'pass',
      'mail',
      'timezone',
      'langcode',
      'preferred_langcode',
      'preferred_admin_langcode'
    ), parent::getEditedFieldNames($form_state));
  }
357

358 359 360 361 362 363 364
  /**
   * {@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.
365 366
    $field_names = array(
      'name',
367
      'pass',
368 369 370 371 372 373
      'mail',
      'timezone',
      'langcode',
      'preferred_langcode',
      'preferred_admin_langcode'
    );
374 375 376
    foreach ($violations->getByFields($field_names) as $violation) {
      list($field_name) = explode('.', $violation->getPropertyPath(), 2);
      $form_state->setErrorByName($field_name, $violation->getMessage());
377
    }
378
    parent::flagViolations($violations, $form, $form_state);
379
  }
380

381 382 383
  /**
   * {@inheritdoc}
   */
384 385
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
386 387 388 389

    $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.
390 391
    if (isset($_SESSION['pass_reset_' . $user->id()])) {
      unset($_SESSION['pass_reset_' . $user->id()]);
392 393
    }
  }
394

395
}