2d7d24a006386d024b3c1aba91975cb98e846dd2
[yaffs-website] / web / core / modules / user / user.module
1 <?php
2
3 /**
4  * @file
5  * Enables the user registration and login system.
6  */
7
8 use Drupal\Component\Utility\Crypt;
9 use Drupal\Component\Render\PlainTextOutput;
10 use Drupal\Component\Utility\Unicode;
11 use Drupal\Core\Asset\AttachedAssetsInterface;
12 use Drupal\Core\Cache\Cache;
13 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
14 use Drupal\Core\Field\BaseFieldDefinition;
15 use Drupal\Core\Render\Element;
16 use Drupal\Core\Routing\RouteMatchInterface;
17 use Drupal\Core\Session\AccountInterface;
18 use Drupal\Core\Session\AnonymousUserSession;
19 use Drupal\Core\Site\Settings;
20 use Drupal\Core\Url;
21 use Drupal\system\Entity\Action;
22 use Drupal\user\Entity\Role;
23 use Drupal\user\Entity\User;
24 use Drupal\user\RoleInterface;
25 use Drupal\user\UserInterface;
26
27 /**
28  * Maximum length of username text field.
29  *
30  * Keep this under 191 characters so we can use a unique constraint in MySQL.
31  *
32  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
33  *   Use \Drupal\user\UserInterface::USERNAME_MAX_LENGTH instead.
34  *
35  * @see https://www.drupal.org/node/2831620
36  */
37 const USERNAME_MAX_LENGTH = 60;
38
39 /**
40  * Only administrators can create user accounts.
41  *
42  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
43  *   Use \Drupal\user\UserInterface::REGISTER_ADMINISTRATORS_ONLY instead.
44  *
45  * @see https://www.drupal.org/node/2831620
46  */
47 const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
48
49 /**
50  * Visitors can create their own accounts.
51  *
52  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
53  *   Use \Drupal\user\UserInterface::REGISTER_VISITORS instead.
54  *
55  * @see https://www.drupal.org/node/2831620
56  */
57 const USER_REGISTER_VISITORS = 'visitors';
58
59 /**
60  * Visitors can create accounts, but they don't become active without
61  * administrative approval.
62  *
63  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
64  *   Use \Drupal\user\UserInterface::REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL
65  *   instead.
66  *
67  * @see https://www.drupal.org/node/2831620
68  */
69 const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
70
71 /**
72  * Implements hook_help().
73  */
74 function user_help($route_name, RouteMatchInterface $route_match) {
75   switch ($route_name) {
76     case 'help.page.user':
77       $output = '';
78       $output .= '<h3>' . t('About') . '</h3>';
79       $output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles and permissions. For more information, see the <a href=":user_docs">online documentation for the User module</a>.', [':user_docs' => 'https://www.drupal.org/documentation/modules/user']) . '</p>';
80       $output .= '<h3>' . t('Uses') . '</h3>';
81       $output .= '<dl>';
82       $output .= '<dt>' . t('Creating and managing users') . '</dt>';
83       $output .= '<dd>' . t('Through the <a href=":people">People administration page</a> you can add and cancel user accounts and assign users to roles. By editing one particular user you can change their username, email address, password, and information in other fields.', [':people' => \Drupal::url('entity.user.collection')]) . '</dd>';
84       $output .= '<dt>' . t('Configuring user roles') . '</dt>';
85       $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. Typically there are two pre-defined roles: <em>Anonymous user</em> (users that are not logged in), and <em>Authenticated user</em> (users that are registered and logged in). Depending on how your site was set up, an <em>Administrator</em> role may also be available: users with this role will automatically be assigned any new permissions whenever a module is enabled. You can create additional roles on the <a href=":roles">Roles administration page</a>.', [':roles' => \Drupal::url('entity.user_role.collection')]) . '</dd>';
86       $output .= '<dt>' . t('Setting permissions') . '</dt>';
87       $output .= '<dd>' . t('After creating roles, you can set permissions for each role on the <a href=":permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing content, editing or creating  a particular type of content, administering settings for a particular module, or using a particular function of the site (such as search).', [':permissions_user' => \Drupal::url('user.admin_permissions')]) . '</dd>';
88       $output .= '<dt>' . t('Managing account settings') . '</dt>';
89       $output .= '<dd>' . t('The <a href=":accounts">Account settings page</a> allows you to manage settings for the displayed name of the Anonymous user role, personal contact forms, user registration settings, and account cancellation settings. On this page you can also manage settings for account personalization, and adapt the text for the email messages that users receive when they register or request a password recovery. You may also set which role is automatically assigned new permissions whenever a module is enabled (the Administrator role).', [':accounts' => \Drupal::url('entity.user.admin_form')]) . '</dd>';
90       $output .= '<dt>' . t('Managing user account fields') . '</dt>';
91       $output .= '<dd>' . t('Because User accounts are an entity type, you can extend them by adding fields through the Manage fields tab on the <a href=":accounts">Account settings page</a>. By adding fields for e.g., a picture, a biography, or address, you can a create a custom profile for the users of the website. For background information on entities and fields, see the <a href=":field_help">Field module help page</a>.', [':field_help' => (\Drupal::moduleHandler()->moduleExists('field')) ? \Drupal::url('help.page', ['name' => 'field']) : '#', ':accounts' => \Drupal::url('entity.user.admin_form')]) . '</dd>';
92       $output .= '</dl>';
93       return $output;
94
95     case 'user.admin_create':
96       return '<p>' . t("This web page allows administrators to register new users. Users' email addresses and usernames must be unique.") . '</p>';
97
98     case 'user.admin_permissions':
99       return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href=":role">Roles</a> page to create a role.) Any permissions granted to the Authenticated user role will be given to any user who is logged in to your site. From the <a href=":settings">Account settings</a> page, you can make any role into an Administrator role for the site, meaning that role will be granted all new permissions automatically. You should be careful to ensure that only trusted users are given this access and level of control of your site.', [':role' => \Drupal::url('entity.user_role.collection'), ':settings' => \Drupal::url('entity.user.admin_form')]) . '</p>';
100
101     case 'entity.user_role.collection':
102       return '<p>' . t('A role defines a group of users that have certain privileges. These privileges are defined on the <a href=":permissions">Permissions page</a>. Here, you can define the names and the display sort order of the roles on your site. It is recommended to order roles from least permissive (for example, Anonymous user) to most permissive (for example, Administrator user). Users who are not logged in have the Anonymous user role. Users who are logged in have the Authenticated user role, plus any other roles granted to their user account.', [':permissions' => \Drupal::url('user.admin_permissions')]) . '</p>';
103
104     case 'entity.user.field_ui_fields':
105       return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';
106
107     case 'entity.entity_form_display.user.default':
108       return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';
109
110     case 'entity.entity_view_display.user.default':
111       return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
112   }
113 }
114
115 /**
116  * Implements hook_theme().
117  */
118 function user_theme() {
119   return [
120     'user' => [
121       'render element' => 'elements',
122     ],
123     'username' => [
124       'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
125     ],
126   ];
127 }
128
129 /**
130  * Implements hook_js_settings_alter().
131  */
132 function user_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
133   // Provide the user ID in drupalSettings to allow JavaScript code to customize
134   // the experience for the end user, rather than the server side, which would
135   // break the render cache.
136   // Similarly, provide a permissions hash, so that permission-dependent data
137   // can be reliably cached on the client side.
138   $user = \Drupal::currentUser();
139   $settings['user']['uid'] = $user->id();
140   $settings['user']['permissionsHash'] = \Drupal::service('user_permissions_hash_generator')->generate($user);
141 }
142
143 /**
144  * Returns whether this site supports the default user picture feature.
145  *
146  * This approach preserves compatibility with node/comment templates. Alternate
147  * user picture implementations (e.g., Gravatar) should provide their own
148  * add/edit/delete forms and populate the 'picture' variable during the
149  * preprocess stage.
150  */
151 function user_picture_enabled() {
152   $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
153   return isset($field_definitions['user_picture']);
154 }
155
156 /**
157  * Implements hook_entity_extra_field_info().
158  */
159 function user_entity_extra_field_info() {
160   $fields['user']['user']['form']['account'] = [
161     'label' => t('User name and password'),
162     'description' => t('User module account form elements.'),
163     'weight' => -10,
164   ];
165   $fields['user']['user']['form']['language'] = [
166     'label' => t('Language settings'),
167     'description' => t('User module form element.'),
168     'weight' => 0,
169   ];
170   if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
171     $fields['user']['user']['form']['timezone'] = [
172       'label' => t('Timezone'),
173       'description' => t('System module form element.'),
174       'weight' => 6,
175     ];
176   }
177
178   $fields['user']['user']['display']['member_for'] = [
179     'label' => t('Member for'),
180     'description' => t("User module 'member for' view element."),
181     'weight' => 5,
182   ];
183
184   return $fields;
185 }
186
187 /**
188  * Loads multiple users based on certain conditions.
189  *
190  * This function should be used whenever you need to load more than one user
191  * from the database. Users are loaded into memory and will not require
192  * database access if loaded again during the same page request.
193  *
194  * @param array $uids
195  *   (optional) An array of entity IDs. If omitted, all entities are loaded.
196  * @param bool $reset
197  *   A boolean indicating that the internal cache should be reset. Use this if
198  *   loading a user object which has been altered during the page request.
199  *
200  * @return array
201  *   An array of user objects, indexed by uid.
202  *
203  * @see entity_load_multiple()
204  * @see \Drupal\user\Entity\User::load()
205  * @see user_load_by_mail()
206  * @see user_load_by_name()
207  * @see \Drupal\Core\Entity\Query\QueryInterface
208  *
209  * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
210  *   Use \Drupal\user\Entity\User::loadMultiple().
211  */
212 function user_load_multiple(array $uids = NULL, $reset = FALSE) {
213   if ($reset) {
214     \Drupal::entityManager()->getStorage('user')->resetCache($uids);
215   }
216   return User::loadMultiple($uids);
217 }
218
219 /**
220  * Loads a user object.
221  *
222  * @param int $uid
223  *   Integer specifying the user ID to load.
224  * @param bool $reset
225  *   TRUE to reset the internal cache and load from the database; FALSE
226  *   (default) to load from the internal cache, if set.
227  *
228  * @return \Drupal\user\UserInterface
229  *   A fully-loaded user object upon successful user load, or NULL if the user
230  *   cannot be loaded.
231  *
232  * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
233  *   Use \Drupal\user\Entity\User::load().
234  *
235  * @see \Drupal\user\Entity\User::loadMultiple()
236  */
237 function user_load($uid, $reset = FALSE) {
238   if ($reset) {
239     \Drupal::entityManager()->getStorage('user')->resetCache([$uid]);
240   }
241   return User::load($uid);
242 }
243
244 /**
245  * Fetches a user object by email address.
246  *
247  * @param string $mail
248  *   String with the account's email address.
249  * @return object|bool
250  *   A fully-loaded $user object upon successful user load or FALSE if user
251  *   cannot be loaded.
252  *
253  * @see \Drupal\user\Entity\User::loadMultiple()
254  */
255 function user_load_by_mail($mail) {
256   $users = \Drupal::entityTypeManager()->getStorage('user')
257     ->loadByProperties(['mail' => $mail]);
258   return $users ? reset($users) : FALSE;
259 }
260
261 /**
262  * Fetches a user object by account name.
263  *
264  * @param string $name
265  *   String with the account's user name.
266  * @return object|bool
267  *   A fully-loaded $user object upon successful user load or FALSE if user
268  *   cannot be loaded.
269  *
270  * @see \Drupal\user\Entity\User::loadMultiple()
271  */
272 function user_load_by_name($name) {
273   $users = \Drupal::entityTypeManager()->getStorage('user')
274     ->loadByProperties(['name' => $name]);
275   return $users ? reset($users) : FALSE;
276 }
277
278 /**
279  * Verify the syntax of the given name.
280  *
281  * @param string $name
282  *   The user name to validate.
283  *
284  * @return string|null
285  *   A translated violation message if the name is invalid or NULL if the name
286  *   is valid.
287  */
288 function user_validate_name($name) {
289   $definition = BaseFieldDefinition::create('string')
290     ->addConstraint('UserName', []);
291   $data = \Drupal::typedDataManager()->create($definition);
292   $data->setValue($name);
293   $violations = $data->validate();
294   if (count($violations) > 0) {
295     return $violations[0]->getMessage();
296   }
297 }
298
299 /**
300  * Generate a random alphanumeric password.
301  */
302 function user_password($length = 10) {
303   // This variable contains the list of allowable characters for the
304   // password. Note that the number 0 and the letter 'O' have been
305   // removed to avoid confusion between the two. The same is true
306   // of 'I', 1, and 'l'.
307   $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
308
309   // Zero-based count of characters in the allowable list:
310   $len = strlen($allowable_characters) - 1;
311
312   // Declare the password as a blank string.
313   $pass = '';
314
315   // Loop the number of times specified by $length.
316   for ($i = 0; $i < $length; $i++) {
317     do {
318       // Find a secure random number within the range needed.
319       $index = ord(Crypt::randomBytes(1));
320     } while ($index > $len);
321
322     // Each iteration, pick a random character from the
323     // allowable string and append it to the password:
324     $pass .= $allowable_characters[$index];
325   }
326
327   return $pass;
328 }
329
330 /**
331  * Determine the permissions for one or more roles.
332  *
333  * @param array $roles
334  *   An array of role IDs.
335  *
336  * @return array
337  *   An array indexed by role ID. Each value is an array of permission strings
338  *   for the given role.
339  */
340 function user_role_permissions(array $roles) {
341   if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
342     return _user_role_permissions_update($roles);
343   }
344   $entities = Role::loadMultiple($roles);
345   $role_permissions = [];
346   foreach ($roles as $rid) {
347     $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : [];
348   }
349   return $role_permissions;
350 }
351
352 /**
353  * Determine the permissions for one or more roles during update.
354  *
355  * A separate version is needed because during update the entity system can't
356  * be used and in non-update situations the entity system is preferred because
357  * of the hook system.
358  *
359  * @param array $roles
360  *   An array of role IDs.
361  *
362  * @return array
363  *   An array indexed by role ID. Each value is an array of permission strings
364  *   for the given role.
365  */
366 function _user_role_permissions_update($roles) {
367   $role_permissions = [];
368   foreach ($roles as $rid) {
369     $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: [];
370   }
371   return $role_permissions;
372 }
373
374 /**
375  * Checks for usernames blocked by user administration.
376  *
377  * @param string $name
378  *   A string containing a name of the user.
379  *
380  * @return bool
381  *   TRUE if the user is blocked, FALSE otherwise.
382  */
383 function user_is_blocked($name) {
384   return (bool) \Drupal::entityQuery('user')
385     ->condition('name', $name)
386     ->condition('status', 0)
387     ->execute();
388 }
389
390 /**
391  * Implements hook_ENTITY_TYPE_view() for user entities.
392  */
393 function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
394   if ($display->getComponent('member_for')) {
395     $build['member_for'] = [
396       '#type' => 'item',
397       '#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . \Drupal::service('date.formatter')->formatTimeDiffSince($account->getCreatedTime()),
398     ];
399   }
400 }
401
402 /**
403  * Implements hook_ENTITY_TYPE_view_alter() for user entities.
404  *
405  * This function adds a default alt tag to the user_picture field to maintain
406  * accessibility.
407  */
408 function user_user_view_alter(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
409   if (user_picture_enabled() && !empty($build['user_picture'])) {
410     foreach (Element::children($build['user_picture']) as $key) {
411       $item = $build['user_picture'][$key]['#item'];
412       if (!$item->get('alt')->getValue()) {
413         $item->get('alt')->setValue(\Drupal::translation()->translate('Profile picture for user @username', ['@username' => $account->getUsername()]));
414       }
415     }
416   }
417 }
418
419 /**
420  * Implements hook_preprocess_HOOK() for block templates.
421  */
422 function user_preprocess_block(&$variables) {
423   if ($variables['configuration']['provider'] == 'user') {
424     switch ($variables['elements']['#plugin_id']) {
425       case 'user_login_block':
426         $variables['attributes']['role'] = 'form';
427         break;
428     }
429   }
430 }
431
432 /**
433  * Format a username.
434  *
435  * @param \Drupal\Core\Session\AccountInterface $account
436  *   The account object for the user whose name is to be formatted.
437  *
438  * @return string
439  *   An unsanitized string with the username to display.
440  *
441  * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
442  *   Use \Drupal\Core\Session\AccountInterface::getDisplayName().
443  *
444  * @todo Remove usage in https://www.drupal.org/node/2311219.
445  */
446 function user_format_name(AccountInterface $account) {
447   return $account->getDisplayName();
448 }
449
450 /**
451  * Implements hook_template_preprocess_default_variables_alter().
452  *
453  * @see user_user_login()
454  * @see user_user_logout()
455  */
456 function user_template_preprocess_default_variables_alter(&$variables) {
457   $user = \Drupal::currentUser();
458
459   $variables['user'] = clone $user;
460   // Remove password and session IDs, since themes should not need nor see them.
461   unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
462
463   $variables['is_admin'] = $user->hasPermission('access administration pages');
464   $variables['logged_in'] = $user->isAuthenticated();
465 }
466
467 /**
468  * Prepares variables for username templates.
469  *
470  * Default template: username.html.twig.
471  *
472  * Modules that make any changes to variables like 'name' or 'extra' must ensure
473  * that the final string is safe.
474  *
475  * @param array $variables
476  *   An associative array containing:
477  *   - account: The user account (\Drupal\Core\Session\AccountInterface).
478  */
479 function template_preprocess_username(&$variables) {
480   $account = $variables['account'] ?: new AnonymousUserSession();
481
482   $variables['extra'] = '';
483   $variables['uid'] = $account->id();
484   if (empty($variables['uid'])) {
485     if (theme_get_setting('features.comment_user_verification')) {
486       $variables['extra'] = ' (' . t('not verified') . ')';
487     }
488   }
489
490   // Set the name to a formatted name that is safe for printing and
491   // that won't break tables by being too long. Keep an unshortened,
492   // unsanitized version, in case other preprocess functions want to implement
493   // their own shortening logic or add markup. If they do so, they must ensure
494   // that $variables['name'] is safe for printing.
495   $name  = $account->getDisplayName();
496   $variables['name_raw'] = $account->getUsername();
497   if (Unicode::strlen($name) > 20) {
498     $name = Unicode::truncate($name, 15, FALSE, TRUE);
499     $variables['truncated'] = TRUE;
500   }
501   else {
502     $variables['truncated'] = FALSE;
503   }
504   $variables['name'] = $name;
505   $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
506
507   $external = FALSE;
508   // Populate link path and attributes if appropriate.
509   if ($variables['uid'] && $variables['profile_access']) {
510     // We are linking to a local user.
511     $variables['attributes']['title'] = t('View user profile.');
512     $variables['link_path'] = 'user/' . $variables['uid'];
513   }
514   elseif (!empty($account->homepage)) {
515     // Like the 'class' attribute, the 'rel' attribute can hold a
516     // space-separated set of values, so initialize it as an array to make it
517     // easier for other preprocess functions to append to it.
518     $variables['attributes']['rel'] = 'nofollow';
519     $variables['link_path'] = $account->homepage;
520     $variables['homepage'] = $account->homepage;
521     $external = TRUE;
522   }
523   // We have a link path, so we should generate a URL.
524   if (isset($variables['link_path'])) {
525     if ($external) {
526       $variables['attributes']['href'] = Url::fromUri($variables['link_path'], $variables['link_options'])
527         ->toString();
528     }
529     else {
530       $variables['attributes']['href'] = Url::fromRoute('entity.user.canonical', [
531         'user' => $variables['uid'],
532       ])->toString();
533     }
534   }
535 }
536
537 /**
538  * Finalizes the login process and logs in a user.
539  *
540  * The function logs in the user, records a watchdog message about the new
541  * session, saves the login timestamp, calls hook_user_login(), and generates a
542  * new session.
543  *
544  * The current user is replaced with the passed in account.
545  *
546  * @param \Drupal\user\UserInterface $account
547  *   The account to log in.
548  *
549  * @see hook_user_login()
550  */
551 function user_login_finalize(UserInterface $account) {
552   \Drupal::currentUser()->setAccount($account);
553   \Drupal::logger('user')->notice('Session opened for %name.', ['%name' => $account->getUsername()]);
554   // Update the user table timestamp noting user has logged in.
555   // This is also used to invalidate one-time login links.
556   $account->setLastLoginTime(REQUEST_TIME);
557   \Drupal::entityManager()
558     ->getStorage('user')
559     ->updateLastLoginTimestamp($account);
560
561   // Regenerate the session ID to prevent against session fixation attacks.
562   // This is called before hook_user_login() in case one of those functions
563   // fails or incorrectly does a redirect which would leave the old session
564   // in place.
565   \Drupal::service('session')->migrate();
566   \Drupal::service('session')->set('uid', $account->id());
567   \Drupal::moduleHandler()->invokeAll('user_login', [$account]);
568 }
569
570 /**
571  * Implements hook_user_login().
572  */
573 function user_user_login($account) {
574   // Reset static cache of default variables in template_preprocess() to reflect
575   // the new user.
576   drupal_static_reset('template_preprocess');
577 }
578
579 /**
580  * Implements hook_user_logout().
581  */
582 function user_user_logout($account) {
583   // Reset static cache of default variables in template_preprocess() to reflect
584   // the new user.
585   drupal_static_reset('template_preprocess');
586 }
587
588 /**
589  * Generates a unique URL for a user to log in and reset their password.
590  *
591  * @param \Drupal\user\UserInterface $account
592  *   An object containing the user account.
593  * @param array $options
594  *   (optional) A keyed array of settings. Supported options are:
595  *   - langcode: A language code to be used when generating locale-sensitive
596  *    URLs. If langcode is NULL the users preferred language is used.
597  *
598  * @return string
599  *   A unique URL that provides a one-time log in for the user, from which
600  *   they can change their password.
601  */
602 function user_pass_reset_url($account, $options = []) {
603   $timestamp = REQUEST_TIME;
604   $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
605   return \Drupal::url('user.reset',
606     [
607       'uid' => $account->id(),
608       'timestamp' => $timestamp,
609       'hash' => user_pass_rehash($account, $timestamp),
610     ],
611     [
612       'absolute' => TRUE,
613       'language' => \Drupal::languageManager()->getLanguage($langcode)
614     ]
615   );
616 }
617
618 /**
619  * Generates a URL to confirm an account cancellation request.
620  *
621  * @param \Drupal\user\UserInterface $account
622  *   The user account object.
623  * @param array $options
624  *   (optional) A keyed array of settings. Supported options are:
625  *   - langcode: A language code to be used when generating locale-sensitive
626  *     URLs. If langcode is NULL the users preferred language is used.
627  *
628  * @return string
629  *   A unique URL that may be used to confirm the cancellation of the user
630  *   account.
631  *
632  * @see user_mail_tokens()
633  * @see \Drupal\user\Controller\UserController::confirmCancel()
634  */
635 function user_cancel_url(UserInterface $account, $options = []) {
636   $timestamp = REQUEST_TIME;
637   $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
638   $url_options = ['absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode)];
639   return \Drupal::url('user.cancel_confirm', [
640     'user' => $account->id(),
641     'timestamp' => $timestamp,
642     'hashed_pass' => user_pass_rehash($account, $timestamp)
643   ], $url_options);
644 }
645
646 /**
647  * Creates a unique hash value for use in time-dependent per-user URLs.
648  *
649  * This hash is normally used to build a unique and secure URL that is sent to
650  * the user by email for purposes such as resetting the user's password. In
651  * order to validate the URL, the same hash can be generated again, from the
652  * same information, and compared to the hash value from the URL. The hash
653  * contains the time stamp, the user's last login time, the numeric user ID,
654  * and the user's email address.
655  * For a usage example, see user_cancel_url() and
656  * \Drupal\user\Controller\UserController::confirmCancel().
657  *
658  * @param \Drupal\user\UserInterface $account
659  *   An object containing the user account.
660  * @param int $timestamp
661  *   A UNIX timestamp, typically REQUEST_TIME.
662  *
663  * @return string
664  *   A string that is safe for use in URLs and SQL statements.
665  */
666 function user_pass_rehash(UserInterface $account, $timestamp) {
667   $data = $timestamp;
668   $data .= $account->getLastLoginTime();
669   $data .= $account->id();
670   $data .= $account->getEmail();
671   return Crypt::hmacBase64($data, Settings::getHashSalt() . $account->getPassword());
672 }
673
674 /**
675  * Cancel a user account.
676  *
677  * Since the user cancellation process needs to be run in a batch, either
678  * Form API will invoke it, or batch_process() needs to be invoked after calling
679  * this function and should define the path to redirect to.
680  *
681  * @param array $edit
682  *   An array of submitted form values.
683  * @param int $uid
684  *   The user ID of the user account to cancel.
685  * @param string $method
686  *   The account cancellation method to use.
687  *
688  * @see _user_cancel()
689  */
690 function user_cancel($edit, $uid, $method) {
691   $account = User::load($uid);
692
693   if (!$account) {
694     drupal_set_message(t('The user account %id does not exist.', ['%id' => $uid]), 'error');
695     \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
696     return;
697   }
698
699   // Initialize batch (to set title).
700   $batch = [
701     'title' => t('Cancelling account'),
702     'operations' => [],
703   ];
704   batch_set($batch);
705
706   // When the 'user_cancel_delete' method is used, user_delete() is called,
707   // which invokes hook_ENTITY_TYPE_predelete() and hook_ENTITY_TYPE_delete()
708   // for the user entity. Modules should use those hooks to respond to the
709   // account deletion.
710   if ($method != 'user_cancel_delete') {
711     // Allow modules to add further sets to this batch.
712     \Drupal::moduleHandler()->invokeAll('user_cancel', [$edit, $account, $method]);
713   }
714
715   // Finish the batch and actually cancel the account.
716   $batch = [
717     'title' => t('Cancelling user account'),
718     'operations' => [
719       ['_user_cancel', [$edit, $account, $method]],
720     ],
721   ];
722
723   // After cancelling account, ensure that user is logged out.
724   if ($account->id() == \Drupal::currentUser()->id()) {
725     // Batch API stores data in the session, so use the finished operation to
726     // manipulate the current user's session id.
727     $batch['finished'] = '_user_cancel_session_regenerate';
728   }
729
730   batch_set($batch);
731
732   // Batch processing is either handled via Form API or has to be invoked
733   // manually.
734 }
735
736 /**
737  * Implements callback_batch_operation().
738  *
739  * Last step for cancelling a user account.
740  *
741  * Since batch and session API require a valid user account, the actual
742  * cancellation of a user account needs to happen last.
743  * @param array $edit
744  *   An array of submitted form values.
745  * @param \Drupal\user\UserInterface $account
746  *   The user ID of the user account to cancel.
747  * @param string $method
748  *   The account cancellation method to use.
749  *
750  * @see user_cancel()
751  */
752 function _user_cancel($edit, $account, $method) {
753   $logger = \Drupal::logger('user');
754
755   switch ($method) {
756     case 'user_cancel_block':
757     case 'user_cancel_block_unpublish':
758     default:
759       // Send account blocked notification if option was checked.
760       if (!empty($edit['user_cancel_notify'])) {
761         _user_mail_notify('status_blocked', $account);
762       }
763       $account->block();
764       $account->save();
765       drupal_set_message(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
766       $logger->notice('Blocked user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
767       break;
768
769     case 'user_cancel_reassign':
770     case 'user_cancel_delete':
771       // Send account canceled notification if option was checked.
772       if (!empty($edit['user_cancel_notify'])) {
773         _user_mail_notify('status_canceled', $account);
774       }
775       $account->delete();
776       drupal_set_message(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
777       $logger->notice('Deleted user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
778       break;
779   }
780
781   // After cancelling account, ensure that user is logged out. We can't destroy
782   // their session though, as we might have information in it, and we can't
783   // regenerate it because batch API uses the session ID, we will regenerate it
784   // in _user_cancel_session_regenerate().
785   if ($account->id() == \Drupal::currentUser()->id()) {
786     \Drupal::currentUser()->setAccount(new AnonymousUserSession());
787   }
788 }
789
790 /**
791  * Implements callback_batch_finished().
792  *
793  * Finished batch processing callback for cancelling a user account.
794  *
795  * @see user_cancel()
796  */
797 function _user_cancel_session_regenerate() {
798   // Regenerate the users session instead of calling session_destroy() as we
799   // want to preserve any messages that might have been set.
800   \Drupal::service('session')->migrate();
801 }
802
803 /**
804  * Helper function to return available account cancellation methods.
805  *
806  * See documentation of hook_user_cancel_methods_alter().
807  *
808  * @return array
809  *   An array containing all account cancellation methods as form elements.
810  *
811  * @see hook_user_cancel_methods_alter()
812  * @see user_admin_settings()
813  */
814 function user_cancel_methods() {
815   $user_settings = \Drupal::config('user.settings');
816   $anonymous_name = $user_settings->get('anonymous');
817   $methods = [
818     'user_cancel_block' => [
819       'title' => t('Disable the account and keep its content.'),
820       'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your username.'),
821     ],
822     'user_cancel_block_unpublish' => [
823       'title' => t('Disable the account and unpublish its content.'),
824       'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'),
825     ],
826     'user_cancel_reassign' => [
827       'title' => t('Delete the account and make its content belong to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
828       'description' => t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
829     ],
830     'user_cancel_delete' => [
831       'title' => t('Delete the account and its content.'),
832       'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
833       'access' => \Drupal::currentUser()->hasPermission('administer users'),
834     ],
835   ];
836   // Allow modules to customize account cancellation methods.
837   \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
838
839   // Turn all methods into real form elements.
840   $form = [
841     '#options' => [],
842     '#default_value' => $user_settings->get('cancel_method'),
843   ];
844   foreach ($methods as $name => $method) {
845     $form['#options'][$name] = $method['title'];
846     // Add the description for the confirmation form. This description is never
847     // shown for the cancel method option, only on the confirmation form.
848     // Therefore, we use a custom #confirm_description property.
849     if (isset($method['description'])) {
850       $form[$name]['#confirm_description'] = $method['description'];
851     }
852     if (isset($method['access'])) {
853       $form[$name]['#access'] = $method['access'];
854     }
855   }
856   return $form;
857 }
858
859 /**
860  * Delete a user.
861  *
862  * @param int $uid
863  *   A user ID.
864  */
865 function user_delete($uid) {
866   user_delete_multiple([$uid]);
867 }
868
869 /**
870  * Delete multiple user accounts.
871  *
872  * @param int[] $uids
873  *   An array of user IDs.
874  *
875  * @see hook_ENTITY_TYPE_predelete()
876  * @see hook_ENTITY_TYPE_delete()
877  */
878 function user_delete_multiple(array $uids) {
879   entity_delete_multiple('user', $uids);
880 }
881
882 /**
883  * Generate an array for rendering the given user.
884  *
885  * When viewing a user profile, the $page array contains:
886  *
887  * - $page['content']['member_for']:
888  *   Contains the default "Member for" profile data for a user.
889  * - $page['content']['#user']:
890  *   The user account of the profile being viewed.
891  *
892  * To theme user profiles, copy core/modules/user/templates/user.html.twig
893  * to your theme directory, and edit it as instructed in that file's comments.
894  *
895  * @param \Drupal\user\UserInterface $account
896  *   A user object.
897  * @param string $view_mode
898  *   View mode, e.g. 'full'.
899  * @param string|null $langcode
900  *   (optional) A language code to use for rendering. Defaults to the global
901  *   content language of the current request.
902  *
903  * @return array
904  *   An array as expected by drupal_render().
905  */
906 function user_view($account, $view_mode = 'full', $langcode = NULL) {
907   return entity_view($account, $view_mode, $langcode);
908 }
909
910 /**
911  * Constructs a drupal_render() style array from an array of loaded users.
912  *
913  * @param \Drupal\user\UserInterface[] $accounts
914  *   An array of user accounts as returned by User::loadMultiple().
915  * @param string $view_mode
916  *   (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
917  * @param string|null $langcode
918  *   (optional) A language code to use for rendering. Defaults to the global
919  *   content language of the current request.
920  *
921  * @return array
922  *   An array in the format expected by drupal_render().
923  */
924 function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
925   return entity_view_multiple($accounts, $view_mode, $langcode);
926 }
927
928 /**
929  * Implements hook_mail().
930  */
931 function user_mail($key, &$message, $params) {
932   $token_service = \Drupal::token();
933   $language_manager = \Drupal::languageManager();
934   $langcode = $message['langcode'];
935   $variables = ['user' => $params['account']];
936
937   $language = $language_manager->getLanguage($params['account']->getPreferredLangcode());
938   $original_language = $language_manager->getConfigOverrideLanguage();
939   $language_manager->setConfigOverrideLanguage($language);
940   $mail_config = \Drupal::config('user.mail');
941
942   $token_options = ['langcode' => $langcode, 'callback' => 'user_mail_tokens', 'clear' => TRUE];
943   $message['subject'] .= PlainTextOutput::renderFromHtml($token_service->replace($mail_config->get($key . '.subject'), $variables, $token_options));
944   $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);
945
946   $language_manager->setConfigOverrideLanguage($original_language);
947
948 }
949
950 /**
951  * Token callback to add unsafe tokens for user mails.
952  *
953  * This function is used by \Drupal\Core\Utility\Token::replace() to set up
954  * some additional tokens that can be used in email messages generated by
955  * user_mail().
956  *
957  * @param array $replacements
958  *   An associative array variable containing mappings from token names to
959  *   values (for use with strtr()).
960  * @param array $data
961  *   An associative array of token replacement values. If the 'user' element
962  *   exists, it must contain a user account object with the following
963  *   properties:
964  *   - login: The UNIX timestamp of the user's last login.
965  *   - pass: The hashed account login password.
966  * @param array $options
967  *   A keyed array of settings and flags to control the token replacement
968  *   process. See \Drupal\Core\Utility\Token::replace().
969  */
970 function user_mail_tokens(&$replacements, $data, $options) {
971   if (isset($data['user'])) {
972     $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
973     $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
974   }
975 }
976
977 /*** Administrative features ***********************************************/
978
979 /**
980  * Retrieves the names of roles matching specified conditions.
981  *
982  * @param bool $membersonly
983  *   (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
984  *   FALSE.
985  * @param string|null $permission
986  *   (optional) A string containing a permission. If set, only roles
987  *    containing that permission are returned. Defaults to NULL, which
988  *    returns all roles.
989  *
990  * @return array
991  *   An associative array with the role id as the key and the role name as
992  *   value.
993  */
994 function user_role_names($membersonly = FALSE, $permission = NULL) {
995   return array_map(function ($item) {
996     return $item->label();
997   }, user_roles($membersonly, $permission));
998 }
999
1000 /**
1001  * Implements hook_ENTITY_TYPE_insert() for user_role entities.
1002  */
1003 function user_user_role_insert(RoleInterface $role) {
1004   // Ignore the authenticated and anonymous roles or the role is being synced.
1005   if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
1006     return;
1007   }
1008
1009   $add_id = 'user_add_role_action.' . $role->id();
1010   if (!Action::load($add_id)) {
1011     $action = Action::create([
1012       'id' => $add_id,
1013       'type' => 'user',
1014       'label' => t('Add the @label role to the selected user(s)', ['@label' => $role->label()]),
1015       'configuration' => [
1016         'rid' => $role->id(),
1017       ],
1018       'plugin' => 'user_add_role_action',
1019     ]);
1020     $action->trustData()->save();
1021   }
1022   $remove_id = 'user_remove_role_action.' . $role->id();
1023   if (!Action::load($remove_id)) {
1024     $action = Action::create([
1025       'id' => $remove_id,
1026       'type' => 'user',
1027       'label' => t('Remove the @label role from the selected user(s)', ['@label' => $role->label()]),
1028       'configuration' => [
1029         'rid' => $role->id(),
1030       ],
1031       'plugin' => 'user_remove_role_action',
1032     ]);
1033     $action->trustData()->save();
1034   }
1035 }
1036
1037 /**
1038  * Implements hook_ENTITY_TYPE_delete() for user_role entities.
1039  */
1040 function user_user_role_delete(RoleInterface $role) {
1041   // Delete role references for all users.
1042   $user_storage = \Drupal::entityManager()->getStorage('user');
1043   $user_storage->deleteRoleReferences([$role->id()]);
1044
1045   // Ignore the authenticated and anonymous roles or the role is being synced.
1046   if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
1047     return;
1048   }
1049
1050   $actions = Action::loadMultiple([
1051     'user_add_role_action.' . $role->id(),
1052     'user_remove_role_action.' . $role->id(),
1053   ]);
1054   foreach ($actions as $action) {
1055     $action->delete();
1056   }
1057 }
1058
1059 /**
1060  * Retrieve an array of roles matching specified conditions.
1061  *
1062  * @param bool $membersonly
1063  *   (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
1064  *   FALSE.
1065  * @param string|null $permission
1066  *   (optional) A string containing a permission. If set, only roles
1067  *   containing that permission are returned. Defaults to NULL, which
1068  *   returns all roles.
1069  *
1070  * @return \Drupal\user\RoleInterface[]
1071  *   An associative array with the role id as the key and the role object as
1072  *   value.
1073  */
1074 function user_roles($membersonly = FALSE, $permission = NULL) {
1075   $roles = Role::loadMultiple();
1076   if ($membersonly) {
1077     unset($roles[RoleInterface::ANONYMOUS_ID]);
1078   }
1079
1080   if (!empty($permission)) {
1081     $roles = array_filter($roles, function ($role) use ($permission) {
1082       return $role->hasPermission($permission);
1083     });
1084   }
1085
1086   return $roles;
1087 }
1088
1089 /**
1090  * Fetches a user role by role ID.
1091  *
1092  * @param string $rid
1093  *   A string representing the role ID.
1094  *
1095  * @return \Drupal\user\RoleInterface|null
1096  *   A fully-loaded role object if a role with the given ID exists, or NULL
1097  *   otherwise.
1098  *
1099  * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
1100  *   Use \Drupal\user\Entity\Role::load().
1101  */
1102 function user_role_load($rid) {
1103   return Role::load($rid);
1104 }
1105
1106 /**
1107  * Change permissions for a user role.
1108  *
1109  * This function may be used to grant and revoke multiple permissions at once.
1110  * For example, when a form exposes checkboxes to configure permissions for a
1111  * role, the form submit handler may directly pass the submitted values for the
1112  * checkboxes form element to this function.
1113  *
1114  * @param mixed $rid
1115  *   The ID of a user role to alter.
1116  * @param array $permissions
1117  *   (optional) An associative array, where the key holds the permission name
1118  *   and the value determines whether to grant or revoke that permission. Any
1119  *   value that evaluates to TRUE will cause the permission to be granted.
1120  *   Any value that evaluates to FALSE will cause the permission to be
1121  *   revoked.
1122  *   @code
1123  *     array(
1124  *       'administer nodes' => 0,                // Revoke 'administer nodes'
1125  *       'administer blocks' => FALSE,           // Revoke 'administer blocks'
1126  *       'access user profiles' => 1,            // Grant 'access user profiles'
1127  *       'access content' => TRUE,               // Grant 'access content'
1128  *       'access comments' => 'access comments', // Grant 'access comments'
1129  *     )
1130  *   @endcode
1131  *   Existing permissions are not changed, unless specified in $permissions.
1132  *
1133  * @see user_role_grant_permissions()
1134  * @see user_role_revoke_permissions()
1135  */
1136 function user_role_change_permissions($rid, array $permissions = []) {
1137   // Grant new permissions for the role.
1138   $grant = array_filter($permissions);
1139   if (!empty($grant)) {
1140     user_role_grant_permissions($rid, array_keys($grant));
1141   }
1142   // Revoke permissions for the role.
1143   $revoke = array_diff_assoc($permissions, $grant);
1144   if (!empty($revoke)) {
1145     user_role_revoke_permissions($rid, array_keys($revoke));
1146   }
1147 }
1148
1149 /**
1150  * Grant permissions to a user role.
1151  *
1152  * @param mixed $rid
1153  *   The ID of a user role to alter.
1154  * @param array $permissions
1155  *   (optional) A list of permission names to grant.
1156  *
1157  * @see user_role_change_permissions()
1158  * @see user_role_revoke_permissions()
1159  */
1160 function user_role_grant_permissions($rid, array $permissions = []) {
1161   // Grant new permissions for the role.
1162   if ($role = Role::load($rid)) {
1163     foreach ($permissions as $permission) {
1164       $role->grantPermission($permission);
1165     }
1166     $role->trustData()->save();
1167   }
1168 }
1169
1170 /**
1171  * Revoke permissions from a user role.
1172  *
1173  * @param mixed $rid
1174  *   The ID of a user role to alter.
1175  * @param array $permissions
1176  *   (optional) A list of permission names to revoke.
1177  *
1178  * @see user_role_change_permissions()
1179  * @see user_role_grant_permissions()
1180  */
1181 function user_role_revoke_permissions($rid, array $permissions = []) {
1182   // Revoke permissions for the role.
1183   $role = Role::load($rid);
1184   foreach ($permissions as $permission) {
1185     $role->revokePermission($permission);
1186   }
1187   $role->trustData()->save();
1188 }
1189
1190 /**
1191  * Conditionally create and send a notification email when a certain
1192  * operation happens on the given user account.
1193  *
1194  * @param string $op
1195  *   The operation being performed on the account. Possible values:
1196  *   - 'register_admin_created': Welcome message for user created by the admin.
1197  *   - 'register_no_approval_required': Welcome message when user
1198  *     self-registers.
1199  *   - 'register_pending_approval': Welcome message, user pending admin
1200  *     approval.
1201  *   - 'password_reset': Password recovery request.
1202  *   - 'status_activated': Account activated.
1203  *   - 'status_blocked': Account blocked.
1204  *   - 'cancel_confirm': Account cancellation request.
1205  *   - 'status_canceled': Account canceled.
1206  *
1207  * @param \Drupal\Core\Session\AccountInterface $account
1208  *   The user object of the account being notified. Must contain at
1209  *   least the fields 'uid', 'name', and 'mail'.
1210  * @param string $langcode
1211  *   (optional) Language code to use for the notification, overriding account
1212  *   language.
1213  *
1214  * @return array
1215  *   An array containing various information about the message.
1216  *   See \Drupal\Core\Mail\MailManagerInterface::mail() for details.
1217  *
1218  * @see user_mail_tokens()
1219  */
1220 function _user_mail_notify($op, $account, $langcode = NULL) {
1221   if (\Drupal::config('user.settings')->get('notify.' . $op)) {
1222     $params['account'] = $account;
1223     $langcode = $langcode ? $langcode : $account->getPreferredLangcode();
1224     // Get the custom site notification email to use as the from email address
1225     // if it has been set.
1226     $site_mail = \Drupal::config('system.site')->get('mail_notification');
1227     // If the custom site notification email has not been set, we use the site
1228     // default for this.
1229     if (empty($site_mail)) {
1230       $site_mail = \Drupal::config('system.site')->get('mail');
1231     }
1232     if (empty($site_mail)) {
1233       $site_mail = ini_get('sendmail_from');
1234     }
1235     $mail = \Drupal::service('plugin.manager.mail')->mail('user', $op, $account->getEmail(), $langcode, $params, $site_mail);
1236     if ($op == 'register_pending_approval') {
1237       // If a user registered requiring admin approval, notify the admin, too.
1238       // We use the site default language for this.
1239       \Drupal::service('plugin.manager.mail')->mail('user', 'register_pending_approval_admin', $site_mail, \Drupal::languageManager()->getDefaultLanguage()->getId(), $params);
1240     }
1241   }
1242   return empty($mail) ? NULL : $mail['result'];
1243 }
1244
1245 /**
1246  * Implements hook_element_info_alter().
1247  */
1248 function user_element_info_alter(array &$types) {
1249   if (isset($types['password_confirm'])) {
1250     $types['password_confirm']['#process'][] = 'user_form_process_password_confirm';
1251   }
1252 }
1253
1254 /**
1255  * Form element process handler for client-side password validation.
1256  *
1257  * This #process handler is automatically invoked for 'password_confirm' form
1258  * elements to add the JavaScript and string translations for dynamic password
1259  * validation.
1260  */
1261 function user_form_process_password_confirm($element) {
1262   $password_settings = [
1263     'confirmTitle' => t('Passwords match:'),
1264     'confirmSuccess' => t('yes'),
1265     'confirmFailure' => t('no'),
1266     'showStrengthIndicator' => FALSE,
1267   ];
1268
1269   if (\Drupal::config('user.settings')->get('password_strength')) {
1270     $password_settings['showStrengthIndicator'] = TRUE;
1271     $password_settings += [
1272       'strengthTitle' => t('Password strength:'),
1273       'hasWeaknesses' => t('Recommendations to make your password stronger:'),
1274       'tooShort' => t('Make it at least 12 characters'),
1275       'addLowerCase' => t('Add lowercase letters'),
1276       'addUpperCase' => t('Add uppercase letters'),
1277       'addNumbers' => t('Add numbers'),
1278       'addPunctuation' => t('Add punctuation'),
1279       'sameAsUsername' => t('Make it different from your username'),
1280       'weak' => t('Weak'),
1281       'fair' => t('Fair'),
1282       'good' => t('Good'),
1283       'strong' => t('Strong'),
1284       'username' => \Drupal::currentUser()->getUsername(),
1285     ];
1286   }
1287
1288   $element['#attached']['library'][] = 'user/drupal.user';
1289   $element['#attached']['drupalSettings']['password'] = $password_settings;
1290
1291   return $element;
1292 }
1293
1294 /**
1295  * Implements hook_modules_uninstalled().
1296  */
1297 function user_modules_uninstalled($modules) {
1298   // Remove any potentially orphan module data stored for users.
1299   \Drupal::service('user.data')->delete($modules);
1300 }
1301
1302 /**
1303  * Saves visitor information as a cookie so it can be reused.
1304  *
1305  * @param array $values
1306  *   An array of key/value pairs to be saved into a cookie.
1307  */
1308 function user_cookie_save(array $values) {
1309   foreach ($values as $field => $value) {
1310     // Set cookie for 365 days.
1311     setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
1312   }
1313 }
1314
1315 /**
1316  * Delete a visitor information cookie.
1317  *
1318  * @param string $cookie_name
1319  *   A cookie name such as 'homepage'.
1320  */
1321 function user_cookie_delete($cookie_name) {
1322   setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
1323 }
1324
1325 /**
1326  * Implements hook_toolbar().
1327  */
1328 function user_toolbar() {
1329   $user = \Drupal::currentUser();
1330
1331   // Add logout & user account links or login link.
1332   $links_cache_contexts = [];
1333   if ($user->isAuthenticated()) {
1334     $links = [
1335       'account' => [
1336         'title' => t('View profile'),
1337         'url' => Url::fromRoute('user.page'),
1338         'attributes' => [
1339           'title' => t('User account'),
1340         ],
1341       ],
1342       'account_edit' => [
1343         'title' => t('Edit profile'),
1344         'url' => Url::fromRoute('entity.user.edit_form', ['user' => $user->id()]),
1345         'attributes' => [
1346           'title' => t('Edit user account'),
1347         ],
1348       ],
1349       'logout' => [
1350         'title' => t('Log out'),
1351         'url' => Url::fromRoute('user.logout'),
1352       ],
1353     ];
1354     // The "Edit user account" link is per-user.
1355     $links_cache_contexts[] = 'user';
1356   }
1357   else {
1358     $links = [
1359       'login' => [
1360         'title' => t('Log in'),
1361         'url' => Url::fromRoute('user.page'),
1362       ],
1363     ];
1364   }
1365
1366   $items['user'] = [
1367     '#type' => 'toolbar_item',
1368     'tab' => [
1369       '#type' => 'link',
1370       '#title' => $user->getDisplayName(),
1371       '#url' => Url::fromRoute('user.page'),
1372       '#attributes' => [
1373         'title' => t('My account'),
1374         'class' => ['toolbar-icon', 'toolbar-icon-user'],
1375       ],
1376       '#cache' => [
1377         'contexts' => [
1378           // Cacheable per user, because the current user's name is shown.
1379           'user',
1380         ],
1381       ],
1382     ],
1383     'tray' => [
1384       '#heading' => t('User account actions'),
1385       'user_links' => [
1386         '#cache' => [
1387           // Cacheable per "authenticated or not", because the links to
1388           // display depend on that.
1389           'contexts' => Cache::mergeContexts(['user.roles:authenticated'], $links_cache_contexts),
1390         ],
1391         '#theme' => 'links__toolbar_user',
1392         '#links' => $links,
1393         '#attributes' => [
1394           'class' => ['toolbar-menu'],
1395         ],
1396       ],
1397     ],
1398     '#weight' => 100,
1399     '#attached' => [
1400       'library' => [
1401         'user/drupal.user.icons',
1402       ],
1403     ],
1404   ];
1405
1406   return $items;
1407 }
1408
1409 /**
1410  * Logs the current user out.
1411  */
1412 function user_logout() {
1413   $user = \Drupal::currentUser();
1414
1415   \Drupal::logger('user')->notice('Session closed for %name.', ['%name' => $user->getAccountName()]);
1416
1417   \Drupal::moduleHandler()->invokeAll('user_logout', [$user]);
1418
1419   // Destroy the current session, and reset $user to the anonymous user.
1420   // Note: In Symfony the session is intended to be destroyed with
1421   // Session::invalidate(). Regrettably this method is currently broken and may
1422   // lead to the creation of spurious session records in the database.
1423   // @see https://github.com/symfony/symfony/issues/12375
1424   \Drupal::service('session_manager')->destroy();
1425   $user->setAccount(new AnonymousUserSession());
1426 }
1427
1428 /**
1429  * Prepares variables for user templates.
1430  *
1431  * Default template: user.html.twig.
1432  *
1433  * @param array $variables
1434  *   An associative array containing:
1435  *   - elements: An associative array containing the user information and any
1436  *     fields attached to the user. Properties used:
1437  *     - #user: A \Drupal\user\Entity\User object. The user account of the
1438  *       profile being viewed.
1439  *   - attributes: HTML attributes for the containing element.
1440  */
1441 function template_preprocess_user(&$variables) {
1442   $variables['user'] = $variables['elements']['#user'];
1443   // Helpful $content variable for templates.
1444   foreach (Element::children($variables['elements']) as $key) {
1445     $variables['content'][$key] = $variables['elements'][$key];
1446   }
1447 }