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