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

/**
 * @file
5
 * Contains \Drupal\user\AccountForm.
6 7 8 9
 */

namespace Drupal\user;

10
use Drupal\Component\Utility\Unicode;
11
use Drupal\Core\Entity\ContentEntityForm;
12
use Drupal\Core\Entity\EntityManagerInterface;
13
use Drupal\Core\Entity\Query\QueryFactory;
14
use Drupal\Core\Form\FormStateInterface;
15
use Drupal\Core\Language\LanguageInterface;
16
use Drupal\Core\Language\LanguageManagerInterface;
17
use Drupal\Core\Url;
18 19
use Drupal\language\ConfigurableLanguageManagerInterface;
use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUser;
20
use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUserAdmin;
21
use Symfony\Component\DependencyInjection\ContainerInterface;
22 23 24 25

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

28 29 30
  /**
   * The language manager.
   *
31
   * @var \Drupal\Core\Language\LanguageManagerInterface
32 33 34
   */
  protected $languageManager;

35 36 37 38 39 40 41
  /**
   * The entity query factory service.
   *
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
  protected $entityQuery;

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

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
63
      $container->get('entity.manager'),
64 65
      $container->get('language_manager'),
      $container->get('entity.query')
66 67 68
    );
  }

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

79
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();
80
    $register = $account->isAnonymous();
81
    $admin = $user->hasPermission('administer users');
82 83 84 85 86 87 88 89 90

    // 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.
91
    // This allows users without email address to be edited and deleted.
92
    // Also see \Drupal\user\Plugin\Validation\Constraint\UserMailRequired.
93 94
    $form['account']['mail'] = array(
      '#type' => 'email',
95 96
      '#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.'),
97
      '#required' => !(!$account->getEmail() && $user->hasPermission('administer users')),
98
      '#default_value' => (!$register ? $account->getEmail() : ''),
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    );

    // 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,
      '#description' => $this->t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
      '#required' => TRUE,
      '#attributes' => array(
        'class' => array('username'),
        'autocorrect' => 'off',
        'autocapitalize' => 'off',
        'spellcheck' => 'false',
      ),
      '#default_value' => (!$register ? $account->getUsername() : ''),
      '#access' => ($register || ($user->id() == $account->id() && $user->hasPermission('change own username')) || $admin),
116 117 118 119 120 121 122 123
    );

    // 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,
124
        '#description' => $this->t('To change the current user password, enter the new password in both fields.'),
125 126 127
      );

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

135 136 137 138 139
      $protected_values = array();
      $current_pass_description = '';

      // The user may only change their own password without their current
      // password if they logged in via a one-time login link.
140
      if (!$form_state->get('user_pass_reset')) {
141
        $protected_values['mail'] = $form['account']['mail']['#title'];
142
        $protected_values['pass'] = $this->t('Password');
143 144 145 146 147 148 149 150 151 152
        $request_new = $this->l($this->t('Reset your password'), new Url('user.pass',
          array(), array('attributes' => array('title' => $this->t('Send password reset instructions via e-mail.'))))
        );
        $current_pass_description = $this->t('Required if you want to change the %mail or %pass below. !request_new.',
          array(
            '%mail' => $protected_values['mail'],
            '%pass' => $protected_values['pass'],
            '!request_new' => $request_new,
          )
        );
153 154 155
      }

      // The user must enter their current password to change to a new one.
156
      if ($user->id() == $account->id()) {
157 158
        $form['account']['current_pass'] = array(
          '#type' => 'password',
159
          '#title' => $this->t('Current password'),
160 161 162 163
          '#size' => 25,
          '#access' => !empty($protected_values),
          '#description' => $current_pass_description,
          '#weight' => -5,
164 165 166
          // 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.
167 168 169
          '#attributes' => array('autocomplete' => 'off'),
        );

170
        $form_state->set('user', $account);
171 172
      }
    }
173
    elseif (!$config->get('verify_mail') || $admin) {
174 175 176
      $form['account']['pass'] = array(
        '#type' => 'password_confirm',
        '#size' => 25,
177
        '#description' => $this->t('Provide a password for the new account in both fields.'),
178 179 180 181
        '#required' => TRUE,
      );
    }

182 183 184 185 186 187 188 189 190 191
    // 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';
        }
      }
    }

192
    if ($admin) {
193
      $status = $account->isActive();
194 195
    }
    else {
196
      $status = $register ? $config->get('register') == USER_REGISTER_VISITORS : $account->isActive();
197 198 199 200
    }

    $form['account']['status'] = array(
      '#type' => 'radios',
201
      '#title' => $this->t('Status'),
202
      '#default_value' => $status,
203
      '#options' => array($this->t('Blocked'), $this->t('Active')),
204 205 206
      '#access' => $admin,
    );

207
    $roles = array_map(array('\Drupal\Component\Utility\SafeMarkup', 'checkPlain'), user_role_names(TRUE));
208 209 210

    $form['account']['roles'] = array(
      '#type' => 'checkboxes',
211
      '#title' => $this->t('Roles'),
212
      '#default_value' => (!$register ? $account->getRoles() : array()),
213
      '#options' => $roles,
214
      '#access' => $roles && $user->hasPermission('administer permissions'),
215 216 217
    );

    // Special handling for the inevitable "Authenticated user" role.
218
    $form['account']['roles'][RoleInterface::AUTHENTICATED_ID] = array(
219 220
      '#default_value' => TRUE,
      '#disabled' => TRUE,
221 222 223 224
    );

    $form['account']['notify'] = array(
      '#type' => 'checkbox',
225
      '#title' => $this->t('Notify user of new account'),
226 227 228
      '#access' => $register && $admin,
    );

229
    $user_preferred_langcode = $register ? $language_interface->getId() : $account->getPreferredLangcode();
230

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

233 234
    // Is the user preferred language added?
    $user_language_added = FALSE;
235 236
    if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
      $negotiator = $this->languageManager->getNegotiator();
237
      $user_language_added = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUser::METHOD_ID, LanguageInterface::TYPE_INTERFACE);
238
    }
239
    $form['language'] = array(
240
      '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container',
241
      '#title' => $this->t('Language settings'),
242
      '#open' => TRUE,
243 244
      // Display language selector when either creating a user on the admin
      // interface or editing a user account.
245
      '#access' => !$register || $user->hasPermission('administer users'),
246
    );
247

248 249
    $form['language']['preferred_langcode'] = array(
      '#type' => 'language_select',
250
      '#title' => $this->t('Site language'),
251
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
252
      '#default_value' => $user_preferred_langcode,
253
      '#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."),
254 255 256 257
      // 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']],
258
    );
259

260 261 262
    // 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;
263 264 265
    if ($account->hasPermission('access administration pages') && $this->languageManager instanceof ConfigurableLanguageManagerInterface) {
      $negotiator = $this->languageManager->getNegotiator();
      $show_admin_language = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUserAdmin::METHOD_ID);
266
    }
267 268
    $form['language']['preferred_admin_langcode'] = array(
      '#type' => 'language_select',
269
      '#title' => $this->t('Administration pages language'),
270
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
271
      '#default_value' => $user_preferred_admin_langcode,
272
      '#access' => $show_admin_language,
273 274
      '#empty_option' => $this->t('- No preference -'),
      '#empty_value' => '',
275
    );
276

277 278 279 280
    // 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
281 282 283 284
    // language. This entity builder provides that synchronization. For
    // use-cases where this synchronization is not desired, a module can alter
    // or remove this item.
    $form['#entity_builders']['sync_user_langcode'] = [$this, 'syncUserLangcode'];
285 286 287 288

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

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
  /**
   * 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) {
319
    $user->getUntranslated()->langcode = $user->preferred_langcode;
320 321
  }

322 323 324
  /**
   * {@inheritdoc}
   */
325
  public function buildEntity(array $form, FormStateInterface $form_state) {
326 327 328 329 330
    // 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.
331

332 333
    if (is_string(key($form_state->getValue('roles')))) {
      $form_state->setValue('roles', array_keys(array_filter($form_state->getValue('roles'))));
334
    }
335 336 337 338 339 340 341 342 343 344

    /** @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;
      }
    }
345 346 347 348 349 350

    // Set existing password if set in the form state.
    if ($current_pass = $form_state->getValue('current_pass')) {
      $account->setExistingPassword($current_pass);
    }

351
    return $account;
352 353
  }

354
  /**
355
   * {@inheritdoc}
356
   */
357
  public function validate(array &$form, FormStateInterface $form_state) {
358
    /** @var \Drupal\user\UserInterface $account */
359 360
    $account = parent::validate($form, $form_state);

361 362 363 364
    // Skip the protected user field constraint if the user came from the
    // password recovery page.
    $account->_skipProtectedUserFieldConstraint = $form_state->get('user_pass_reset');

365 366 367 368 369
    // Customly trigger validation of manually added fields and add in
    // violations. This is necessary as entity form displays only invoke entity
    // validation for fields contained in the display.
    $field_names = array(
      'name',
370
      'pass',
371 372 373 374 375 376 377 378 379 380
      'mail',
      'timezone',
      'langcode',
      'preferred_langcode',
      'preferred_admin_langcode'
    );
    foreach ($field_names as $field_name) {
      $violations = $account->$field_name->validate();
      foreach ($violations as $violation) {
        $form_state->setErrorByName($field_name, $violation->getMessage());
381 382
      }
    }
383 384

    return $account;
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 396 397 398 399

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