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