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\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;
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;
28 * Maximum length of username text field.
30 * Keep this under 191 characters so we can use a unique constraint in MySQL.
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.
35 * @see https://www.drupal.org/node/2831620
37 const USERNAME_MAX_LENGTH = 60;
40 * Only administrators can create user accounts.
42 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
43 * Use \Drupal\user\UserInterface::REGISTER_ADMINISTRATORS_ONLY instead.
45 * @see https://www.drupal.org/node/2831620
47 const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
50 * Visitors can create their own accounts.
52 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
53 * Use \Drupal\user\UserInterface::REGISTER_VISITORS instead.
55 * @see https://www.drupal.org/node/2831620
57 const USER_REGISTER_VISITORS = 'visitors';
60 * Visitors can create accounts, but they don't become active without
61 * administrative approval.
63 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
64 * Use \Drupal\user\UserInterface::REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL
67 * @see https://www.drupal.org/node/2831620
69 const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
72 * Implements hook_help().
74 function user_help($route_name, RouteMatchInterface $route_match) {
75 switch ($route_name) {
76 case 'help.page.user':
78 $output .= '<h3>' . t('About') . '</h3>';
79 $output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles and permissions. For more information, see the <a href=":user_docs">online documentation for the User module</a>.', [':user_docs' => 'https://www.drupal.org/documentation/modules/user']) . '</p>';
80 $output .= '<h3>' . t('Uses') . '</h3>';
82 $output .= '<dt>' . t('Creating and managing users') . '</dt>';
83 $output .= '<dd>' . t('Through the <a href=":people">People administration page</a> you can add and cancel user accounts and assign users to roles. By editing one particular user you can change their username, email address, password, and information in other fields.', [':people' => \Drupal::url('entity.user.collection')]) . '</dd>';
84 $output .= '<dt>' . t('Configuring user roles') . '</dt>';
85 $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. Typically there are two pre-defined roles: <em>Anonymous user</em> (users that are not logged in), and <em>Authenticated user</em> (users that are registered and logged in). Depending on how your site was set up, an <em>Administrator</em> role may also be available: users with this role will automatically be assigned any new permissions whenever a module is enabled. You can create additional roles on the <a href=":roles">Roles administration page</a>.', [':roles' => \Drupal::url('entity.user_role.collection')]) . '</dd>';
86 $output .= '<dt>' . t('Setting permissions') . '</dt>';
87 $output .= '<dd>' . t('After creating roles, you can set permissions for each role on the <a href=":permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing content, editing or creating a particular type of content, administering settings for a particular module, or using a particular function of the site (such as search).', [':permissions_user' => \Drupal::url('user.admin_permissions')]) . '</dd>';
88 $output .= '<dt>' . t('Managing account settings') . '</dt>';
89 $output .= '<dd>' . t('The <a href=":accounts">Account settings page</a> allows you to manage settings for the displayed name of the Anonymous user role, personal contact forms, user registration settings, and account cancellation settings. On this page you can also manage settings for account personalization, and adapt the text for the email messages that users receive when they register or request a password recovery. You may also set which role is automatically assigned new permissions whenever a module is enabled (the Administrator role).', [':accounts' => \Drupal::url('entity.user.admin_form')]) . '</dd>';
90 $output .= '<dt>' . t('Managing user account fields') . '</dt>';
91 $output .= '<dd>' . t('Because User accounts are an entity type, you can extend them by adding fields through the Manage fields tab on the <a href=":accounts">Account settings page</a>. By adding fields for e.g., a picture, a biography, or address, you can a create a custom profile for the users of the website. For background information on entities and fields, see the <a href=":field_help">Field module help page</a>.', [':field_help' => (\Drupal::moduleHandler()->moduleExists('field')) ? \Drupal::url('help.page', ['name' => 'field']) : '#', ':accounts' => \Drupal::url('entity.user.admin_form')]) . '</dd>';
95 case 'user.admin_create':
96 return '<p>' . t("This web page allows administrators to register new users. Users' email addresses and usernames must be unique.") . '</p>';
98 case 'user.admin_permissions':
99 return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href=":role">Roles</a> page to create a role.) Any permissions granted to the Authenticated user role will be given to any user who is logged in to your site. From the <a href=":settings">Account settings</a> page, you can make any role into an Administrator role for the site, meaning that role will be granted all new permissions automatically. You should be careful to ensure that only trusted users are given this access and level of control of your site.', [':role' => \Drupal::url('entity.user_role.collection'), ':settings' => \Drupal::url('entity.user.admin_form')]) . '</p>';
101 case 'entity.user_role.collection':
102 return '<p>' . t('A role defines a group of users that have certain privileges. These privileges are defined on the <a href=":permissions">Permissions page</a>. Here, you can define the names and the display sort order of the roles on your site. It is recommended to order roles from least permissive (for example, Anonymous user) to most permissive (for example, Administrator user). Users who are not logged in have the Anonymous user role. Users who are logged in have the Authenticated user role, plus any other roles granted to their user account.', [':permissions' => \Drupal::url('user.admin_permissions')]) . '</p>';
104 case 'entity.user.field_ui_fields':
105 return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';
107 case 'entity.entity_form_display.user.default':
108 return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';
110 case 'entity.entity_view_display.user.default':
111 return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
116 * Implements hook_theme().
118 function user_theme() {
121 'render element' => 'elements',
124 'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
130 * Implements hook_js_settings_alter().
132 function user_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
133 // Provide the user ID in drupalSettings to allow JavaScript code to customize
134 // the experience for the end user, rather than the server side, which would
135 // break the render cache.
136 // Similarly, provide a permissions hash, so that permission-dependent data
137 // can be reliably cached on the client side.
138 $user = \Drupal::currentUser();
139 $settings['user']['uid'] = $user->id();
140 $settings['user']['permissionsHash'] = \Drupal::service('user_permissions_hash_generator')->generate($user);
144 * Returns whether this site supports the default user picture feature.
146 * This approach preserves compatibility with node/comment templates. Alternate
147 * user picture implementations (e.g., Gravatar) should provide their own
148 * add/edit/delete forms and populate the 'picture' variable during the
151 function user_picture_enabled() {
152 $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
153 return isset($field_definitions['user_picture']);
157 * Implements hook_entity_extra_field_info().
159 function user_entity_extra_field_info() {
160 $fields['user']['user']['form']['account'] = [
161 'label' => t('User name and password'),
162 'description' => t('User module account form elements.'),
165 $fields['user']['user']['form']['language'] = [
166 'label' => t('Language settings'),
167 'description' => t('User module form element.'),
170 if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
171 $fields['user']['user']['form']['timezone'] = [
172 'label' => t('Timezone'),
173 'description' => t('System module form element.'),
178 $fields['user']['user']['display']['member_for'] = [
179 'label' => t('Member for'),
180 'description' => t("User module 'member for' view element."),
188 * Loads multiple users based on certain conditions.
190 * This function should be used whenever you need to load more than one user
191 * from the database. Users are loaded into memory and will not require
192 * database access if loaded again during the same page request.
195 * (optional) An array of entity IDs. If omitted, all entities are loaded.
197 * A boolean indicating that the internal cache should be reset. Use this if
198 * loading a user object which has been altered during the page request.
201 * An array of user objects, indexed by uid.
203 * @see entity_load_multiple()
204 * @see \Drupal\user\Entity\User::load()
205 * @see user_load_by_mail()
206 * @see user_load_by_name()
207 * @see \Drupal\Core\Entity\Query\QueryInterface
209 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
210 * Use \Drupal\user\Entity\User::loadMultiple().
212 function user_load_multiple(array $uids = NULL, $reset = FALSE) {
214 \Drupal::entityManager()->getStorage('user')->resetCache($uids);
216 return User::loadMultiple($uids);
220 * Loads a user object.
223 * Integer specifying the user ID to load.
225 * TRUE to reset the internal cache and load from the database; FALSE
226 * (default) to load from the internal cache, if set.
228 * @return \Drupal\user\UserInterface
229 * A fully-loaded user object upon successful user load, or NULL if the user
232 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
233 * Use \Drupal\user\Entity\User::load().
235 * @see \Drupal\user\Entity\User::loadMultiple()
237 function user_load($uid, $reset = FALSE) {
239 \Drupal::entityManager()->getStorage('user')->resetCache([$uid]);
241 return User::load($uid);
245 * Fetches a user object by email address.
247 * @param string $mail
248 * String with the account's email address.
249 * @return object|bool
250 * A fully-loaded $user object upon successful user load or FALSE if user
253 * @see \Drupal\user\Entity\User::loadMultiple()
255 function user_load_by_mail($mail) {
256 $users = \Drupal::entityTypeManager()->getStorage('user')
257 ->loadByProperties(['mail' => $mail]);
258 return $users ? reset($users) : FALSE;
262 * Fetches a user object by account name.
264 * @param string $name
265 * String with the account's user name.
266 * @return object|bool
267 * A fully-loaded $user object upon successful user load or FALSE if user
270 * @see \Drupal\user\Entity\User::loadMultiple()
272 function user_load_by_name($name) {
273 $users = \Drupal::entityTypeManager()->getStorage('user')
274 ->loadByProperties(['name' => $name]);
275 return $users ? reset($users) : FALSE;
279 * Verify the syntax of the given name.
281 * @param string $name
282 * The user name to validate.
284 * @return string|null
285 * A translated violation message if the name is invalid or NULL if the name
288 function user_validate_name($name) {
289 $definition = BaseFieldDefinition::create('string')
290 ->addConstraint('UserName', []);
291 $data = \Drupal::typedDataManager()->create($definition);
292 $data->setValue($name);
293 $violations = $data->validate();
294 if (count($violations) > 0) {
295 return $violations[0]->getMessage();
300 * Generate a random alphanumeric password.
302 function user_password($length = 10) {
303 // This variable contains the list of allowable characters for the
304 // password. Note that the number 0 and the letter 'O' have been
305 // removed to avoid confusion between the two. The same is true
306 // of 'I', 1, and 'l'.
307 $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
309 // Zero-based count of characters in the allowable list:
310 $len = strlen($allowable_characters) - 1;
312 // Declare the password as a blank string.
315 // Loop the number of times specified by $length.
316 for ($i = 0; $i < $length; $i++) {
318 // Find a secure random number within the range needed.
319 $index = ord(Crypt::randomBytes(1));
320 } while ($index > $len);
322 // Each iteration, pick a random character from the
323 // allowable string and append it to the password:
324 $pass .= $allowable_characters[$index];
331 * Determine the permissions for one or more roles.
333 * @param array $roles
334 * An array of role IDs.
337 * An array indexed by role ID. Each value is an array of permission strings
338 * for the given role.
340 function user_role_permissions(array $roles) {
341 if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
342 return _user_role_permissions_update($roles);
344 $entities = Role::loadMultiple($roles);
345 $role_permissions = [];
346 foreach ($roles as $rid) {
347 $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : [];
349 return $role_permissions;
353 * Determine the permissions for one or more roles during update.
355 * A separate version is needed because during update the entity system can't
356 * be used and in non-update situations the entity system is preferred because
357 * of the hook system.
359 * @param array $roles
360 * An array of role IDs.
363 * An array indexed by role ID. Each value is an array of permission strings
364 * for the given role.
366 function _user_role_permissions_update($roles) {
367 $role_permissions = [];
368 foreach ($roles as $rid) {
369 $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: [];
371 return $role_permissions;
375 * Checks for usernames blocked by user administration.
377 * @param string $name
378 * A string containing a name of the user.
381 * TRUE if the user is blocked, FALSE otherwise.
383 function user_is_blocked($name) {
384 return (bool) \Drupal::entityQuery('user')
385 ->condition('name', $name)
386 ->condition('status', 0)
391 * Implements hook_ENTITY_TYPE_view() for user entities.
393 function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
394 if ($display->getComponent('member_for')) {
395 $build['member_for'] = [
397 '#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . \Drupal::service('date.formatter')->formatTimeDiffSince($account->getCreatedTime()),
403 * Implements hook_ENTITY_TYPE_view_alter() for user entities.
405 * This function adds a default alt tag to the user_picture field to maintain
408 function user_user_view_alter(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
409 if (user_picture_enabled() && !empty($build['user_picture'])) {
410 foreach (Element::children($build['user_picture']) as $key) {
411 $item = $build['user_picture'][$key]['#item'];
412 if (!$item->get('alt')->getValue()) {
413 $item->get('alt')->setValue(\Drupal::translation()->translate('Profile picture for user @username', ['@username' => $account->getUsername()]));
420 * Implements hook_preprocess_HOOK() for block templates.
422 function user_preprocess_block(&$variables) {
423 if ($variables['configuration']['provider'] == 'user') {
424 switch ($variables['elements']['#plugin_id']) {
425 case 'user_login_block':
426 $variables['attributes']['role'] = 'form';
435 * @param \Drupal\Core\Session\AccountInterface $account
436 * The account object for the user whose name is to be formatted.
439 * An unsanitized string with the username to display.
441 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
442 * Use \Drupal\Core\Session\AccountInterface::getDisplayName().
444 * @todo Remove usage in https://www.drupal.org/node/2311219.
446 function user_format_name(AccountInterface $account) {
447 return $account->getDisplayName();
451 * Implements hook_template_preprocess_default_variables_alter().
453 * @see user_user_login()
454 * @see user_user_logout()
456 function user_template_preprocess_default_variables_alter(&$variables) {
457 $user = \Drupal::currentUser();
459 $variables['user'] = clone $user;
460 // Remove password and session IDs, since themes should not need nor see them.
461 unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
463 $variables['is_admin'] = $user->hasPermission('access administration pages');
464 $variables['logged_in'] = $user->isAuthenticated();
468 * Prepares variables for username templates.
470 * Default template: username.html.twig.
472 * Modules that make any changes to variables like 'name' or 'extra' must ensure
473 * that the final string is safe.
475 * @param array $variables
476 * An associative array containing:
477 * - account: The user account (\Drupal\Core\Session\AccountInterface).
479 function template_preprocess_username(&$variables) {
480 $account = $variables['account'] ?: new AnonymousUserSession();
482 $variables['extra'] = '';
483 $variables['uid'] = $account->id();
484 if (empty($variables['uid'])) {
485 if (theme_get_setting('features.comment_user_verification')) {
486 $variables['extra'] = ' (' . t('not verified') . ')';
490 // Set the name to a formatted name that is safe for printing and
491 // that won't break tables by being too long. Keep an unshortened,
492 // unsanitized version, in case other preprocess functions want to implement
493 // their own shortening logic or add markup. If they do so, they must ensure
494 // that $variables['name'] is safe for printing.
495 $name = $account->getDisplayName();
496 $variables['name_raw'] = $account->getUsername();
497 if (Unicode::strlen($name) > 20) {
498 $name = Unicode::truncate($name, 15, FALSE, TRUE);
499 $variables['truncated'] = TRUE;
502 $variables['truncated'] = FALSE;
504 $variables['name'] = $name;
505 $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
508 // Populate link path and attributes if appropriate.
509 if ($variables['uid'] && $variables['profile_access']) {
510 // We are linking to a local user.
511 $variables['attributes']['title'] = t('View user profile.');
512 $variables['link_path'] = 'user/' . $variables['uid'];
514 elseif (!empty($account->homepage)) {
515 // Like the 'class' attribute, the 'rel' attribute can hold a
516 // space-separated set of values, so initialize it as an array to make it
517 // easier for other preprocess functions to append to it.
518 $variables['attributes']['rel'] = 'nofollow';
519 $variables['link_path'] = $account->homepage;
520 $variables['homepage'] = $account->homepage;
523 // We have a link path, so we should generate a URL.
524 if (isset($variables['link_path'])) {
526 $variables['attributes']['href'] = Url::fromUri($variables['link_path'], $variables['link_options'])
530 $variables['attributes']['href'] = Url::fromRoute('entity.user.canonical', [
531 'user' => $variables['uid'],
538 * Finalizes the login process and logs in a user.
540 * The function logs in the user, records a watchdog message about the new
541 * session, saves the login timestamp, calls hook_user_login(), and generates a
544 * The current user is replaced with the passed in account.
546 * @param \Drupal\user\UserInterface $account
547 * The account to log in.
549 * @see hook_user_login()
551 function user_login_finalize(UserInterface $account) {
552 \Drupal::currentUser()->setAccount($account);
553 \Drupal::logger('user')->notice('Session opened for %name.', ['%name' => $account->getUsername()]);
554 // Update the user table timestamp noting user has logged in.
555 // This is also used to invalidate one-time login links.
556 $account->setLastLoginTime(REQUEST_TIME);
557 \Drupal::entityManager()
559 ->updateLastLoginTimestamp($account);
561 // Regenerate the session ID to prevent against session fixation attacks.
562 // This is called before hook_user_login() in case one of those functions
563 // fails or incorrectly does a redirect which would leave the old session
565 \Drupal::service('session')->migrate();
566 \Drupal::service('session')->set('uid', $account->id());
567 \Drupal::moduleHandler()->invokeAll('user_login', [$account]);
571 * Implements hook_user_login().
573 function user_user_login($account) {
574 // Reset static cache of default variables in template_preprocess() to reflect
576 drupal_static_reset('template_preprocess');
580 * Implements hook_user_logout().
582 function user_user_logout($account) {
583 // Reset static cache of default variables in template_preprocess() to reflect
585 drupal_static_reset('template_preprocess');
589 * Generates a unique URL for a user to log in and reset their password.
591 * @param \Drupal\user\UserInterface $account
592 * An object containing the user account.
593 * @param array $options
594 * (optional) A keyed array of settings. Supported options are:
595 * - langcode: A language code to be used when generating locale-sensitive
596 * URLs. If langcode is NULL the users preferred language is used.
599 * A unique URL that provides a one-time log in for the user, from which
600 * they can change their password.
602 function user_pass_reset_url($account, $options = []) {
603 $timestamp = REQUEST_TIME;
604 $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
605 return \Drupal::url('user.reset',
607 'uid' => $account->id(),
608 'timestamp' => $timestamp,
609 'hash' => user_pass_rehash($account, $timestamp),
613 'language' => \Drupal::languageManager()->getLanguage($langcode)
619 * Generates a URL to confirm an account cancellation request.
621 * @param \Drupal\user\UserInterface $account
622 * The user account object.
623 * @param array $options
624 * (optional) A keyed array of settings. Supported options are:
625 * - langcode: A language code to be used when generating locale-sensitive
626 * URLs. If langcode is NULL the users preferred language is used.
629 * A unique URL that may be used to confirm the cancellation of the user
632 * @see user_mail_tokens()
633 * @see \Drupal\user\Controller\UserController::confirmCancel()
635 function user_cancel_url(UserInterface $account, $options = []) {
636 $timestamp = REQUEST_TIME;
637 $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
638 $url_options = ['absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode)];
639 return \Drupal::url('user.cancel_confirm', [
640 'user' => $account->id(),
641 'timestamp' => $timestamp,
642 'hashed_pass' => user_pass_rehash($account, $timestamp)
647 * Creates a unique hash value for use in time-dependent per-user URLs.
649 * This hash is normally used to build a unique and secure URL that is sent to
650 * the user by email for purposes such as resetting the user's password. In
651 * order to validate the URL, the same hash can be generated again, from the
652 * same information, and compared to the hash value from the URL. The hash
653 * contains the time stamp, the user's last login time, the numeric user ID,
654 * and the user's email address.
655 * For a usage example, see user_cancel_url() and
656 * \Drupal\user\Controller\UserController::confirmCancel().
658 * @param \Drupal\user\UserInterface $account
659 * An object containing the user account.
660 * @param int $timestamp
661 * A UNIX timestamp, typically REQUEST_TIME.
664 * A string that is safe for use in URLs and SQL statements.
666 function user_pass_rehash(UserInterface $account, $timestamp) {
668 $data .= $account->getLastLoginTime();
669 $data .= $account->id();
670 $data .= $account->getEmail();
671 return Crypt::hmacBase64($data, Settings::getHashSalt() . $account->getPassword());
675 * Cancel a user account.
677 * Since the user cancellation process needs to be run in a batch, either
678 * Form API will invoke it, or batch_process() needs to be invoked after calling
679 * this function and should define the path to redirect to.
682 * An array of submitted form values.
684 * The user ID of the user account to cancel.
685 * @param string $method
686 * The account cancellation method to use.
688 * @see _user_cancel()
690 function user_cancel($edit, $uid, $method) {
691 $account = User::load($uid);
694 drupal_set_message(t('The user account %id does not exist.', ['%id' => $uid]), 'error');
695 \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
699 // Initialize batch (to set title).
701 'title' => t('Cancelling account'),
706 // When the 'user_cancel_delete' method is used, user_delete() is called,
707 // which invokes hook_ENTITY_TYPE_predelete() and hook_ENTITY_TYPE_delete()
708 // for the user entity. Modules should use those hooks to respond to the
710 if ($method != 'user_cancel_delete') {
711 // Allow modules to add further sets to this batch.
712 \Drupal::moduleHandler()->invokeAll('user_cancel', [$edit, $account, $method]);
715 // Finish the batch and actually cancel the account.
717 'title' => t('Cancelling user account'),
719 ['_user_cancel', [$edit, $account, $method]],
723 // After cancelling account, ensure that user is logged out.
724 if ($account->id() == \Drupal::currentUser()->id()) {
725 // Batch API stores data in the session, so use the finished operation to
726 // manipulate the current user's session id.
727 $batch['finished'] = '_user_cancel_session_regenerate';
732 // Batch processing is either handled via Form API or has to be invoked
737 * Implements callback_batch_operation().
739 * Last step for cancelling a user account.
741 * Since batch and session API require a valid user account, the actual
742 * cancellation of a user account needs to happen last.
744 * An array of submitted form values.
745 * @param \Drupal\user\UserInterface $account
746 * The user ID of the user account to cancel.
747 * @param string $method
748 * The account cancellation method to use.
752 function _user_cancel($edit, $account, $method) {
753 $logger = \Drupal::logger('user');
756 case 'user_cancel_block':
757 case 'user_cancel_block_unpublish':
759 // Send account blocked notification if option was checked.
760 if (!empty($edit['user_cancel_notify'])) {
761 _user_mail_notify('status_blocked', $account);
765 drupal_set_message(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
766 $logger->notice('Blocked user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
769 case 'user_cancel_reassign':
770 case 'user_cancel_delete':
771 // Send account canceled notification if option was checked.
772 if (!empty($edit['user_cancel_notify'])) {
773 _user_mail_notify('status_canceled', $account);
776 drupal_set_message(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
777 $logger->notice('Deleted user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
781 // After cancelling account, ensure that user is logged out. We can't destroy
782 // their session though, as we might have information in it, and we can't
783 // regenerate it because batch API uses the session ID, we will regenerate it
784 // in _user_cancel_session_regenerate().
785 if ($account->id() == \Drupal::currentUser()->id()) {
786 \Drupal::currentUser()->setAccount(new AnonymousUserSession());
791 * Implements callback_batch_finished().
793 * Finished batch processing callback for cancelling a user account.
797 function _user_cancel_session_regenerate() {
798 // Regenerate the users session instead of calling session_destroy() as we
799 // want to preserve any messages that might have been set.
800 \Drupal::service('session')->migrate();
804 * Helper function to return available account cancellation methods.
806 * See documentation of hook_user_cancel_methods_alter().
809 * An array containing all account cancellation methods as form elements.
811 * @see hook_user_cancel_methods_alter()
812 * @see user_admin_settings()
814 function user_cancel_methods() {
815 $user_settings = \Drupal::config('user.settings');
816 $anonymous_name = $user_settings->get('anonymous');
818 'user_cancel_block' => [
819 'title' => t('Disable the account and keep its content.'),
820 'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your username.'),
822 'user_cancel_block_unpublish' => [
823 'title' => t('Disable the account and unpublish its content.'),
824 'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'),
826 'user_cancel_reassign' => [
827 'title' => t('Delete the account and make its content belong to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
828 'description' => t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
830 'user_cancel_delete' => [
831 'title' => t('Delete the account and its content.'),
832 'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
833 'access' => \Drupal::currentUser()->hasPermission('administer users'),
836 // Allow modules to customize account cancellation methods.
837 \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
839 // Turn all methods into real form elements.
842 '#default_value' => $user_settings->get('cancel_method'),
844 foreach ($methods as $name => $method) {
845 $form['#options'][$name] = $method['title'];
846 // Add the description for the confirmation form. This description is never
847 // shown for the cancel method option, only on the confirmation form.
848 // Therefore, we use a custom #confirm_description property.
849 if (isset($method['description'])) {
850 $form[$name]['#confirm_description'] = $method['description'];
852 if (isset($method['access'])) {
853 $form[$name]['#access'] = $method['access'];
865 function user_delete($uid) {
866 user_delete_multiple([$uid]);
870 * Delete multiple user accounts.
873 * An array of user IDs.
875 * @see hook_ENTITY_TYPE_predelete()
876 * @see hook_ENTITY_TYPE_delete()
878 function user_delete_multiple(array $uids) {
879 entity_delete_multiple('user', $uids);
883 * Generate an array for rendering the given user.
885 * When viewing a user profile, the $page array contains:
887 * - $page['content']['member_for']:
888 * Contains the default "Member for" profile data for a user.
889 * - $page['content']['#user']:
890 * The user account of the profile being viewed.
892 * To theme user profiles, copy core/modules/user/templates/user.html.twig
893 * to your theme directory, and edit it as instructed in that file's comments.
895 * @param \Drupal\user\UserInterface $account
897 * @param string $view_mode
898 * View mode, e.g. 'full'.
899 * @param string|null $langcode
900 * (optional) A language code to use for rendering. Defaults to the global
901 * content language of the current request.
904 * An array as expected by drupal_render().
906 function user_view($account, $view_mode = 'full', $langcode = NULL) {
907 return entity_view($account, $view_mode, $langcode);
911 * Constructs a drupal_render() style array from an array of loaded users.
913 * @param \Drupal\user\UserInterface[] $accounts
914 * An array of user accounts as returned by User::loadMultiple().
915 * @param string $view_mode
916 * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
917 * @param string|null $langcode
918 * (optional) A language code to use for rendering. Defaults to the global
919 * content language of the current request.
922 * An array in the format expected by drupal_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();
1331 // Add logout & user account links or login link.
1332 $links_cache_contexts = [];
1333 if ($user->isAuthenticated()) {
1336 'title' => t('View profile'),
1337 'url' => Url::fromRoute('user.page'),
1339 'title' => t('User account'),
1343 'title' => t('Edit profile'),
1344 'url' => Url::fromRoute('entity.user.edit_form', ['user' => $user->id()]),
1346 'title' => t('Edit user account'),
1350 'title' => t('Log out'),
1351 'url' => Url::fromRoute('user.logout'),
1354 // The "Edit user account" link is per-user.
1355 $links_cache_contexts[] = 'user';
1360 'title' => t('Log in'),
1361 'url' => Url::fromRoute('user.page'),
1367 '#type' => 'toolbar_item',
1370 '#title' => $user->getDisplayName(),
1371 '#url' => Url::fromRoute('user.page'),
1373 'title' => t('My account'),
1374 'class' => ['toolbar-icon', 'toolbar-icon-user'],
1378 // Cacheable per user, because the current user's name is shown.
1384 '#heading' => t('User account actions'),
1387 // Cacheable per "authenticated or not", because the links to
1388 // display depend on that.
1389 'contexts' => Cache::mergeContexts(['user.roles:authenticated'], $links_cache_contexts),
1391 '#theme' => 'links__toolbar_user',
1394 'class' => ['toolbar-menu'],
1401 'user/drupal.user.icons',
1410 * Logs the current user out.
1412 function user_logout() {
1413 $user = \Drupal::currentUser();
1415 \Drupal::logger('user')->notice('Session closed for %name.', ['%name' => $user->getAccountName()]);
1417 \Drupal::moduleHandler()->invokeAll('user_logout', [$user]);
1419 // Destroy the current session, and reset $user to the anonymous user.
1420 // Note: In Symfony the session is intended to be destroyed with
1421 // Session::invalidate(). Regrettably this method is currently broken and may
1422 // lead to the creation of spurious session records in the database.
1423 // @see https://github.com/symfony/symfony/issues/12375
1424 \Drupal::service('session_manager')->destroy();
1425 $user->setAccount(new AnonymousUserSession());
1429 * Prepares variables for user templates.
1431 * Default template: user.html.twig.
1433 * @param array $variables
1434 * An associative array containing:
1435 * - elements: An associative array containing the user information and any
1436 * fields attached to the user. Properties used:
1437 * - #user: A \Drupal\user\Entity\User object. The user account of the
1438 * profile being viewed.
1439 * - attributes: HTML attributes for the containing element.
1441 function template_preprocess_user(&$variables) {
1442 $variables['user'] = $variables['elements']['#user'];
1443 // Helpful $content variable for templates.
1444 foreach (Element::children($variables['elements']) as $key) {
1445 $variables['content'][$key] = $variables['elements'][$key];