5 * Enables the user registration and login system.
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\Entity\Display\EntityViewDisplayInterface;
13 use Drupal\Core\Field\BaseFieldDefinition;
14 use Drupal\Core\Render\Element;
15 use Drupal\Core\Routing\RouteMatchInterface;
16 use Drupal\Core\Session\AccountInterface;
17 use Drupal\Core\Session\AnonymousUserSession;
18 use Drupal\Core\Site\Settings;
20 use Drupal\system\Entity\Action;
21 use Drupal\user\Entity\Role;
22 use Drupal\user\Entity\User;
23 use Drupal\user\RoleInterface;
24 use Drupal\user\UserInterface;
27 * Maximum length of username text field.
29 * Keep this under 191 characters so we can use a unique constraint in MySQL.
31 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
32 * Use \Drupal\user\UserInterface::USERNAME_MAX_LENGTH instead.
34 * @see https://www.drupal.org/node/2831620
36 const USERNAME_MAX_LENGTH = 60;
39 * Only administrators can create user accounts.
41 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
42 * Use \Drupal\user\UserInterface::REGISTER_ADMINISTRATORS_ONLY instead.
44 * @see https://www.drupal.org/node/2831620
46 const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
49 * Visitors can create their own accounts.
51 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
52 * Use \Drupal\user\UserInterface::REGISTER_VISITORS instead.
54 * @see https://www.drupal.org/node/2831620
56 const USER_REGISTER_VISITORS = 'visitors';
59 * Visitors can create accounts, but they don't become active without
60 * administrative approval.
62 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
63 * Use \Drupal\user\UserInterface::REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL
66 * @see https://www.drupal.org/node/2831620
68 const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
71 * Implements hook_help().
73 function user_help($route_name, RouteMatchInterface $route_match) {
74 switch ($route_name) {
75 case 'help.page.user':
77 $output .= '<h3>' . t('About') . '</h3>';
78 $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>';
79 $output .= '<h3>' . t('Uses') . '</h3>';
81 $output .= '<dt>' . t('Creating and managing users') . '</dt>';
82 $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>';
83 $output .= '<dt>' . t('Configuring user roles') . '</dt>';
84 $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>';
85 $output .= '<dt>' . t('Setting permissions') . '</dt>';
86 $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>';
87 $output .= '<dt>' . t('Managing account settings') . '</dt>';
88 $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>';
89 $output .= '<dt>' . t('Managing user account fields') . '</dt>';
90 $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>';
94 case 'user.admin_create':
95 return '<p>' . t("This web page allows administrators to register new users. Users' email addresses and usernames must be unique.") . '</p>';
97 case 'user.admin_permissions':
98 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 case 'entity.user_role.collection':
101 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 case 'entity.user.field_ui_fields':
104 return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';
106 case 'entity.entity_form_display.user.default':
107 return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';
109 case 'entity.entity_view_display.user.default':
110 return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
115 * Implements hook_theme().
117 function user_theme() {
120 'render element' => 'elements',
123 'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
129 * Implements hook_js_settings_alter().
131 function user_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
132 // Provide the user ID in drupalSettings to allow JavaScript code to customize
133 // the experience for the end user, rather than the server side, which would
134 // break the render cache.
135 // Similarly, provide a permissions hash, so that permission-dependent data
136 // can be reliably cached on the client side.
137 $user = \Drupal::currentUser();
138 $settings['user']['uid'] = $user->id();
139 $settings['user']['permissionsHash'] = \Drupal::service('user_permissions_hash_generator')->generate($user);
143 * Returns whether this site supports the default user picture feature.
145 * This approach preserves compatibility with node/comment templates. Alternate
146 * user picture implementations (e.g., Gravatar) should provide their own
147 * add/edit/delete forms and populate the 'picture' variable during the
150 function user_picture_enabled() {
151 $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
152 return isset($field_definitions['user_picture']);
156 * Implements hook_entity_extra_field_info().
158 function user_entity_extra_field_info() {
159 $fields['user']['user']['form']['account'] = [
160 'label' => t('User name and password'),
161 'description' => t('User module account form elements.'),
164 $fields['user']['user']['form']['language'] = [
165 'label' => t('Language settings'),
166 'description' => t('User module form element.'),
169 if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
170 $fields['user']['user']['form']['timezone'] = [
171 'label' => t('Timezone'),
172 'description' => t('System module form element.'),
177 $fields['user']['user']['display']['member_for'] = [
178 'label' => t('Member for'),
179 'description' => t("User module 'member for' view element."),
187 * Loads multiple users based on certain conditions.
189 * This function should be used whenever you need to load more than one user
190 * from the database. Users are loaded into memory and will not require
191 * database access if loaded again during the same page request.
194 * (optional) An array of entity IDs. If omitted, all entities are loaded.
196 * A boolean indicating that the internal cache should be reset. Use this if
197 * loading a user object which has been altered during the page request.
200 * An array of user objects, indexed by uid.
202 * @see entity_load_multiple()
203 * @see \Drupal\user\Entity\User::load()
204 * @see user_load_by_mail()
205 * @see user_load_by_name()
206 * @see \Drupal\Core\Entity\Query\QueryInterface
208 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
209 * Use \Drupal\user\Entity\User::loadMultiple().
211 function user_load_multiple(array $uids = NULL, $reset = FALSE) {
213 \Drupal::entityManager()->getStorage('user')->resetCache($uids);
215 return User::loadMultiple($uids);
219 * Loads a user object.
222 * Integer specifying the user ID to load.
224 * TRUE to reset the internal cache and load from the database; FALSE
225 * (default) to load from the internal cache, if set.
227 * @return \Drupal\user\UserInterface
228 * A fully-loaded user object upon successful user load, or NULL if the user
231 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
232 * Use \Drupal\user\Entity\User::load().
234 * @see \Drupal\user\Entity\User::loadMultiple()
236 function user_load($uid, $reset = FALSE) {
238 \Drupal::entityManager()->getStorage('user')->resetCache([$uid]);
240 return User::load($uid);
244 * Fetches a user object by email address.
246 * @param string $mail
247 * String with the account's email address.
248 * @return object|bool
249 * A fully-loaded $user object upon successful user load or FALSE if user
252 * @see \Drupal\user\Entity\User::loadMultiple()
254 function user_load_by_mail($mail) {
255 $users = \Drupal::entityTypeManager()->getStorage('user')
256 ->loadByProperties(['mail' => $mail]);
257 return $users ? reset($users) : FALSE;
261 * Fetches a user object by account name.
263 * @param string $name
264 * String with the account's user name.
265 * @return object|bool
266 * A fully-loaded $user object upon successful user load or FALSE if user
269 * @see \Drupal\user\Entity\User::loadMultiple()
271 function user_load_by_name($name) {
272 $users = \Drupal::entityTypeManager()->getStorage('user')
273 ->loadByProperties(['name' => $name]);
274 return $users ? reset($users) : FALSE;
278 * Verify the syntax of the given name.
280 * @param string $name
281 * The user name to validate.
283 * @return string|null
284 * A translated violation message if the name is invalid or NULL if the name
287 function user_validate_name($name) {
288 $definition = BaseFieldDefinition::create('string')
289 ->addConstraint('UserName', []);
290 $data = \Drupal::typedDataManager()->create($definition);
291 $data->setValue($name);
292 $violations = $data->validate();
293 if (count($violations) > 0) {
294 return $violations[0]->getMessage();
299 * Generate a random alphanumeric password.
301 function user_password($length = 10) {
302 // This variable contains the list of allowable characters for the
303 // password. Note that the number 0 and the letter 'O' have been
304 // removed to avoid confusion between the two. The same is true
305 // of 'I', 1, and 'l'.
306 $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
308 // Zero-based count of characters in the allowable list:
309 $len = strlen($allowable_characters) - 1;
311 // Declare the password as a blank string.
314 // Loop the number of times specified by $length.
315 for ($i = 0; $i < $length; $i++) {
317 // Find a secure random number within the range needed.
318 $index = ord(Crypt::randomBytes(1));
319 } while ($index > $len);
321 // Each iteration, pick a random character from the
322 // allowable string and append it to the password:
323 $pass .= $allowable_characters[$index];
330 * Determine the permissions for one or more roles.
332 * @param array $roles
333 * An array of role IDs.
336 * An array indexed by role ID. Each value is an array of permission strings
337 * for the given role.
339 function user_role_permissions(array $roles) {
340 if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
341 return _user_role_permissions_update($roles);
343 $entities = Role::loadMultiple($roles);
344 $role_permissions = [];
345 foreach ($roles as $rid) {
346 $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : [];
348 return $role_permissions;
352 * Determine the permissions for one or more roles during update.
354 * A separate version is needed because during update the entity system can't
355 * be used and in non-update situations the entity system is preferred because
356 * of the hook system.
358 * @param array $roles
359 * An array of role IDs.
362 * An array indexed by role ID. Each value is an array of permission strings
363 * for the given role.
365 function _user_role_permissions_update($roles) {
366 $role_permissions = [];
367 foreach ($roles as $rid) {
368 $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: [];
370 return $role_permissions;
374 * Checks for usernames blocked by user administration.
376 * @param string $name
377 * A string containing a name of the user.
380 * TRUE if the user is blocked, FALSE otherwise.
382 function user_is_blocked($name) {
383 return (bool) \Drupal::entityQuery('user')
384 ->condition('name', $name)
385 ->condition('status', 0)
390 * Implements hook_ENTITY_TYPE_view() for user entities.
392 function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
393 if ($display->getComponent('member_for')) {
394 $build['member_for'] = [
396 '#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . \Drupal::service('date.formatter')->formatTimeDiffSince($account->getCreatedTime()),
402 * Implements hook_ENTITY_TYPE_view_alter() for user entities.
404 * This function adds a default alt tag to the user_picture field to maintain
407 function user_user_view_alter(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
408 if (user_picture_enabled() && !empty($build['user_picture'])) {
409 foreach (Element::children($build['user_picture']) as $key) {
410 $item = $build['user_picture'][$key]['#item'];
411 if (!$item->get('alt')->getValue()) {
412 $item->get('alt')->setValue(\Drupal::translation()->translate('Profile picture for user @username', ['@username' => $account->getUsername()]));
419 * Implements hook_preprocess_HOOK() for block templates.
421 function user_preprocess_block(&$variables) {
422 if ($variables['configuration']['provider'] == 'user') {
423 switch ($variables['elements']['#plugin_id']) {
424 case 'user_login_block':
425 $variables['attributes']['role'] = 'form';
434 * @param \Drupal\Core\Session\AccountInterface $account
435 * The account object for the user whose name is to be formatted.
438 * An unsanitized string with the username to display.
440 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
441 * Use \Drupal\Core\Session\AccountInterface::getDisplayName().
443 * @todo Remove usage in https://www.drupal.org/node/2311219.
445 function user_format_name(AccountInterface $account) {
446 return $account->getDisplayName();
450 * Implements hook_template_preprocess_default_variables_alter().
452 * @see user_user_login()
453 * @see user_user_logout()
455 function user_template_preprocess_default_variables_alter(&$variables) {
456 $user = \Drupal::currentUser();
458 $variables['user'] = clone $user;
459 // Remove password and session IDs, since themes should not need nor see them.
460 unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
462 $variables['is_admin'] = $user->hasPermission('access administration pages');
463 $variables['logged_in'] = $user->isAuthenticated();
467 * Prepares variables for username templates.
469 * Default template: username.html.twig.
471 * Modules that make any changes to variables like 'name' or 'extra' must ensure
472 * that the final string is safe.
474 * @param array $variables
475 * An associative array containing:
476 * - account: The user account (\Drupal\Core\Session\AccountInterface).
478 function template_preprocess_username(&$variables) {
479 $account = $variables['account'] ?: new AnonymousUserSession();
481 $variables['extra'] = '';
482 $variables['uid'] = $account->id();
483 if (empty($variables['uid'])) {
484 if (theme_get_setting('features.comment_user_verification')) {
485 $variables['extra'] = ' (' . t('not verified') . ')';
489 // Set the name to a formatted name that is safe for printing and
490 // that won't break tables by being too long. Keep an unshortened,
491 // unsanitized version, in case other preprocess functions want to implement
492 // their own shortening logic or add markup. If they do so, they must ensure
493 // that $variables['name'] is safe for printing.
494 $name = $account->getDisplayName();
495 $variables['name_raw'] = $account->getUsername();
496 if (mb_strlen($name) > 20) {
497 $name = Unicode::truncate($name, 15, FALSE, TRUE);
498 $variables['truncated'] = TRUE;
501 $variables['truncated'] = FALSE;
503 $variables['name'] = $name;
504 $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
507 // Populate link path and attributes if appropriate.
508 if ($variables['uid'] && $variables['profile_access']) {
509 // We are linking to a local user.
510 $variables['attributes']['title'] = t('View user profile.');
511 $variables['link_path'] = 'user/' . $variables['uid'];
513 elseif (!empty($account->homepage)) {
514 // Like the 'class' attribute, the 'rel' attribute can hold a
515 // space-separated set of values, so initialize it as an array to make it
516 // easier for other preprocess functions to append to it.
517 $variables['attributes']['rel'] = 'nofollow';
518 $variables['link_path'] = $account->homepage;
519 $variables['homepage'] = $account->homepage;
522 // We have a link path, so we should generate a URL.
523 if (isset($variables['link_path'])) {
525 $variables['attributes']['href'] = Url::fromUri($variables['link_path'], $variables['link_options'])
529 $variables['attributes']['href'] = Url::fromRoute('entity.user.canonical', [
530 'user' => $variables['uid'],
537 * Finalizes the login process and logs in a user.
539 * The function logs in the user, records a watchdog message about the new
540 * session, saves the login timestamp, calls hook_user_login(), and generates a
543 * The current user is replaced with the passed in account.
545 * @param \Drupal\user\UserInterface $account
546 * The account to log in.
548 * @see hook_user_login()
550 function user_login_finalize(UserInterface $account) {
551 \Drupal::currentUser()->setAccount($account);
552 \Drupal::logger('user')->notice('Session opened for %name.', ['%name' => $account->getUsername()]);
553 // Update the user table timestamp noting user has logged in.
554 // This is also used to invalidate one-time login links.
555 $account->setLastLoginTime(REQUEST_TIME);
556 \Drupal::entityManager()
558 ->updateLastLoginTimestamp($account);
560 // Regenerate the session ID to prevent against session fixation attacks.
561 // This is called before hook_user_login() in case one of those functions
562 // fails or incorrectly does a redirect which would leave the old session
564 \Drupal::service('session')->migrate();
565 \Drupal::service('session')->set('uid', $account->id());
566 \Drupal::moduleHandler()->invokeAll('user_login', [$account]);
570 * Implements hook_user_login().
572 function user_user_login(UserInterface $account) {
573 // Reset static cache of default variables in template_preprocess() to reflect
575 drupal_static_reset('template_preprocess');
579 * Implements hook_user_logout().
581 function user_user_logout(AccountInterface $account) {
582 // Reset static cache of default variables in template_preprocess() to reflect
584 drupal_static_reset('template_preprocess');
588 * Generates a unique URL for a user to log in and reset their password.
590 * @param \Drupal\user\UserInterface $account
591 * An object containing the user account.
592 * @param array $options
593 * (optional) A keyed array of settings. Supported options are:
594 * - langcode: A language code to be used when generating locale-sensitive
595 * URLs. If langcode is NULL the users preferred language is used.
598 * A unique URL that provides a one-time log in for the user, from which
599 * they can change their password.
601 function user_pass_reset_url($account, $options = []) {
602 $timestamp = REQUEST_TIME;
603 $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
604 return \Drupal::url('user.reset',
606 'uid' => $account->id(),
607 'timestamp' => $timestamp,
608 'hash' => user_pass_rehash($account, $timestamp),
612 'language' => \Drupal::languageManager()->getLanguage($langcode),
618 * Generates a URL to confirm an account cancellation request.
620 * @param \Drupal\user\UserInterface $account
621 * The user account object.
622 * @param array $options
623 * (optional) A keyed array of settings. Supported options are:
624 * - langcode: A language code to be used when generating locale-sensitive
625 * URLs. If langcode is NULL the users preferred language is used.
628 * A unique URL that may be used to confirm the cancellation of the user
631 * @see user_mail_tokens()
632 * @see \Drupal\user\Controller\UserController::confirmCancel()
634 function user_cancel_url(UserInterface $account, $options = []) {
635 $timestamp = REQUEST_TIME;
636 $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
637 $url_options = ['absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode)];
638 return \Drupal::url('user.cancel_confirm', [
639 'user' => $account->id(),
640 'timestamp' => $timestamp,
641 'hashed_pass' => user_pass_rehash($account, $timestamp),
646 * Creates a unique hash value for use in time-dependent per-user URLs.
648 * This hash is normally used to build a unique and secure URL that is sent to
649 * the user by email for purposes such as resetting the user's password. In
650 * order to validate the URL, the same hash can be generated again, from the
651 * same information, and compared to the hash value from the URL. The hash
652 * contains the time stamp, the user's last login time, the numeric user ID,
653 * and the user's email address.
654 * For a usage example, see user_cancel_url() and
655 * \Drupal\user\Controller\UserController::confirmCancel().
657 * @param \Drupal\user\UserInterface $account
658 * An object containing the user account.
659 * @param int $timestamp
660 * A UNIX timestamp, typically REQUEST_TIME.
663 * A string that is safe for use in URLs and SQL statements.
665 function user_pass_rehash(UserInterface $account, $timestamp) {
667 $data .= $account->getLastLoginTime();
668 $data .= $account->id();
669 $data .= $account->getEmail();
670 return Crypt::hmacBase64($data, Settings::getHashSalt() . $account->getPassword());
674 * Cancel a user account.
676 * Since the user cancellation process needs to be run in a batch, either
677 * Form API will invoke it, or batch_process() needs to be invoked after calling
678 * this function and should define the path to redirect to.
681 * An array of submitted form values.
683 * The user ID of the user account to cancel.
684 * @param string $method
685 * The account cancellation method to use.
687 * @see _user_cancel()
689 function user_cancel($edit, $uid, $method) {
690 $account = User::load($uid);
693 \Drupal::messenger()->addError(t('The user account %id does not exist.', ['%id' => $uid]));
694 \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
698 // Initialize batch (to set title).
700 'title' => t('Cancelling account'),
705 // When the 'user_cancel_delete' method is used, user_delete() is called,
706 // which invokes hook_ENTITY_TYPE_predelete() and hook_ENTITY_TYPE_delete()
707 // for the user entity. Modules should use those hooks to respond to the
709 if ($method != 'user_cancel_delete') {
710 // Allow modules to add further sets to this batch.
711 \Drupal::moduleHandler()->invokeAll('user_cancel', [$edit, $account, $method]);
714 // Finish the batch and actually cancel the account.
716 'title' => t('Cancelling user account'),
718 ['_user_cancel', [$edit, $account, $method]],
722 // After cancelling account, ensure that user is logged out.
723 if ($account->id() == \Drupal::currentUser()->id()) {
724 // Batch API stores data in the session, so use the finished operation to
725 // manipulate the current user's session id.
726 $batch['finished'] = '_user_cancel_session_regenerate';
731 // Batch processing is either handled via Form API or has to be invoked
736 * Implements callback_batch_operation().
738 * Last step for cancelling a user account.
740 * Since batch and session API require a valid user account, the actual
741 * cancellation of a user account needs to happen last.
743 * An array of submitted form values.
744 * @param \Drupal\user\UserInterface $account
745 * The user ID of the user account to cancel.
746 * @param string $method
747 * The account cancellation method to use.
751 function _user_cancel($edit, $account, $method) {
752 $logger = \Drupal::logger('user');
755 case 'user_cancel_block':
756 case 'user_cancel_block_unpublish':
758 // Send account blocked notification if option was checked.
759 if (!empty($edit['user_cancel_notify'])) {
760 _user_mail_notify('status_blocked', $account);
764 \Drupal::messenger()->addStatus(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
765 $logger->notice('Blocked user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
768 case 'user_cancel_reassign':
769 case 'user_cancel_delete':
770 // Send account canceled notification if option was checked.
771 if (!empty($edit['user_cancel_notify'])) {
772 _user_mail_notify('status_canceled', $account);
775 \Drupal::messenger()->addStatus(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
776 $logger->notice('Deleted user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
780 // After cancelling account, ensure that user is logged out. We can't destroy
781 // their session though, as we might have information in it, and we can't
782 // regenerate it because batch API uses the session ID, we will regenerate it
783 // in _user_cancel_session_regenerate().
784 if ($account->id() == \Drupal::currentUser()->id()) {
785 \Drupal::currentUser()->setAccount(new AnonymousUserSession());
790 * Implements callback_batch_finished().
792 * Finished batch processing callback for cancelling a user account.
796 function _user_cancel_session_regenerate() {
797 // Regenerate the users session instead of calling session_destroy() as we
798 // want to preserve any messages that might have been set.
799 \Drupal::service('session')->migrate();
803 * Helper function to return available account cancellation methods.
805 * See documentation of hook_user_cancel_methods_alter().
808 * An array containing all account cancellation methods as form elements.
810 * @see hook_user_cancel_methods_alter()
811 * @see user_admin_settings()
813 function user_cancel_methods() {
814 $user_settings = \Drupal::config('user.settings');
815 $anonymous_name = $user_settings->get('anonymous');
817 'user_cancel_block' => [
818 'title' => t('Disable the account and keep its content.'),
819 '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 'user_cancel_block_unpublish' => [
822 'title' => t('Disable the account and unpublish its content.'),
823 '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 'user_cancel_reassign' => [
826 'title' => t('Delete the account and make its content belong to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
827 '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 'user_cancel_delete' => [
830 'title' => t('Delete the account and its content.'),
831 'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
832 'access' => \Drupal::currentUser()->hasPermission('administer users'),
835 // Allow modules to customize account cancellation methods.
836 \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
838 // Turn all methods into real form elements.
841 '#default_value' => $user_settings->get('cancel_method'),
843 foreach ($methods as $name => $method) {
844 $form['#options'][$name] = $method['title'];
845 // Add the description for the confirmation form. This description is never
846 // shown for the cancel method option, only on the confirmation form.
847 // Therefore, we use a custom #confirm_description property.
848 if (isset($method['description'])) {
849 $form[$name]['#confirm_description'] = $method['description'];
851 if (isset($method['access'])) {
852 $form[$name]['#access'] = $method['access'];
864 function user_delete($uid) {
865 user_delete_multiple([$uid]);
869 * Delete multiple user accounts.
872 * An array of user IDs.
874 * @see hook_ENTITY_TYPE_predelete()
875 * @see hook_ENTITY_TYPE_delete()
877 function user_delete_multiple(array $uids) {
878 entity_delete_multiple('user', $uids);
882 * Generate an array for rendering the given user.
884 * When viewing a user profile, the $page array contains:
886 * - $page['content']['member_for']:
887 * Contains the default "Member for" profile data for a user.
888 * - $page['content']['#user']:
889 * The user account of the profile being viewed.
891 * To theme user profiles, copy core/modules/user/templates/user.html.twig
892 * to your theme directory, and edit it as instructed in that file's comments.
894 * @param \Drupal\user\UserInterface $account
896 * @param string $view_mode
897 * View mode, e.g. 'full'.
898 * @param string|null $langcode
899 * (optional) A language code to use for rendering. Defaults to the global
900 * content language of the current request.
903 * An array as expected by \Drupal\Core\Render\RendererInterface::render().
905 function user_view($account, $view_mode = 'full', $langcode = NULL) {
906 return entity_view($account, $view_mode, $langcode);
910 * Constructs a drupal_render() style array from an array of loaded users.
912 * @param \Drupal\user\UserInterface[] $accounts
913 * An array of user accounts as returned by User::loadMultiple().
914 * @param string $view_mode
915 * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
916 * @param string|null $langcode
917 * (optional) A language code to use for rendering. Defaults to the global
918 * content language of the current request.
921 * An array in the format expected by
922 * \Drupal\Core\Render\RendererInterface::render().
924 function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
925 return entity_view_multiple($accounts, $view_mode, $langcode);
929 * Implements hook_mail().
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']];
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');
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);
946 $language_manager->setConfigOverrideLanguage($original_language);
951 * Token callback to add unsafe tokens for user mails.
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
957 * @param array $replacements
958 * An associative array variable containing mappings from token names to
959 * values (for use with strtr()).
961 * An associative array of token replacement values. If the 'user' element
962 * exists, it must contain a user account object with the following
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().
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);
977 /*** Administrative features ***********************************************/
980 * Retrieves the names of roles matching specified conditions.
982 * @param bool $membersonly
983 * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
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
991 * An associative array with the role id as the key and the role name as
994 function user_role_names($membersonly = FALSE, $permission = NULL) {
995 return array_map(function ($item) {
996 return $item->label();
997 }, user_roles($membersonly, $permission));
1001 * Implements hook_ENTITY_TYPE_insert() for user_role entities.
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()) {
1009 $add_id = 'user_add_role_action.' . $role->id();
1010 if (!Action::load($add_id)) {
1011 $action = Action::create([
1014 'label' => t('Add the @label role to the selected user(s)', ['@label' => $role->label()]),
1015 'configuration' => [
1016 'rid' => $role->id(),
1018 'plugin' => 'user_add_role_action',
1020 $action->trustData()->save();
1022 $remove_id = 'user_remove_role_action.' . $role->id();
1023 if (!Action::load($remove_id)) {
1024 $action = Action::create([
1027 'label' => t('Remove the @label role from the selected user(s)', ['@label' => $role->label()]),
1028 'configuration' => [
1029 'rid' => $role->id(),
1031 'plugin' => 'user_remove_role_action',
1033 $action->trustData()->save();
1038 * Implements hook_ENTITY_TYPE_delete() for user_role entities.
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()]);
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()) {
1050 $actions = Action::loadMultiple([
1051 'user_add_role_action.' . $role->id(),
1052 'user_remove_role_action.' . $role->id(),
1054 foreach ($actions as $action) {
1060 * Retrieve an array of roles matching specified conditions.
1062 * @param bool $membersonly
1063 * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
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.
1070 * @return \Drupal\user\RoleInterface[]
1071 * An associative array with the role id as the key and the role object as
1074 function user_roles($membersonly = FALSE, $permission = NULL) {
1075 $roles = Role::loadMultiple();
1077 unset($roles[RoleInterface::ANONYMOUS_ID]);
1080 if (!empty($permission)) {
1081 $roles = array_filter($roles, function ($role) use ($permission) {
1082 return $role->hasPermission($permission);
1090 * Fetches a user role by role ID.
1092 * @param string $rid
1093 * A string representing the role ID.
1095 * @return \Drupal\user\RoleInterface|null
1096 * A fully-loaded role object if a role with the given ID exists, or NULL
1099 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
1100 * Use \Drupal\user\Entity\Role::load().
1102 function user_role_load($rid) {
1103 return Role::load($rid);
1107 * Change permissions for a user role.
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.
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
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'
1131 * Existing permissions are not changed, unless specified in $permissions.
1133 * @see user_role_grant_permissions()
1134 * @see user_role_revoke_permissions()
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));
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));
1150 * Grant permissions to a user role.
1153 * The ID of a user role to alter.
1154 * @param array $permissions
1155 * (optional) A list of permission names to grant.
1157 * @see user_role_change_permissions()
1158 * @see user_role_revoke_permissions()
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);
1166 $role->trustData()->save();
1171 * Revoke permissions from a user role.
1174 * The ID of a user role to alter.
1175 * @param array $permissions
1176 * (optional) A list of permission names to revoke.
1178 * @see user_role_change_permissions()
1179 * @see user_role_grant_permissions()
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);
1187 $role->trustData()->save();
1191 * Conditionally create and send a notification email when a certain
1192 * operation happens on the given user account.
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
1199 * - 'register_pending_approval': Welcome message, user pending admin
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.
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
1215 * An array containing various information about the message.
1216 * See \Drupal\Core\Mail\MailManagerInterface::mail() for details.
1218 * @see user_mail_tokens()
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');
1232 if (empty($site_mail)) {
1233 $site_mail = ini_get('sendmail_from');
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);
1242 return empty($mail) ? NULL : $mail['result'];
1246 * Implements hook_element_info_alter().
1248 function user_element_info_alter(array &$types) {
1249 if (isset($types['password_confirm'])) {
1250 $types['password_confirm']['#process'][] = 'user_form_process_password_confirm';
1255 * Form element process handler for client-side password validation.
1257 * This #process handler is automatically invoked for 'password_confirm' form
1258 * elements to add the JavaScript and string translations for dynamic password
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,
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(),
1288 $element['#attached']['library'][] = 'user/drupal.user';
1289 $element['#attached']['drupalSettings']['password'] = $password_settings;
1295 * Implements hook_modules_uninstalled().
1297 function user_modules_uninstalled($modules) {
1298 // Remove any potentially orphan module data stored for users.
1299 \Drupal::service('user.data')->delete($modules);
1303 * Saves visitor information as a cookie so it can be reused.
1305 * @param array $values
1306 * An array of key/value pairs to be saved into a cookie.
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, '/');
1316 * Delete a visitor information cookie.
1318 * @param string $cookie_name
1319 * A cookie name such as 'homepage'.
1321 function user_cookie_delete($cookie_name) {
1322 setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
1326 * Implements hook_toolbar().
1328 function user_toolbar() {
1329 $user = \Drupal::currentUser();
1332 '#type' => 'toolbar_item',
1335 '#title' => $user->getDisplayName(),
1336 '#url' => Url::fromRoute('user.page'),
1338 'title' => t('My account'),
1339 'class' => ['toolbar-icon', 'toolbar-icon-user'],
1342 // Vary cache for anonymous and authenticated users.
1343 'contexts' => ['user.roles:anonymous'],
1347 '#heading' => t('User account actions'),
1352 'user/drupal.user.icons',
1357 if ($user->isAnonymous()) {
1360 'title' => t('Log in'),
1361 'url' => Url::fromRoute('user.page'),
1364 $items['user']['tray']['user_links'] = [
1365 '#theme' => 'links__toolbar_user',
1368 'class' => ['toolbar-menu'],
1373 $items['user']['tab']['#title'] = [
1374 '#lazy_builder' => ['user.toolbar_link_builder:renderDisplayName', []],
1375 '#create_placeholder' => TRUE,
1377 $items['user']['tray']['user_links'] = [
1378 '#lazy_builder' => ['user.toolbar_link_builder:renderToolbarLinks', []],
1379 '#create_placeholder' => TRUE,
1387 * Logs the current user out.
1389 function user_logout() {
1390 $user = \Drupal::currentUser();
1392 \Drupal::logger('user')->notice('Session closed for %name.', ['%name' => $user->getAccountName()]);
1394 \Drupal::moduleHandler()->invokeAll('user_logout', [$user]);
1396 // Destroy the current session, and reset $user to the anonymous user.
1397 // Note: In Symfony the session is intended to be destroyed with
1398 // Session::invalidate(). Regrettably this method is currently broken and may
1399 // lead to the creation of spurious session records in the database.
1400 // @see https://github.com/symfony/symfony/issues/12375
1401 \Drupal::service('session_manager')->destroy();
1402 $user->setAccount(new AnonymousUserSession());
1406 * Prepares variables for user templates.
1408 * Default template: user.html.twig.
1410 * @param array $variables
1411 * An associative array containing:
1412 * - elements: An associative array containing the user information and any
1413 * fields attached to the user. Properties used:
1414 * - #user: A \Drupal\user\Entity\User object. The user account of the
1415 * profile being viewed.
1416 * - attributes: HTML attributes for the containing element.
1418 function template_preprocess_user(&$variables) {
1419 $variables['user'] = $variables['elements']['#user'];
1420 // Helpful $content variable for templates.
1421 foreach (Element::children($variables['elements']) as $key) {
1422 $variables['content'][$key] = $variables['elements'][$key];