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

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

namespace Drupal\user;

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

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

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

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

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

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

67
  /**
68
   * {@inheritdoc}
69
   */
70
  public function form(array $form, FormStateInterface $form_state) {
71
    /** @var \Drupal\user\UserInterface $account */
72
    $account = $this->entity;
73
    $user = $this->currentUser();
74
    $config = \Drupal::config('user.settings');
75

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

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

    // 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),
112 113 114 115 116 117 118 119
    );

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

      // To skip the current password field, the user must have logged in via a
      // one-time link and have the token in the URL.
125 126
      $pass_reset = isset($_SESSION['pass_reset_' . $account->id()]) && (\Drupal::request()->query->get('pass-reset-token') == $_SESSION['pass_reset_' . $account->id()]);

127 128 129 130 131 132 133
      $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.
      if (!$pass_reset) {
        $protected_values['mail'] = $form['account']['mail']['#title'];
134
        $protected_values['pass'] = $this->t('Password');
135
        $request_new = \Drupal::l($this->t('Request new password'), 'user.pass', array(), array('attributes' => array('title' => $this->t('Request new password via email.'))));
136
        $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));
137 138 139
      }

      // The user must enter their current password to change to a new one.
140
      if ($user->id() == $account->id()) {
141 142 143 144 145 146 147
        $form['account']['current_pass_required_values'] = array(
          '#type' => 'value',
          '#value' => $protected_values,
        );

        $form['account']['current_pass'] = array(
          '#type' => 'password',
148
          '#title' => $this->t('Current password'),
149 150 151 152
          '#size' => 25,
          '#access' => !empty($protected_values),
          '#description' => $current_pass_description,
          '#weight' => -5,
153 154 155
          // 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.
156 157 158
          '#attributes' => array('autocomplete' => 'off'),
        );

159
        $form_state->set('user', $account);
160 161 162
        $form['#validate'][] = 'user_validate_current_pass';
      }
    }
163
    elseif (!$config->get('verify_mail') || $admin) {
164 165 166
      $form['account']['pass'] = array(
        '#type' => 'password_confirm',
        '#size' => 25,
167
        '#description' => $this->t('Provide a password for the new account in both fields.'),
168 169 170 171
        '#required' => TRUE,
      );
    }

172 173 174 175 176 177 178 179 180 181
    // 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';
        }
      }
    }

182
    if ($admin) {
183
      $status = $account->isActive();
184 185
    }
    else {
186
      $status = $register ? $config->get('register') == USER_REGISTER_VISITORS : $account->isActive();
187 188 189 190
    }

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

197
    $roles = array_map(array('\Drupal\Component\Utility\String', 'checkPlain'), user_role_names(TRUE));
198 199 200

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

    // Special handling for the inevitable "Authenticated user" role.
    $form['account']['roles'][DRUPAL_AUTHENTICATED_RID] = array(
      '#default_value' => TRUE,
      '#disabled' => TRUE,
211 212 213 214
    );

    $form['account']['notify'] = array(
      '#type' => 'checkbox',
215
      '#title' => $this->t('Notify user of new account'),
216 217 218 219 220
      '#access' => $register && $admin,
    );

    // Signature.
    $form['signature_settings'] = array(
221
      '#type' => 'details',
222
      '#title' => $this->t('Signature settings'),
223
      '#open' => TRUE,
224
      '#weight' => 1,
225
      '#access' => (!$register && $config->get('signatures')),
226
    );
227 228 229 230 231 232 233 234 235 236 237 238 239 240
    // While the details group will simply not be rendered if empty, the actual
    // signature element cannot use #access, since #type 'text_format' is not
    // available when Filter module is not installed. If the user account has an
    // existing signature value and format, then the existing field values will
    // just be re-saved to the database in case of an entity update.
    if ($this->moduleHandler->moduleExists('filter')) {
      $form['signature_settings']['signature'] = array(
        '#type' => 'text_format',
        '#title' => $this->t('Signature'),
        '#default_value' => $account->getSignature(),
        '#description' => $this->t('Your signature will be publicly displayed at the end of your comments.'),
        '#format' => $account->getSignatureFormat(),
      );
    }
241

242
    $user_preferred_langcode = $register ? $language_interface->id : $account->getPreferredLangcode();
243

244
    $user_preferred_admin_langcode = $register ? $language_interface->id : $account->getPreferredAdminLangcode(FALSE);
245

246 247
    // Is the user preferred language added?
    $user_language_added = FALSE;
248 249
    if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
      $negotiator = $this->languageManager->getNegotiator();
250
      $user_language_added = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUser::METHOD_ID, LanguageInterface::TYPE_INTERFACE);
251
    }
252
    $form['language'] = array(
253
      '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container',
254
      '#title' => $this->t('Language settings'),
255
      '#open' => TRUE,
256 257
      // Display language selector when either creating a user on the admin
      // interface or editing a user account.
258
      '#access' => !$register || $user->hasPermission('administer users'),
259
    );
260

261 262
    $form['language']['preferred_langcode'] = array(
      '#type' => 'language_select',
263
      '#title' => $this->t('Site language'),
264
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
265
      '#default_value' => $user_preferred_langcode,
266
      '#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."),
267
    );
268

269 270 271
    // 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;
272 273 274
    if ($account->hasPermission('access administration pages') && $this->languageManager instanceof ConfigurableLanguageManagerInterface) {
      $negotiator = $this->languageManager->getNegotiator();
      $show_admin_language = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUserAdmin::METHOD_ID);
275
    }
276 277
    $form['language']['preferred_admin_langcode'] = array(
      '#type' => 'language_select',
278
      '#title' => $this->t('Administration pages language'),
279
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
280
      '#default_value' => $user_preferred_admin_langcode,
281
      '#access' => $show_admin_language,
282 283
      '#empty_option' => $this->t('- No preference -'),
      '#empty_value' => '',
284
    );
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    // 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
    // language. This element provides that synchronization. For use-cases where
    // this synchronization is not desired, a module can alter or remove this
    // element.
    $form['language']['langcode'] = array(
      '#type' => 'value',
      '#value_callback' => '_user_language_selector_langcode_value',
      // For the synchronization to work, this element must have a larger weight
      // than the preferred_langcode element. Set a large weight here in case
      // a module alters the weight of the other element.
      '#weight' => 100,
    );

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

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

314 315
    if (is_string(key($form_state->getValue('roles')))) {
      $form_state->setValue('roles', array_keys(array_filter($form_state->getValue('roles'))));
316 317 318 319
    }
    return parent::buildEntity($form, $form_state);
  }

320
  /**
321
   * {@inheritdoc}
322
   */
323
  public function validate(array $form, FormStateInterface $form_state) {
324 325
    parent::validate($form, $form_state);

326
    $account = $this->entity;
327
    // Validate new or changing username.
328 329
    if ($form_state->hasValue('name')) {
      if ($error = user_validate_name($form_state->getValue('name'))) {
330
        $form_state->setErrorByName('name', $error);
331 332 333 334
      }
      // Cast the user ID as an integer. It might have been set to NULL, which
      // could lead to unexpected results.
      else {
335 336
        $name_taken = (bool) $this->entityQuery->get('user')
          ->condition('uid', (int) $account->id(), '<>')
337
          ->condition('name', $form_state->getValue('name'))
338 339 340
          ->range(0, 1)
          ->count()
          ->execute();
341 342

        if ($name_taken) {
343
          $form_state->setErrorByName('name', $this->t('The name %name is already taken.', array('%name' => $form_state->getValue('name'))));
344 345 346 347
        }
      }
    }

348
    $mail = $form_state->getValue('mail');
349 350

    if (!empty($mail)) {
351 352 353 354 355 356
      $mail_taken = (bool) $this->entityQuery->get('user')
        ->condition('uid', (int) $account->id(), '<>')
        ->condition('mail', $mail)
        ->range(0, 1)
        ->count()
        ->execute();
357 358 359

      if ($mail_taken) {
        // Format error message dependent on whether the user is logged in or not.
360
        if (\Drupal::currentUser()->isAuthenticated()) {
361
          $form_state->setErrorByName('mail', $this->t('The email address %email is already taken.', array('%email' => $mail)));
362 363
        }
        else {
364
          $form_state->setErrorByName('mail', $this->t('The email address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $mail, '@password' => $this->url('user.pass'))));
365 366 367 368 369 370
        }
      }
    }

    // Make sure the signature isn't longer than the size of the database field.
    // Signatures are disabled by default, so make sure it exists first.
371
    if ($signature = $form_state->getValue('signature')) {
372
      // Move text format for user signature into 'signature_format'.
373
      $form_state->setValue('signature_format', $signature['format']);
374
      // Move text value for user signature into 'signature'.
375
      $form_state->setValue('signature', $signature['value']);
376

377 378 379 380
      // @todo Make the user signature field use a widget to benefit from
      //   automatic typed data validation in https://drupal.org/node/2227381.
      $field_definitions = $this->entityManager->getFieldDefinitions('user', $this->getEntity()->bundle());
      $max_length = $field_definitions['signature']->getSetting('max_length');
381
      if (drupal_strlen($form_state->getValue('signature')) > $max_length) {
382
        $form_state->setErrorByName('signature', $this->t('The signature is too long: it must be %max characters or less.', array('%max' => $max_length)));
383 384 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
}