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 const USERNAME_MAX_LENGTH = 60;
38 * Only administrators can create user accounts.
40 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
41 * Use \Drupal\user\UserInterface::REGISTER_ADMINISTRATORS_ONLY instead.
43 const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
46 * Visitors can create their own accounts.
48 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
49 * Use \Drupal\user\UserInterface::REGISTER_VISITORS instead.
51 const USER_REGISTER_VISITORS = 'visitors';
54 * Visitors can create accounts, but they don't become active without
55 * administrative approval.
57 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
58 * Use \Drupal\user\UserInterface::REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL
61 const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
64 * Implements hook_help().
66 function user_help($route_name, RouteMatchInterface $route_match) {
67 switch ($route_name) {
68 case 'help.page.user':
70 $output .= '<h3>' . t('About') . '</h3>';
71 $output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles and permissions. For more information, see the <a href=":user_docs">online documentation for the User module</a>.', [':user_docs' => 'https://www.drupal.org/documentation/modules/user']) . '</p>';
72 $output .= '<h3>' . t('Uses') . '</h3>';
74 $output .= '<dt>' . t('Creating and managing users') . '</dt>';
75 $output .= '<dd>' . t('Through the <a href=":people">People administration page</a> you can add and cancel user accounts and assign users to roles. By editing one particular user you can change their username, email address, password, and information in other fields.', [':people' => \Drupal::url('entity.user.collection')]) . '</dd>';
76 $output .= '<dt>' . t('Configuring user roles') . '</dt>';
77 $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. Typically there are two pre-defined roles: <em>Anonymous user</em> (users that are not logged in), and <em>Authenticated user</em> (users that are registered and logged in). Depending on how your site was set up, an <em>Administrator</em> role may also be available: users with this role will automatically be assigned any new permissions whenever a module is enabled. You can create additional roles on the <a href=":roles">Roles administration page</a>.', [':roles' => \Drupal::url('entity.user_role.collection')]) . '</dd>';
78 $output .= '<dt>' . t('Setting permissions') . '</dt>';
79 $output .= '<dd>' . t('After creating roles, you can set permissions for each role on the <a href=":permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing content, editing or creating a particular type of content, administering settings for a particular module, or using a particular function of the site (such as search).', [':permissions_user' => \Drupal::url('user.admin_permissions')]) . '</dd>';
80 $output .= '<dt>' . t('Managing account settings') . '</dt>';
81 $output .= '<dd>' . t('The <a href=":accounts">Account settings page</a> allows you to manage settings for the displayed name of the Anonymous user role, personal contact forms, user registration settings, and account cancellation settings. On this page you can also manage settings for account personalization, and adapt the text for the email messages that users receive when they register or request a password recovery. You may also set which role is automatically assigned new permissions whenever a module is enabled (the Administrator role).', [':accounts' => \Drupal::url('entity.user.admin_form')]) . '</dd>';
82 $output .= '<dt>' . t('Managing user account fields') . '</dt>';
83 $output .= '<dd>' . t('Because User accounts are an entity type, you can extend them by adding fields through the Manage fields tab on the <a href=":accounts">Account settings page</a>. By adding fields for e.g., a picture, a biography, or address, you can a create a custom profile for the users of the website. For background information on entities and fields, see the <a href=":field_help">Field module help page</a>.', [':field_help' => (\Drupal::moduleHandler()->moduleExists('field')) ? \Drupal::url('help.page', ['name' => 'field']) : '#', ':accounts' => \Drupal::url('entity.user.admin_form')]) . '</dd>';
87 case 'user.admin_create':
88 return '<p>' . t("This web page allows administrators to register new users. Users' email addresses and usernames must be unique.") . '</p>';
90 case 'user.admin_permissions':
91 return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href=":role">Roles</a> page to create a role.) Any permissions granted to the Authenticated user role will be given to any user who is logged in to your site. From the <a href=":settings">Account settings</a> page, you can make any role into an Administrator role for the site, meaning that role will be granted all new permissions automatically. You should be careful to ensure that only trusted users are given this access and level of control of your site.', [':role' => \Drupal::url('entity.user_role.collection'), ':settings' => \Drupal::url('entity.user.admin_form')]) . '</p>';
93 case 'entity.user_role.collection':
94 return '<p>' . t('A role defines a group of users that have certain privileges. These privileges are defined on the <a href=":permissions">Permissions page</a>. Here, you can define the names and the display sort order of the roles on your site. It is recommended to order roles from least permissive (for example, Anonymous user) to most permissive (for example, Administrator user). Users who are not logged in have the Anonymous user role. Users who are logged in have the Authenticated user role, plus any other roles granted to their user account.', [':permissions' => \Drupal::url('user.admin_permissions')]) . '</p>';
96 case 'entity.user.field_ui_fields':
97 return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';
99 case 'entity.entity_form_display.user.default':
100 return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';
102 case 'entity.entity_view_display.user.default':
103 return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
108 * Implements hook_theme().
110 function user_theme() {
113 'render element' => 'elements',
116 'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
122 * Implements hook_js_settings_alter().
124 function user_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
125 // Provide the user ID in drupalSettings to allow JavaScript code to customize
126 // the experience for the end user, rather than the server side, which would
127 // break the render cache.
128 // Similarly, provide a permissions hash, so that permission-dependent data
129 // can be reliably cached on the client side.
130 $user = \Drupal::currentUser();
131 $settings['user']['uid'] = $user->id();
132 $settings['user']['permissionsHash'] = \Drupal::service('user_permissions_hash_generator')->generate($user);
136 * Returns whether this site supports the default user picture feature.
138 * This approach preserves compatibility with node/comment templates. Alternate
139 * user picture implementations (e.g., Gravatar) should provide their own
140 * add/edit/delete forms and populate the 'picture' variable during the
143 function user_picture_enabled() {
144 $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
145 return isset($field_definitions['user_picture']);
149 * Implements hook_entity_extra_field_info().
151 function user_entity_extra_field_info() {
152 $fields['user']['user']['form']['account'] = [
153 'label' => t('User name and password'),
154 'description' => t('User module account form elements.'),
157 $fields['user']['user']['form']['language'] = [
158 'label' => t('Language settings'),
159 'description' => t('User module form element.'),
162 if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
163 $fields['user']['user']['form']['timezone'] = [
164 'label' => t('Timezone'),
165 'description' => t('System module form element.'),
170 $fields['user']['user']['display']['member_for'] = [
171 'label' => t('Member for'),
172 'description' => t('User module \'member for\' view element.'),
180 * Loads multiple users based on certain conditions.
182 * This function should be used whenever you need to load more than one user
183 * from the database. Users are loaded into memory and will not require
184 * database access if loaded again during the same page request.
187 * (optional) An array of entity IDs. If omitted, all entities are loaded.
189 * A boolean indicating that the internal cache should be reset. Use this if
190 * loading a user object which has been altered during the page request.
193 * An array of user objects, indexed by uid.
195 * @see entity_load_multiple()
196 * @see \Drupal\user\Entity\User::load()
197 * @see user_load_by_mail()
198 * @see user_load_by_name()
199 * @see \Drupal\Core\Entity\Query\QueryInterface
201 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
202 * Use \Drupal\user\Entity\User::loadMultiple().
204 function user_load_multiple(array $uids = NULL, $reset = FALSE) {
206 \Drupal::entityManager()->getStorage('user')->resetCache($uids);
208 return User::loadMultiple($uids);
212 * Loads a user object.
215 * Integer specifying the user ID to load.
217 * TRUE to reset the internal cache and load from the database; FALSE
218 * (default) to load from the internal cache, if set.
220 * @return \Drupal\user\UserInterface
221 * A fully-loaded user object upon successful user load, or NULL if the user
224 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
225 * Use \Drupal\user\Entity\User::load().
227 * @see \Drupal\user\Entity\User::loadMultiple()
229 function user_load($uid, $reset = FALSE) {
231 \Drupal::entityManager()->getStorage('user')->resetCache([$uid]);
233 return User::load($uid);
237 * Fetches a user object by email address.
239 * @param string $mail
240 * String with the account's email address.
241 * @return object|bool
242 * A fully-loaded $user object upon successful user load or FALSE if user
245 * @see \Drupal\user\Entity\User::loadMultiple()
247 function user_load_by_mail($mail) {
248 $users = \Drupal::entityTypeManager()->getStorage('user')
249 ->loadByProperties(['mail' => $mail]);
250 return $users ? reset($users) : FALSE;
254 * Fetches a user object by account name.
256 * @param string $name
257 * String with the account's user name.
258 * @return object|bool
259 * A fully-loaded $user object upon successful user load or FALSE if user
262 * @see \Drupal\user\Entity\User::loadMultiple()
264 function user_load_by_name($name) {
265 $users = \Drupal::entityTypeManager()->getStorage('user')
266 ->loadByProperties(['name' => $name]);
267 return $users ? reset($users) : FALSE;
271 * Verify the syntax of the given name.
273 * @param string $name
274 * The user name to validate.
276 * @return string|null
277 * A translated violation message if the name is invalid or NULL if the name
280 function user_validate_name($name) {
281 $definition = BaseFieldDefinition::create('string')
282 ->addConstraint('UserName', []);
283 $data = \Drupal::typedDataManager()->create($definition);
284 $data->setValue($name);
285 $violations = $data->validate();
286 if (count($violations) > 0) {
287 return $violations[0]->getMessage();
292 * Generate a random alphanumeric password.
294 function user_password($length = 10) {
295 // This variable contains the list of allowable characters for the
296 // password. Note that the number 0 and the letter 'O' have been
297 // removed to avoid confusion between the two. The same is true
298 // of 'I', 1, and 'l'.
299 $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
301 // Zero-based count of characters in the allowable list:
302 $len = strlen($allowable_characters) - 1;
304 // Declare the password as a blank string.
307 // Loop the number of times specified by $length.
308 for ($i = 0; $i < $length; $i++) {
310 // Find a secure random number within the range needed.
311 $index = ord(Crypt::randomBytes(1));
312 } while ($index > $len);
314 // Each iteration, pick a random character from the
315 // allowable string and append it to the password:
316 $pass .= $allowable_characters[$index];
323 * Determine the permissions for one or more roles.
325 * @param array $roles
326 * An array of role IDs.
329 * An array indexed by role ID. Each value is an array of permission strings
330 * for the given role.
332 function user_role_permissions(array $roles) {
333 if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
334 return _user_role_permissions_update($roles);
336 $entities = Role::loadMultiple($roles);
337 $role_permissions = [];
338 foreach ($roles as $rid) {
339 $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : [];
341 return $role_permissions;
345 * Determine the permissions for one or more roles during update.
347 * A separate version is needed because during update the entity system can't
348 * be used and in non-update situations the entity system is preferred because
349 * of the hook system.
351 * @param array $roles
352 * An array of role IDs.
355 * An array indexed by role ID. Each value is an array of permission strings
356 * for the given role.
358 function _user_role_permissions_update($roles) {
359 $role_permissions = [];
360 foreach ($roles as $rid) {
361 $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: [];
363 return $role_permissions;
367 * Checks for usernames blocked by user administration.
369 * @param string $name
370 * A string containing a name of the user.
373 * TRUE if the user is blocked, FALSE otherwise.
375 function user_is_blocked($name) {
376 return (bool) \Drupal::entityQuery('user')
377 ->condition('name', $name)
378 ->condition('status', 0)
383 * Implements hook_ENTITY_TYPE_view() for user entities.
385 function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
386 if ($display->getComponent('member_for')) {
387 $build['member_for'] = [
389 '#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . \Drupal::service('date.formatter')->formatTimeDiffSince($account->getCreatedTime()),
395 * Implements hook_ENTITY_TYPE_view_alter() for user entities.
397 * This function adds a default alt tag to the user_picture field to maintain
400 function user_user_view_alter(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
401 if (user_picture_enabled() && !empty($build['user_picture'])) {
402 foreach (Element::children($build['user_picture']) as $key) {
403 $item = $build['user_picture'][$key]['#item'];
404 if (!$item->get('alt')->getValue()) {
405 $item->get('alt')->setValue(\Drupal::translation()->translate('Profile picture for user @username', ['@username' => $account->getUsername()]));
412 * Implements hook_preprocess_HOOK() for block templates.
414 function user_preprocess_block(&$variables) {
415 if ($variables['configuration']['provider'] == 'user') {
416 switch ($variables['elements']['#plugin_id']) {
417 case 'user_login_block':
418 $variables['attributes']['role'] = 'form';
427 * @param \Drupal\Core\Session\AccountInterface $account
428 * The account object for the user whose name is to be formatted.
431 * An unsanitized string with the username to display.
433 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
434 * Use \Drupal\Core\Session\AccountInterface::getDisplayName().
436 * @todo Remove usage in https://www.drupal.org/node/2311219.
438 function user_format_name(AccountInterface $account) {
439 return $account->getDisplayName();
443 * Implements hook_template_preprocess_default_variables_alter().
445 * @see user_user_login()
446 * @see user_user_logout()
448 function user_template_preprocess_default_variables_alter(&$variables) {
449 $user = \Drupal::currentUser();
451 $variables['user'] = clone $user;
452 // Remove password and session IDs, since themes should not need nor see them.
453 unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
455 $variables['is_admin'] = $user->hasPermission('access administration pages');
456 $variables['logged_in'] = $user->isAuthenticated();
460 * Prepares variables for username templates.
462 * Default template: username.html.twig.
464 * Modules that make any changes to variables like 'name' or 'extra' must ensure
465 * that the final string is safe.
467 * @param array $variables
468 * An associative array containing:
469 * - account: The user account (\Drupal\Core\Session\AccountInterface).
471 function template_preprocess_username(&$variables) {
472 $account = $variables['account'] ?: new AnonymousUserSession();
474 $variables['extra'] = '';
475 $variables['uid'] = $account->id();
476 if (empty($variables['uid'])) {
477 if (theme_get_setting('features.comment_user_verification')) {
478 $variables['extra'] = ' (' . t('not verified') . ')';
482 // Set the name to a formatted name that is safe for printing and
483 // that won't break tables by being too long. Keep an unshortened,
484 // unsanitized version, in case other preprocess functions want to implement
485 // their own shortening logic or add markup. If they do so, they must ensure
486 // that $variables['name'] is safe for printing.
487 $name = $account->getDisplayName();
488 $variables['name_raw'] = $account->getUsername();
489 if (Unicode::strlen($name) > 20) {
490 $name = Unicode::truncate($name, 15, FALSE, TRUE);
491 $variables['truncated'] = TRUE;
494 $variables['truncated'] = FALSE;
496 $variables['name'] = $name;
497 $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
500 // Populate link path and attributes if appropriate.
501 if ($variables['uid'] && $variables['profile_access']) {
502 // We are linking to a local user.
503 $variables['attributes']['title'] = t('View user profile.');
504 $variables['link_path'] = 'user/' . $variables['uid'];
506 elseif (!empty($account->homepage)) {
507 // Like the 'class' attribute, the 'rel' attribute can hold a
508 // space-separated set of values, so initialize it as an array to make it
509 // easier for other preprocess functions to append to it.
510 $variables['attributes']['rel'] = 'nofollow';
511 $variables['link_path'] = $account->homepage;
512 $variables['homepage'] = $account->homepage;
515 // We have a link path, so we should generate a URL.
516 if (isset($variables['link_path'])) {
518 $variables['attributes']['href'] = Url::fromUri($variables['link_path'], $variables['link_options'])
522 $variables['attributes']['href'] = Url::fromRoute('entity.user.canonical', [
523 'user' => $variables['uid'],
530 * Finalizes the login process and logs in a user.
532 * The function logs in the user, records a watchdog message about the new
533 * session, saves the login timestamp, calls hook_user_login(), and generates a
536 * The current user is replaced with the passed in account.
538 * @param \Drupal\user\UserInterface $account
539 * The account to log in.
541 * @see hook_user_login()
543 function user_login_finalize(UserInterface $account) {
544 \Drupal::currentUser()->setAccount($account);
545 \Drupal::logger('user')->notice('Session opened for %name.', ['%name' => $account->getUsername()]);
546 // Update the user table timestamp noting user has logged in.
547 // This is also used to invalidate one-time login links.
548 $account->setLastLoginTime(REQUEST_TIME);
549 \Drupal::entityManager()
551 ->updateLastLoginTimestamp($account);
553 // Regenerate the session ID to prevent against session fixation attacks.
554 // This is called before hook_user_login() in case one of those functions
555 // fails or incorrectly does a redirect which would leave the old session
557 \Drupal::service('session')->migrate();
558 \Drupal::service('session')->set('uid', $account->id());
559 \Drupal::moduleHandler()->invokeAll('user_login', [$account]);
563 * Implements hook_user_login().
565 function user_user_login($account) {
566 // Reset static cache of default variables in template_preprocess() to reflect
568 drupal_static_reset('template_preprocess');
572 * Implements hook_user_logout().
574 function user_user_logout($account) {
575 // Reset static cache of default variables in template_preprocess() to reflect
577 drupal_static_reset('template_preprocess');
581 * Generates a unique URL for a user to log in and reset their password.
583 * @param \Drupal\user\UserInterface $account
584 * An object containing the user account.
585 * @param array $options
586 * (optional) A keyed array of settings. Supported options are:
587 * - langcode: A language code to be used when generating locale-sensitive
588 * URLs. If langcode is NULL the users preferred language is used.
591 * A unique URL that provides a one-time log in for the user, from which
592 * they can change their password.
594 function user_pass_reset_url($account, $options = []) {
595 $timestamp = REQUEST_TIME;
596 $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
597 return \Drupal::url('user.reset',
599 'uid' => $account->id(),
600 'timestamp' => $timestamp,
601 'hash' => user_pass_rehash($account, $timestamp),
605 'language' => \Drupal::languageManager()->getLanguage($langcode)
611 * Generates a URL to confirm an account cancellation request.
613 * @param \Drupal\user\UserInterface $account
614 * The user account object.
615 * @param array $options
616 * (optional) A keyed array of settings. Supported options are:
617 * - langcode: A language code to be used when generating locale-sensitive
618 * URLs. If langcode is NULL the users preferred language is used.
621 * A unique URL that may be used to confirm the cancellation of the user
624 * @see user_mail_tokens()
625 * @see \Drupal\user\Controller\UserController::confirmCancel()
627 function user_cancel_url(UserInterface $account, $options = []) {
628 $timestamp = REQUEST_TIME;
629 $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
630 $url_options = ['absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode)];
631 return \Drupal::url('user.cancel_confirm', [
632 'user' => $account->id(),
633 'timestamp' => $timestamp,
634 'hashed_pass' => user_pass_rehash($account, $timestamp)
639 * Creates a unique hash value for use in time-dependent per-user URLs.
641 * This hash is normally used to build a unique and secure URL that is sent to
642 * the user by email for purposes such as resetting the user's password. In
643 * order to validate the URL, the same hash can be generated again, from the
644 * same information, and compared to the hash value from the URL. The hash
645 * contains the time stamp, the user's last login time, the numeric user ID,
646 * and the user's email address.
647 * For a usage example, see user_cancel_url() and
648 * \Drupal\user\Controller\UserController::confirmCancel().
650 * @param \Drupal\user\UserInterface $account
651 * An object containing the user account.
652 * @param int $timestamp
653 * A UNIX timestamp, typically REQUEST_TIME.
656 * A string that is safe for use in URLs and SQL statements.
658 function user_pass_rehash(UserInterface $account, $timestamp) {
660 $data .= $account->getLastLoginTime();
661 $data .= $account->id();
662 $data .= $account->getEmail();
663 return Crypt::hmacBase64($data, Settings::getHashSalt() . $account->getPassword());
667 * Cancel a user account.
669 * Since the user cancellation process needs to be run in a batch, either
670 * Form API will invoke it, or batch_process() needs to be invoked after calling
671 * this function and should define the path to redirect to.
674 * An array of submitted form values.
676 * The user ID of the user account to cancel.
677 * @param string $method
678 * The account cancellation method to use.
680 * @see _user_cancel()
682 function user_cancel($edit, $uid, $method) {
683 $account = User::load($uid);
686 drupal_set_message(t('The user account %id does not exist.', ['%id' => $uid]), 'error');
687 \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
691 // Initialize batch (to set title).
693 'title' => t('Cancelling account'),
698 // When the 'user_cancel_delete' method is used, user_delete() is called,
699 // which invokes hook_ENTITY_TYPE_predelete() and hook_ENTITY_TYPE_delete()
700 // for the user entity. Modules should use those hooks to respond to the
702 if ($method != 'user_cancel_delete') {
703 // Allow modules to add further sets to this batch.
704 \Drupal::moduleHandler()->invokeAll('user_cancel', [$edit, $account, $method]);
707 // Finish the batch and actually cancel the account.
709 'title' => t('Cancelling user account'),
711 ['_user_cancel', [$edit, $account, $method]],
715 // After cancelling account, ensure that user is logged out.
716 if ($account->id() == \Drupal::currentUser()->id()) {
717 // Batch API stores data in the session, so use the finished operation to
718 // manipulate the current user's session id.
719 $batch['finished'] = '_user_cancel_session_regenerate';
724 // Batch processing is either handled via Form API or has to be invoked
729 * Implements callback_batch_operation().
731 * Last step for cancelling a user account.
733 * Since batch and session API require a valid user account, the actual
734 * cancellation of a user account needs to happen last.
736 * An array of submitted form values.
737 * @param \Drupal\user\UserInterface $account
738 * The user ID of the user account to cancel.
739 * @param string $method
740 * The account cancellation method to use.
744 function _user_cancel($edit, $account, $method) {
745 $logger = \Drupal::logger('user');
748 case 'user_cancel_block':
749 case 'user_cancel_block_unpublish':
751 // Send account blocked notification if option was checked.
752 if (!empty($edit['user_cancel_notify'])) {
753 _user_mail_notify('status_blocked', $account);
757 drupal_set_message(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
758 $logger->notice('Blocked user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
761 case 'user_cancel_reassign':
762 case 'user_cancel_delete':
763 // Send account canceled notification if option was checked.
764 if (!empty($edit['user_cancel_notify'])) {
765 _user_mail_notify('status_canceled', $account);
768 drupal_set_message(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
769 $logger->notice('Deleted user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
773 // After cancelling account, ensure that user is logged out. We can't destroy
774 // their session though, as we might have information in it, and we can't
775 // regenerate it because batch API uses the session ID, we will regenerate it
776 // in _user_cancel_session_regenerate().
777 if ($account->id() == \Drupal::currentUser()->id()) {
778 \Drupal::currentUser()->setAccount(new AnonymousUserSession());
783 * Implements callback_batch_finished().
785 * Finished batch processing callback for cancelling a user account.
789 function _user_cancel_session_regenerate() {
790 // Regenerate the users session instead of calling session_destroy() as we
791 // want to preserve any messages that might have been set.
792 \Drupal::service('session')->migrate();
796 * Helper function to return available account cancellation methods.
798 * See documentation of hook_user_cancel_methods_alter().
801 * An array containing all account cancellation methods as form elements.
803 * @see hook_user_cancel_methods_alter()
804 * @see user_admin_settings()
806 function user_cancel_methods() {
807 $user_settings = \Drupal::config('user.settings');
808 $anonymous_name = $user_settings->get('anonymous');
810 'user_cancel_block' => [
811 'title' => t('Disable the account and keep its content.'),
812 'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your username.'),
814 'user_cancel_block_unpublish' => [
815 'title' => t('Disable the account and unpublish its content.'),
816 'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'),
818 'user_cancel_reassign' => [
819 'title' => t('Delete the account and make its content belong to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
820 'description' => t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
822 'user_cancel_delete' => [
823 'title' => t('Delete the account and its content.'),
824 'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
825 'access' => \Drupal::currentUser()->hasPermission('administer users'),
828 // Allow modules to customize account cancellation methods.
829 \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
831 // Turn all methods into real form elements.
834 '#default_value' => $user_settings->get('cancel_method'),
836 foreach ($methods as $name => $method) {
837 $form['#options'][$name] = $method['title'];
838 // Add the description for the confirmation form. This description is never
839 // shown for the cancel method option, only on the confirmation form.
840 // Therefore, we use a custom #confirm_description property.
841 if (isset($method['description'])) {
842 $form[$name]['#confirm_description'] = $method['description'];
844 if (isset($method['access'])) {
845 $form[$name]['#access'] = $method['access'];
857 function user_delete($uid) {
858 user_delete_multiple([$uid]);
862 * Delete multiple user accounts.
865 * An array of user IDs.
867 * @see hook_ENTITY_TYPE_predelete()
868 * @see hook_ENTITY_TYPE_delete()
870 function user_delete_multiple(array $uids) {
871 entity_delete_multiple('user', $uids);
875 * Generate an array for rendering the given user.
877 * When viewing a user profile, the $page array contains:
879 * - $page['content']['member_for']:
880 * Contains the default "Member for" profile data for a user.
881 * - $page['content']['#user']:
882 * The user account of the profile being viewed.
884 * To theme user profiles, copy core/modules/user/templates/user.html.twig
885 * to your theme directory, and edit it as instructed in that file's comments.
887 * @param \Drupal\user\UserInterface $account
889 * @param string $view_mode
890 * View mode, e.g. 'full'.
891 * @param string|null $langcode
892 * (optional) A language code to use for rendering. Defaults to the global
893 * content language of the current request.
896 * An array as expected by drupal_render().
898 function user_view($account, $view_mode = 'full', $langcode = NULL) {
899 return entity_view($account, $view_mode, $langcode);
903 * Constructs a drupal_render() style array from an array of loaded users.
905 * @param \Drupal\user\UserInterface[] $accounts
906 * An array of user accounts as returned by User::loadMultiple().
907 * @param string $view_mode
908 * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
909 * @param string|null $langcode
910 * (optional) A language code to use for rendering. Defaults to the global
911 * content language of the current request.
914 * An array in the format expected by drupal_render().
916 function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
917 return entity_view_multiple($accounts, $view_mode, $langcode);
921 * Implements hook_mail().
923 function user_mail($key, &$message, $params) {
924 $token_service = \Drupal::token();
925 $language_manager = \Drupal::languageManager();
926 $langcode = $message['langcode'];
927 $variables = ['user' => $params['account']];
929 $language = $language_manager->getLanguage($params['account']->getPreferredLangcode());
930 $original_language = $language_manager->getConfigOverrideLanguage();
931 $language_manager->setConfigOverrideLanguage($language);
932 $mail_config = \Drupal::config('user.mail');
934 $token_options = ['langcode' => $langcode, 'callback' => 'user_mail_tokens', 'clear' => TRUE];
935 $message['subject'] .= PlainTextOutput::renderFromHtml($token_service->replace($mail_config->get($key . '.subject'), $variables, $token_options));
936 $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);
938 $language_manager->setConfigOverrideLanguage($original_language);
943 * Token callback to add unsafe tokens for user mails.
945 * This function is used by \Drupal\Core\Utility\Token::replace() to set up
946 * some additional tokens that can be used in email messages generated by
949 * @param array $replacements
950 * An associative array variable containing mappings from token names to
951 * values (for use with strtr()).
953 * An associative array of token replacement values. If the 'user' element
954 * exists, it must contain a user account object with the following
956 * - login: The UNIX timestamp of the user's last login.
957 * - pass: The hashed account login password.
958 * @param array $options
959 * A keyed array of settings and flags to control the token replacement
960 * process. See \Drupal\Core\Utility\Token::replace().
962 function user_mail_tokens(&$replacements, $data, $options) {
963 if (isset($data['user'])) {
964 $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
965 $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
969 /*** Administrative features ***********************************************/
972 * Retrieves the names of roles matching specified conditions.
974 * @param bool $membersonly
975 * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
977 * @param string|null $permission
978 * (optional) A string containing a permission. If set, only roles
979 * containing that permission are returned. Defaults to NULL, which
983 * An associative array with the role id as the key and the role name as
986 function user_role_names($membersonly = FALSE, $permission = NULL) {
987 return array_map(function ($item) {
988 return $item->label();
989 }, user_roles($membersonly, $permission));
993 * Implements hook_ENTITY_TYPE_insert() for user_role entities.
995 function user_user_role_insert(RoleInterface $role) {
996 // Ignore the authenticated and anonymous roles or the role is being synced.
997 if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
1001 $add_id = 'user_add_role_action.' . $role->id();
1002 if (!Action::load($add_id)) {
1003 $action = Action::create([
1006 'label' => t('Add the @label role to the selected users', ['@label' => $role->label()]),
1007 'configuration' => [
1008 'rid' => $role->id(),
1010 'plugin' => 'user_add_role_action',
1012 $action->trustData()->save();
1014 $remove_id = 'user_remove_role_action.' . $role->id();
1015 if (!Action::load($remove_id)) {
1016 $action = Action::create([
1019 'label' => t('Remove the @label role from the selected users', ['@label' => $role->label()]),
1020 'configuration' => [
1021 'rid' => $role->id(),
1023 'plugin' => 'user_remove_role_action',
1025 $action->trustData()->save();
1030 * Implements hook_ENTITY_TYPE_delete() for user_role entities.
1032 function user_user_role_delete(RoleInterface $role) {
1033 // Delete role references for all users.
1034 $user_storage = \Drupal::entityManager()->getStorage('user');
1035 $user_storage->deleteRoleReferences([$role->id()]);
1037 // Ignore the authenticated and anonymous roles or the role is being synced.
1038 if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
1042 $actions = Action::loadMultiple([
1043 'user_add_role_action.' . $role->id(),
1044 'user_remove_role_action.' . $role->id(),
1046 foreach ($actions as $action) {
1052 * Retrieve an array of roles matching specified conditions.
1054 * @param bool $membersonly
1055 * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
1057 * @param string|null $permission
1058 * (optional) A string containing a permission. If set, only roles
1059 * containing that permission are returned. Defaults to NULL, which
1060 * returns all roles.
1062 * @return \Drupal\user\RoleInterface[]
1063 * An associative array with the role id as the key and the role object as
1066 function user_roles($membersonly = FALSE, $permission = NULL) {
1067 $roles = Role::loadMultiple();
1069 unset($roles[RoleInterface::ANONYMOUS_ID]);
1072 if (!empty($permission)) {
1073 $roles = array_filter($roles, function ($role) use ($permission) {
1074 return $role->hasPermission($permission);
1082 * Fetches a user role by role ID.
1084 * @param string $rid
1085 * A string representing the role ID.
1087 * @return \Drupal\user\RoleInterface|null
1088 * A fully-loaded role object if a role with the given ID exists, or NULL
1091 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
1092 * Use \Drupal\user\Entity\Role::load().
1094 function user_role_load($rid) {
1095 return Role::load($rid);
1099 * Change permissions for a user role.
1101 * This function may be used to grant and revoke multiple permissions at once.
1102 * For example, when a form exposes checkboxes to configure permissions for a
1103 * role, the form submit handler may directly pass the submitted values for the
1104 * checkboxes form element to this function.
1107 * The ID of a user role to alter.
1108 * @param array $permissions
1109 * (optional) An associative array, where the key holds the permission name
1110 * and the value determines whether to grant or revoke that permission. Any
1111 * value that evaluates to TRUE will cause the permission to be granted.
1112 * Any value that evaluates to FALSE will cause the permission to be
1116 * 'administer nodes' => 0, // Revoke 'administer nodes'
1117 * 'administer blocks' => FALSE, // Revoke 'administer blocks'
1118 * 'access user profiles' => 1, // Grant 'access user profiles'
1119 * 'access content' => TRUE, // Grant 'access content'
1120 * 'access comments' => 'access comments', // Grant 'access comments'
1123 * Existing permissions are not changed, unless specified in $permissions.
1125 * @see user_role_grant_permissions()
1126 * @see user_role_revoke_permissions()
1128 function user_role_change_permissions($rid, array $permissions = []) {
1129 // Grant new permissions for the role.
1130 $grant = array_filter($permissions);
1131 if (!empty($grant)) {
1132 user_role_grant_permissions($rid, array_keys($grant));
1134 // Revoke permissions for the role.
1135 $revoke = array_diff_assoc($permissions, $grant);
1136 if (!empty($revoke)) {
1137 user_role_revoke_permissions($rid, array_keys($revoke));
1142 * Grant permissions to a user role.
1145 * The ID of a user role to alter.
1146 * @param array $permissions
1147 * (optional) A list of permission names to grant.
1149 * @see user_role_change_permissions()
1150 * @see user_role_revoke_permissions()
1152 function user_role_grant_permissions($rid, array $permissions = []) {
1153 // Grant new permissions for the role.
1154 if ($role = Role::load($rid)) {
1155 foreach ($permissions as $permission) {
1156 $role->grantPermission($permission);
1158 $role->trustData()->save();
1163 * Revoke permissions from a user role.
1166 * The ID of a user role to alter.
1167 * @param array $permissions
1168 * (optional) A list of permission names to revoke.
1170 * @see user_role_change_permissions()
1171 * @see user_role_grant_permissions()
1173 function user_role_revoke_permissions($rid, array $permissions = []) {
1174 // Revoke permissions for the role.
1175 $role = Role::load($rid);
1176 foreach ($permissions as $permission) {
1177 $role->revokePermission($permission);
1179 $role->trustData()->save();
1183 * Conditionally create and send a notification email when a certain
1184 * operation happens on the given user account.
1187 * The operation being performed on the account. Possible values:
1188 * - 'register_admin_created': Welcome message for user created by the admin.
1189 * - 'register_no_approval_required': Welcome message when user
1191 * - 'register_pending_approval': Welcome message, user pending admin
1193 * - 'password_reset': Password recovery request.
1194 * - 'status_activated': Account activated.
1195 * - 'status_blocked': Account blocked.
1196 * - 'cancel_confirm': Account cancellation request.
1197 * - 'status_canceled': Account canceled.
1199 * @param \Drupal\Core\Session\AccountInterface $account
1200 * The user object of the account being notified. Must contain at
1201 * least the fields 'uid', 'name', and 'mail'.
1202 * @param string $langcode
1203 * (optional) Language code to use for the notification, overriding account
1207 * An array containing various information about the message.
1208 * See \Drupal\Core\Mail\MailManagerInterface::mail() for details.
1210 * @see user_mail_tokens()
1212 function _user_mail_notify($op, $account, $langcode = NULL) {
1213 if (\Drupal::config('user.settings')->get('notify.' . $op)) {
1214 $params['account'] = $account;
1215 $langcode = $langcode ? $langcode : $account->getPreferredLangcode();
1216 // Get the custom site notification email to use as the from email address
1217 // if it has been set.
1218 $site_mail = \Drupal::config('system.site')->get('mail_notification');
1219 // If the custom site notification email has not been set, we use the site
1220 // default for this.
1221 if (empty($site_mail)) {
1222 $site_mail = \Drupal::config('system.site')->get('mail');
1224 if (empty($site_mail)) {
1225 $site_mail = ini_get('sendmail_from');
1227 $mail = \Drupal::service('plugin.manager.mail')->mail('user', $op, $account->getEmail(), $langcode, $params, $site_mail);
1228 if ($op == 'register_pending_approval') {
1229 // If a user registered requiring admin approval, notify the admin, too.
1230 // We use the site default language for this.
1231 \Drupal::service('plugin.manager.mail')->mail('user', 'register_pending_approval_admin', $site_mail, \Drupal::languageManager()->getDefaultLanguage()->getId(), $params);
1234 return empty($mail) ? NULL : $mail['result'];
1238 * Implements hook_element_info_alter().
1240 function user_element_info_alter(array &$types) {
1241 if (isset($types['password_confirm'])) {
1242 $types['password_confirm']['#process'][] = 'user_form_process_password_confirm';
1247 * Form element process handler for client-side password validation.
1249 * This #process handler is automatically invoked for 'password_confirm' form
1250 * elements to add the JavaScript and string translations for dynamic password
1253 function user_form_process_password_confirm($element) {
1254 $password_settings = [
1255 'confirmTitle' => t('Passwords match:'),
1256 'confirmSuccess' => t('yes'),
1257 'confirmFailure' => t('no'),
1258 'showStrengthIndicator' => FALSE,
1261 if (\Drupal::config('user.settings')->get('password_strength')) {
1262 $password_settings['showStrengthIndicator'] = TRUE;
1263 $password_settings += [
1264 'strengthTitle' => t('Password strength:'),
1265 'hasWeaknesses' => t('Recommendations to make your password stronger:'),
1266 'tooShort' => t('Make it at least 12 characters'),
1267 'addLowerCase' => t('Add lowercase letters'),
1268 'addUpperCase' => t('Add uppercase letters'),
1269 'addNumbers' => t('Add numbers'),
1270 'addPunctuation' => t('Add punctuation'),
1271 'sameAsUsername' => t('Make it different from your username'),
1272 'weak' => t('Weak'),
1273 'fair' => t('Fair'),
1274 'good' => t('Good'),
1275 'strong' => t('Strong'),
1276 'username' => \Drupal::currentUser()->getUsername(),
1280 $element['#attached']['library'][] = 'user/drupal.user';
1281 $element['#attached']['drupalSettings']['password'] = $password_settings;
1287 * Implements hook_modules_uninstalled().
1289 function user_modules_uninstalled($modules) {
1290 // Remove any potentially orphan module data stored for users.
1291 \Drupal::service('user.data')->delete($modules);
1295 * Saves visitor information as a cookie so it can be reused.
1297 * @param array $values
1298 * An array of key/value pairs to be saved into a cookie.
1300 function user_cookie_save(array $values) {
1301 foreach ($values as $field => $value) {
1302 // Set cookie for 365 days.
1303 setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
1308 * Delete a visitor information cookie.
1310 * @param string $cookie_name
1311 * A cookie name such as 'homepage'.
1313 function user_cookie_delete($cookie_name) {
1314 setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
1318 * Implements hook_toolbar().
1320 function user_toolbar() {
1321 $user = \Drupal::currentUser();
1323 // Add logout & user account links or login link.
1324 $links_cache_contexts = [];
1325 if ($user->isAuthenticated()) {
1328 'title' => t('View profile'),
1329 'url' => Url::fromRoute('user.page'),
1331 'title' => t('User account'),
1335 'title' => t('Edit profile'),
1336 'url' => Url::fromRoute('entity.user.edit_form', ['user' => $user->id()]),
1338 'title' => t('Edit user account'),
1342 'title' => t('Log out'),
1343 'url' => Url::fromRoute('user.logout'),
1346 // The "Edit user account" link is per-user.
1347 $links_cache_contexts[] = 'user';
1352 'title' => t('Log in'),
1353 'url' => Url::fromRoute('user.page'),
1359 '#type' => 'toolbar_item',
1362 '#title' => $user->getDisplayName(),
1363 '#url' => Url::fromRoute('user.page'),
1365 'title' => t('My account'),
1366 'class' => ['toolbar-icon', 'toolbar-icon-user'],
1370 // Cacheable per user, because the current user's name is shown.
1376 '#heading' => t('User account actions'),
1379 // Cacheable per "authenticated or not", because the links to
1380 // display depend on that.
1381 'contexts' => Cache::mergeContexts(['user.roles:authenticated'], $links_cache_contexts),
1383 '#theme' => 'links__toolbar_user',
1386 'class' => ['toolbar-menu'],
1393 'user/drupal.user.icons',
1402 * Logs the current user out.
1404 function user_logout() {
1405 $user = \Drupal::currentUser();
1407 \Drupal::logger('user')->notice('Session closed for %name.', ['%name' => $user->getAccountName()]);
1409 \Drupal::moduleHandler()->invokeAll('user_logout', [$user]);
1411 // Destroy the current session, and reset $user to the anonymous user.
1412 // Note: In Symfony the session is intended to be destroyed with
1413 // Session::invalidate(). Regrettably this method is currently broken and may
1414 // lead to the creation of spurious session records in the database.
1415 // @see https://github.com/symfony/symfony/issues/12375
1416 \Drupal::service('session_manager')->destroy();
1417 $user->setAccount(new AnonymousUserSession());
1421 * Prepares variables for user templates.
1423 * Default template: user.html.twig.
1425 * @param array $variables
1426 * An associative array containing:
1427 * - elements: An associative array containing the user information and any
1428 * fields attached to the user. Properties used:
1429 * - #user: A \Drupal\user\Entity\User object. The user account of the
1430 * profile being viewed.
1431 * - attributes: HTML attributes for the containing element.
1433 function template_preprocess_user(&$variables) {
1434 $variables['user'] = $variables['elements']['#user'];
1435 // Helpful $content variable for templates.
1436 foreach (Element::children($variables['elements']) as $key) {
1437 $variables['content'][$key] = $variables['elements'][$key];