user.module 51.4 KB
Newer Older
1 2
<?php

3 4 5 6 7
/**
 * @file
 * 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 14 15
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Render\Element;
16
use Drupal\Core\Routing\RouteMatchInterface;
17
use Drupal\Core\Session\AccountInterface;
18
use Drupal\Core\Session\AnonymousUserSession;
19
use Drupal\Core\Site\Settings;
20
use Drupal\Core\Url;
21
use Drupal\system\Entity\Action;
22
use Drupal\user\Entity\Role;
23
use Drupal\user\Entity\User;
24
use Drupal\user\RoleInterface;
25
use Drupal\user\UserInterface;
Crell's avatar
Crell committed
26

27 28
/**
 * Maximum length of username text field.
29 30
 *
 * Keep this under 191 characters so we can use a unique constraint in MySQL.
31 32 33
 *
 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
 *   Use \Drupal\user\UserInterface::USERNAME_MAX_LENGTH instead.
34
 */
35
const USERNAME_MAX_LENGTH = 60;
36

37 38
/**
 * Only administrators can create user accounts.
39 40 41
 *
 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
 *   Use \Drupal\user\UserInterface::REGISTER_ADMINISTRATORS_ONLY instead.
42
 */
43
const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
44 45 46

/**
 * Visitors can create their own accounts.
47 48 49
 *
 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
 *   Use \Drupal\user\UserInterface::REGISTER_VISITORS instead.
50
 */
51
const USER_REGISTER_VISITORS = 'visitors';
52 53 54 55

/**
 * Visitors can create accounts, but they don't become active without
 * administrative approval.
56 57 58
 *
 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
 *   Use \Drupal\user\UserInterface::REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL
59
 *   instead.
60
 */
61
const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
62

63
/**
64
 * Implements hook_help().
65
 */
66
function user_help($route_name, RouteMatchInterface $route_match) {
67 68
  switch ($route_name) {
    case 'help.page.user':
69 70
      $output = '';
      $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 73 74
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating and managing users') . '</dt>';
75
      $output .= '<dd>' . t('Through the <a href=":people">People administration page</a> you can add and cancel user accounts and assign users to roles. By editing one particular user you can change their username, email address, password, and information in other fields.', [':people' => \Drupal::url('entity.user.collection')]) . '</dd>';
76
      $output .= '<dt>' . t('Configuring user roles') . '</dt>';
77
      $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. Typically there are two pre-defined roles: <em>Anonymous user</em> (users that are not logged in), and <em>Authenticated user</em> (users that are registered and logged in). Depending on how your site was set up, an <em>Administrator</em> role may also be available: users with this role will automatically be assigned any new permissions whenever a module is enabled. You can create additional roles on the <a href=":roles">Roles administration page</a>.', [':roles' => \Drupal::url('entity.user_role.collection')]) . '</dd>';
78
      $output .= '<dt>' . t('Setting permissions') . '</dt>';
79
      $output .= '<dd>' . t('After creating roles, you can set permissions for each role on the <a href=":permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing content, editing or creating  a particular type of content, administering settings for a particular module, or using a particular function of the site (such as search).', [':permissions_user' => \Drupal::url('user.admin_permissions')]) . '</dd>';
80
      $output .= '<dt>' . t('Managing account settings') . '</dt>';
81
      $output .= '<dd>' . t('The <a href=":accounts">Account settings page</a> allows you to manage settings for the displayed name of the Anonymous user role, personal contact forms, user registration settings, and account cancellation settings. On this page you can also manage settings for account personalization, and adapt the text for the email messages that users receive when they register or request a password recovery. You may also set which role is automatically assigned new permissions whenever a module is enabled (the Administrator role).', [':accounts'  => \Drupal::url('entity.user.admin_form')]) . '</dd>';
82
      $output .= '<dt>' . t('Managing user account fields') . '</dt>';
83
      $output .= '<dd>' . t('Because User accounts are an entity type, you can extend them by adding fields through the Manage fields tab on the <a href=":accounts">Account settings page</a>. By adding fields for e.g., a picture, a biography, or address, you can a create a custom profile for the users of the website. For background information on entities and fields, see the <a href=":field_help">Field module help page</a>.', [':field_help' => (\Drupal::moduleHandler()->moduleExists('field')) ? \Drupal::url('help.page', ['name' => 'field']) : '#', ':accounts' => \Drupal::url('entity.user.admin_form')]) . '</dd>';
84 85
      $output .= '</dl>';
      return $output;
86 87

    case 'user.admin_create':
88
      return '<p>' . t("This web page allows administrators to register new users. Users' email addresses and usernames must be unique.") . '</p>';
89 90

    case 'user.admin_permissions':
91
      return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href=":role">Roles</a> page to create a role.) Any permissions granted to the Authenticated user role will be given to any user who is logged in to your site. From the <a href=":settings">Account settings</a> page, you can make any role into an Administrator role for the site, meaning that role will be granted all new permissions automatically. You should be careful to ensure that only trusted users are given this access and level of control of your site.', [':role' => \Drupal::url('entity.user_role.collection'), ':settings' => \Drupal::url('entity.user.admin_form')]) . '</p>';
92

93
    case 'entity.user_role.collection':
94
      return '<p>' . t('A role defines a group of users that have certain privileges. These privileges are defined on the <a href=":permissions">Permissions page</a>. Here, you can define the names and the display sort order of the roles on your site. It is recommended to order roles from least permissive (for example, Anonymous user) to most permissive (for example, Administrator user). Users who are not logged in have the Anonymous user role. Users who are logged in have the Authenticated user role, plus any other roles granted to their user account.', [':permissions' => \Drupal::url('user.admin_permissions')]) . '</p>';
95

96
    case 'entity.user.field_ui_fields':
97
      return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';
98

99
    case 'entity.entity_form_display.user.default':
100
      return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';
101

102
    case 'entity.entity_view_display.user.default':
103 104 105
      return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
  }
}
106

107
/**
108
 * Implements hook_theme().
109 110
 */
function user_theme() {
111 112
  return [
    'user' => [
113
      'render element' => 'elements',
114 115 116 117 118
    ],
    'username' => [
      'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
    ],
  ];
119 120
}

121
/**
122
 * Implements hook_js_settings_alter().
123
 */
124
function user_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
125 126 127
  // Provide the user ID in drupalSettings to allow JavaScript code to customize
  // the experience for the end user, rather than the server side, which would
  // break the render cache.
128 129 130
  // Similarly, provide a permissions hash, so that permission-dependent data
  // can be reliably cached on the client side.
  $user = \Drupal::currentUser();
131
  $settings['user']['uid'] = $user->id();
132
  $settings['user']['permissionsHash'] = \Drupal::service('user_permissions_hash_generator')->generate($user);
133 134
}

135 136 137 138 139 140 141 142 143
/**
 * Returns whether this site supports the default user picture feature.
 *
 * This approach preserves compatibility with node/comment templates. Alternate
 * user picture implementations (e.g., Gravatar) should provide their own
 * add/edit/delete forms and populate the 'picture' variable during the
 * preprocess stage.
 */
function user_picture_enabled() {
144 145
  $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
  return isset($field_definitions['user_picture']);
146 147
}

148
/**
149
 * Implements hook_entity_extra_field_info().
150
 */
151
function user_entity_extra_field_info() {
152
  $fields['user']['user']['form']['account'] = [
153 154 155
    'label' => t('User name and password'),
    'description' => t('User module account form elements.'),
    'weight' => -10,
156 157
  ];
  $fields['user']['user']['form']['language'] = [
158 159 160
    'label' => t('Language settings'),
    'description' => t('User module form element.'),
    'weight' => 0,
161
  ];
162
  if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
163
    $fields['user']['user']['form']['timezone'] = [
164 165 166
      'label' => t('Timezone'),
      'description' => t('System module form element.'),
      'weight' => 6,
167
    ];
168 169
  }

170
  $fields['user']['user']['display']['member_for'] = [
171
    'label' => t('Member for'),
172
    'description' => t("User module 'member for' view element."),
173
    'weight' => 5,
174
  ];
175

176
  return $fields;
177 178
}

179
/**
180
 * Loads multiple users based on certain conditions.
181
 *
182 183 184
 * This function should be used whenever you need to load more than one user
 * from the database. Users are loaded into memory and will not require
 * database access if loaded again during the same page request.
185
 *
186 187
 * @param array $uids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
188
 * @param bool $reset
189 190
 *   A boolean indicating that the internal cache should be reset. Use this if
 *   loading a user object which has been altered during the page request.
191
 *
192
 * @return array
193 194
 *   An array of user objects, indexed by uid.
 *
195
 * @see entity_load_multiple()
196
 * @see \Drupal\user\Entity\User::load()
197 198
 * @see user_load_by_mail()
 * @see user_load_by_name()
199
 * @see \Drupal\Core\Entity\Query\QueryInterface
200 201 202
 *
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal\user\Entity\User::loadMultiple().
203
 */
204
function user_load_multiple(array $uids = NULL, $reset = FALSE) {
205 206 207 208
  if ($reset) {
    \Drupal::entityManager()->getStorage('user')->resetCache($uids);
  }
  return User::loadMultiple($uids);
209
}
210 211

/**
212 213
 * Loads a user object.
 *
214
 * @param int $uid
215
 *   Integer specifying the user ID to load.
216
 * @param bool $reset
217 218 219
 *   TRUE to reset the internal cache and load from the database; FALSE
 *   (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
222 223
 *   cannot be loaded.
 *
224 225 226
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal\user\Entity\User::load().
 *
227
 * @see \Drupal\user\Entity\User::loadMultiple()
228 229
 */
function user_load($uid, $reset = FALSE) {
230
  if ($reset) {
231
    \Drupal::entityManager()->getStorage('user')->resetCache([$uid]);
232 233
  }
  return User::load($uid);
234 235 236
}

/**
237
 * Fetches a user object by email address.
238
 *
239
 * @param string $mail
240
 *   String with the account's email address.
241
 * @return object|bool
242 243 244
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
245
 * @see \Drupal\user\Entity\User::loadMultiple()
246 247
 */
function user_load_by_mail($mail) {
248 249
  $users = \Drupal::entityTypeManager()->getStorage('user')
    ->loadByProperties(['mail' => $mail]);
250
  return $users ? reset($users) : FALSE;
251 252 253
}

/**
254
 * Fetches a user object by account name.
255
 *
256
 * @param string $name
257
 *   String with the account's user name.
258
 * @return object|bool
259 260 261
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
262
 * @see \Drupal\user\Entity\User::loadMultiple()
263 264
 */
function user_load_by_name($name) {
265 266
  $users = \Drupal::entityTypeManager()->getStorage('user')
    ->loadByProperties(['name' => $name]);
267
  return $users ? reset($users) : FALSE;
268 269
}

270 271
/**
 * Verify the syntax of the given name.
272 273 274 275 276 277 278
 *
 * @param string $name
 *   The user name to validate.
 *
 * @return string|null
 *   A translated violation message if the name is invalid or NULL if the name
 *   is valid.
279
 */
280
function user_validate_name($name) {
281
  $definition = BaseFieldDefinition::create('string')
282
    ->addConstraint('UserName', []);
283
  $data = \Drupal::typedDataManager()->create($definition);
284 285 286 287
  $data->setValue($name);
  $violations = $data->validate();
  if (count($violations) > 0) {
    return $violations[0]->getMessage();
288
  }
289 290
}

291 292 293
/**
 * Generate a random alphanumeric password.
 */
294 295
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
296 297
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
298
  // of 'I', 1, and 'l'.
299
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
300

301 302
  // Zero-based count of characters in the allowable list:
  $len = strlen($allowable_characters) - 1;
303

304 305
  // Declare the password as a blank string.
  $pass = '';
306

307
  // Loop the number of times specified by $length.
308
  for ($i = 0; $i < $length; $i++) {
309 310 311 312
    do {
      // Find a secure random number within the range needed.
      $index = ord(Crypt::randomBytes(1));
    } while ($index > $len);
313 314 315

    // Each iteration, pick a random character from the
    // allowable string and append it to the password:
316
    $pass .= $allowable_characters[$index];
317 318 319
  }

  return $pass;
320 321
}

322 323 324
/**
 * Determine the permissions for one or more roles.
 *
325 326
 * @param array $roles
 *   An array of role IDs.
327
 *
328 329 330
 * @return array
 *   An array indexed by role ID. Each value is an array of permission strings
 *   for the given role.
331
 */
332 333 334 335
function user_role_permissions(array $roles) {
  if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
    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() : [];
340
  }
341 342
  return $role_permissions;
}
343

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
/**
 * Determine the permissions for one or more roles during update.
 *
 * A separate version is needed because during update the entity system can't
 * be used and in non-update situations the entity system is preferred because
 * of the hook system.
 *
 * @param array $roles
 *   An array of role IDs.
 *
 * @return array
 *   An array indexed by role ID. Each value is an array of permission strings
 *   for the given role.
 */
function _user_role_permissions_update($roles) {
359
  $role_permissions = [];
360
  foreach ($roles as $rid) {
361
    $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: [];
362 363 364 365
  }
  return $role_permissions;
}

366
/**
367
 * Checks for usernames blocked by user administration.
368
 *
369
 * @param string $name
370 371
 *   A string containing a name of the user.
 *
372 373
 * @return bool
 *   TRUE if the user is blocked, FALSE otherwise.
374 375
 */
function user_is_blocked($name) {
376 377
  return (bool) \Drupal::entityQuery('user')
    ->condition('name', $name)
378
    ->condition('status', 0)
379
    ->execute();
380 381
}

382
/**
383
 * Implements hook_ENTITY_TYPE_view() for user entities.
384
 */
385
function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
386
  if ($display->getComponent('member_for')) {
387
    $build['member_for'] = [
388
      '#type' => 'item',
389
      '#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . \Drupal::service('date.formatter')->formatTimeDiffSince($account->getCreatedTime()),
390
    ];
391
  }
392 393
}

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
/**
 * Implements hook_ENTITY_TYPE_view_alter() for user entities.
 *
 * This function adds a default alt tag to the user_picture field to maintain
 * accessibility.
 */
function user_user_view_alter(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
  if (user_picture_enabled() && !empty($build['user_picture'])) {
    foreach (Element::children($build['user_picture']) as $key) {
      $item = $build['user_picture'][$key]['#item'];
      if (!$item->get('alt')->getValue()) {
        $item->get('alt')->setValue(\Drupal::translation()->translate('Profile picture for user @username', ['@username' => $account->getUsername()]));
      }
    }
  }
}

411
/**
412
 * Implements hook_preprocess_HOOK() for block templates.
413 414
 */
function user_preprocess_block(&$variables) {
415
  if ($variables['configuration']['provider'] == 'user') {
416
    switch ($variables['elements']['#plugin_id']) {
417
      case 'user_login_block':
418
        $variables['attributes']['role'] = 'form';
419 420 421 422 423
        break;
    }
  }
}

424 425 426
/**
 * Format a username.
 *
427
 * @param \Drupal\Core\Session\AccountInterface $account
428 429
 *   The account object for the user whose name is to be formatted.
 *
430
 * @return string
431
 *   An unsanitized string with the username to display.
432
 *
433
 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
434
 *   Use \Drupal\Core\Session\AccountInterface::getDisplayName().
435 436
 *
 * @todo Remove usage in https://www.drupal.org/node/2311219.
437
 */
438
function user_format_name(AccountInterface $account) {
439
  return $account->getDisplayName();
440 441
}

442 443 444 445 446 447 448
/**
 * Implements hook_template_preprocess_default_variables_alter().
 *
 * @see user_user_login()
 * @see user_user_logout()
 */
function user_template_preprocess_default_variables_alter(&$variables) {
449
  $user = \Drupal::currentUser();
450 451

  $variables['user'] = clone $user;
452
  // Remove password and session IDs, since themes should not need nor see them.
453 454
  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();
457 458
}

459
/**
460 461 462 463
 * Prepares variables for username templates.
 *
 * Default template: username.html.twig.
 *
464 465 466
 * Modules that make any changes to variables like 'name' or 'extra' must ensure
 * that the final string is safe.
 *
467 468
 * @param array $variables
 *   An associative array containing:
469
 *   - account: The user account (\Drupal\Core\Session\AccountInterface).
470 471
 */
function template_preprocess_username(&$variables) {
472
  $account = $variables['account'] ?: new AnonymousUserSession();
473 474

  $variables['extra'] = '';
475 476 477 478 479
  $variables['uid'] = $account->id();
  if (empty($variables['uid'])) {
    if (theme_get_setting('features.comment_user_verification')) {
      $variables['extra'] = ' (' . t('not verified') . ')';
    }
480 481 482 483 484 485 486
  }

  // Set the name to a formatted name that is safe for printing and
  // that won't break tables by being too long. Keep an unshortened,
  // unsanitized version, in case other preprocess functions want to implement
  // their own shortening logic or add markup. If they do so, they must ensure
  // that $variables['name'] is safe for printing.
487 488
  $name  = $account->getDisplayName();
  $variables['name_raw'] = $account->getUsername();
489
  if (Unicode::strlen($name) > 20) {
490
    $name = Unicode::truncate($name, 15, FALSE, TRUE);
491 492 493 494
    $variables['truncated'] = TRUE;
  }
  else {
    $variables['truncated'] = FALSE;
495
  }
496
  $variables['name'] = $name;
497
  $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
498

499
  $external = FALSE;
500 501 502
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
503
    $variables['attributes']['title'] = t('View user profile.');
504 505 506 507 508 509
    $variables['link_path'] = 'user/' . $variables['uid'];
  }
  elseif (!empty($account->homepage)) {
    // Like the 'class' attribute, the 'rel' attribute can hold a
    // space-separated set of values, so initialize it as an array to make it
    // easier for other preprocess functions to append to it.
510
    $variables['attributes']['rel'] = 'nofollow';
511 512
    $variables['link_path'] = $account->homepage;
    $variables['homepage'] = $account->homepage;
513
    $external = TRUE;
514
  }
515
  // We have a link path, so we should generate a URL.
516
  if (isset($variables['link_path'])) {
517 518 519 520 521
    if ($external) {
      $variables['attributes']['href'] = Url::fromUri($variables['link_path'], $variables['link_options'])
        ->toString();
    }
    else {
522
      $variables['attributes']['href'] = Url::fromRoute('entity.user.canonical', [
523
        'user' => $variables['uid'],
524
      ])->toString();
525
    }
526 527 528
  }
}

529
/**
530
 * Finalizes the login process and logs in a user.
531
 *
532 533 534
 * The function logs in the user, records a watchdog message about the new
 * session, saves the login timestamp, calls hook_user_login(), and generates a
 * new session.
535
 *
536
 * The current user is replaced with the passed in account.
537
 *
538
 * @param \Drupal\user\UserInterface $account
539
 *   The account to log in.
540 541
 *
 * @see hook_user_login()
542
 */
543
function user_login_finalize(UserInterface $account) {
544
  \Drupal::currentUser()->setAccount($account);
545
  \Drupal::logger('user')->notice('Session opened for %name.', ['%name' => $account->getUsername()]);
546 547
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
548
  $account->setLastLoginTime(REQUEST_TIME);
549
  \Drupal::entityManager()
550
    ->getStorage('user')
551
    ->updateLastLoginTimestamp($account);
552

553
  // Regenerate the session ID to prevent against session fixation attacks.
554 555 556
  // This is called before hook_user_login() in case one of those functions
  // fails or incorrectly does a redirect which would leave the old session
  // in place.
557
  \Drupal::service('session')->migrate();
558
  \Drupal::service('session')->set('uid', $account->id());
559
  \Drupal::moduleHandler()->invokeAll('user_login', [$account]);
560 561
}

562 563 564
/**
 * Implements hook_user_login().
 */
565
function user_user_login($account) {
566 567 568 569 570 571 572 573 574 575 576 577 578 579
  // Reset static cache of default variables in template_preprocess() to reflect
  // the new user.
  drupal_static_reset('template_preprocess');
}

/**
 * Implements hook_user_logout().
 */
function user_user_logout($account) {
  // Reset static cache of default variables in template_preprocess() to reflect
  // the new user.
  drupal_static_reset('template_preprocess');
}

580
/**
581
 * Generates a unique URL for a user to log in and reset their password.
582
 *
583 584
 * @param \Drupal\user\UserInterface $account
 *   An object containing the user account.
585 586 587
 * @param array $options
 *   (optional) A keyed array of settings. Supported options are:
 *   - langcode: A language code to be used when generating locale-sensitive
588
 *    URLs. If langcode is NULL the users preferred language is used.
589
 *
590
 * @return string
591 592 593
 *   A unique URL that provides a one-time log in for the user, from which
 *   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',
598
    [
599 600
      'uid' => $account->id(),
      'timestamp' => $timestamp,
601
      'hash' => user_pass_rehash($account, $timestamp),
602 603
    ],
    [
604 605
      'absolute' => TRUE,
      'language' => \Drupal::languageManager()->getLanguage($langcode)
606
    ]
607
  );
608 609
}

610
/**
611 612
 * Generates a URL to confirm an account cancellation request.
 *
613
 * @param \Drupal\user\UserInterface $account
614
 *   The user account object.
615 616 617
 * @param array $options
 *   (optional) A keyed array of settings. Supported options are:
 *   - langcode: A language code to be used when generating locale-sensitive
618
 *     URLs. If langcode is NULL the users preferred language is used.
619
 *
620
 * @return string
621 622
 *   A unique URL that may be used to confirm the cancellation of the user
 *   account.
623 624
 *
 * @see user_mail_tokens()
625
 * @see \Drupal\user\Controller\UserController::confirmCancel()
626
 */
627
function user_cancel_url(UserInterface $account, $options = []) {
628
  $timestamp = REQUEST_TIME;
629
  $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
630
  $url_options = ['absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode)];
631 632 633
  return \Drupal::url('user.cancel_confirm', [
    'user' => $account->id(),
    'timestamp' => $timestamp,
634
    'hashed_pass' => user_pass_rehash($account, $timestamp)
635
  ], $url_options);
636 637
}

638 639 640 641 642 643
/**
 * Creates a unique hash value for use in time-dependent per-user URLs.
 *
 * This hash is normally used to build a unique and secure URL that is sent to
 * the user by email for purposes such as resetting the user's password. In
 * order to validate the URL, the same hash can be generated again, from the
644 645 646
 * same information, and compared to the hash value from the URL. The hash
 * contains the time stamp, the user's last login time, the numeric user ID,
 * and the user's email address.
647 648
 * For a usage example, see user_cancel_url() and
 * \Drupal\user\Controller\UserController::confirmCancel().
649
 *
650 651
 * @param \Drupal\user\UserInterface $account
 *   An object containing the user account.
652 653
 * @param int $timestamp
 *   A UNIX timestamp, typically REQUEST_TIME.
654
 *
655
 * @return string
656 657
 *   A string that is safe for use in URLs and SQL statements.
 */
658 659 660 661 662 663
function user_pass_rehash(UserInterface $account, $timestamp) {
  $data = $timestamp;
  $data .= $account->getLastLoginTime();
  $data .= $account->id();
  $data .= $account->getEmail();
  return Crypt::hmacBase64($data, Settings::getHashSalt() . $account->getPassword());
664 665
}

666
/**
667 668 669 670 671 672
 * Cancel a user account.
 *
 * Since the user cancellation process needs to be run in a batch, either
 * Form API will invoke it, or batch_process() needs to be invoked after calling
 * this function and should define the path to redirect to.
 *
673
 * @param array $edit
674
 *   An array of submitted form values.
675
 * @param int $uid
676
 *   The user ID of the user account to cancel.
677
 * @param string $method
678
 *   The account cancellation method to use.
679
 *
680
 * @see _user_cancel()
681
 */
682
function user_cancel($edit, $uid, $method) {
683
  $account = User::load($uid);
684 685

  if (!$account) {
686 687
    drupal_set_message(t('The user account %id does not exist.', ['%id' => $uid]), 'error');
    \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
688 689 690 691
    return;
  }

  // Initialize batch (to set title).
692
  $batch = [
693
    'title' => t('Cancelling account'),
694 695
    'operations' => [],
  ];
696 697
  batch_set($batch);

698
  // When the 'user_cancel_delete' method is used, user_delete() is called,
699 700 701
  // which invokes hook_ENTITY_TYPE_predelete() and hook_ENTITY_TYPE_delete()
  // for the user entity. Modules should use those hooks to respond to the
  // account deletion.
702 703
  if ($method != 'user_cancel_delete') {
    // Allow modules to add further sets to this batch.
704
    \Drupal::moduleHandler()->invokeAll('user_cancel', [$edit, $account, $method]);
705
  }
706 707

  // Finish the batch and actually cancel the account.
708
  $batch = [
709
    'title' => t('Cancelling user account'),
710 711 712 713
    'operations' => [
      ['_user_cancel', [$edit, $account, $method]],
    ],
  ];
714 715

  // After cancelling account, ensure that user is logged out.
716
  if ($account->id() == \Drupal::currentUser()->id()) {
717 718 719 720 721
    // Batch API stores data in the session, so use the finished operation to
    // manipulate the current user's session id.
    $batch['finished'] = '_user_cancel_session_regenerate';
  }

722 723 724 725 726 727 728
  batch_set($batch);

  // Batch processing is either handled via Form API or has to be invoked
  // manually.
}

/**
729 730 731
 * Implements callback_batch_operation().
 *
 * Last step for cancelling a user account.
732 733 734
 *
 * Since batch and session API require a valid user account, the actual
 * cancellation of a user account needs to happen last.
735 736 737 738 739 740
 * @param array $edit
 *   An array of submitted form values.
 * @param \Drupal\user\UserInterface $account
 *   The user ID of the user account to cancel.
 * @param string $method
 *   The account cancellation method to use.
741 742 743 744
 *
 * @see user_cancel()
 */
function _user_cancel($edit, $account, $method) {
745
  $logger = \Drupal::logger('user');
746 747 748 749 750 751 752 753 754

  switch ($method) {
    case 'user_cancel_block':
    case 'user_cancel_block_unpublish':
    default:
      // Send account blocked notification if option was checked.
      if (!empty($edit['user_cancel_notify'])) {
        _user_mail_notify('status_blocked', $account);
      }
755
      $account->block();
756
      $account->save();
757 758
      drupal_set_message(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
      $logger->notice('Blocked user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
759 760 761 762 763 764 765 766
      break;

    case 'user_cancel_reassign':
    case 'user_cancel_delete':
      // Send account canceled notification if option was checked.
      if (!empty($edit['user_cancel_notify'])) {
        _user_mail_notify('status_canceled', $account);
      }
767
      $account->delete();
768 769
      drupal_set_message(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
      $logger->notice('Deleted user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
770 771 772
      break;
  }

773 774 775 776
  // After cancelling account, ensure that user is logged out. We can't destroy
  // their session though, as we might have information in it, and we can't
  // regenerate it because batch API uses the session ID, we will regenerate it
  // in _user_cancel_session_regenerate().
777 778
  if ($account->id() == \Drupal::currentUser()->id()) {
    \Drupal::currentUser()->setAccount(new AnonymousUserSession());
779
  }
780 781
}

782
/**
783 784
 * Implements callback_batch_finished().
 *
785 786 787 788 789 790 791
 * Finished batch processing callback for cancelling a user account.
 *
 * @see user_cancel()
 */
function _user_cancel_session_regenerate() {
  // Regenerate the users session instead of calling session_destroy() as we
  // want to preserve any messages that might have been set.
792
  \Drupal::service('session')->migrate();
793 794
}

795 796 797 798 799 800 801 802 803 804 805 806
/**
 * Helper function to return available account cancellation methods.
 *
 * See documentation of hook_user_cancel_methods_alter().
 *
 * @return array
 *   An array containing all account cancellation methods as form elements.
 *
 * @see hook_user_cancel_methods_alter()
 * @see user_admin_settings()
 */
function user_cancel_methods() {
807
  $user_settings = \Drupal::config('user.settings');
808
  $anonymous_name = $user_settings->get('anonymous');
809 810
  $methods = [
    'user_cancel_block' => [
811
      'title' => t('Disable the account and keep its content.'),
812
      'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your username.'),
813 814
    ],
    'user_cancel_block_unpublish' => [
815 816
      'title' => t('Disable the account and unpublish its content.'),
      'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'),
817 818 819 820 821 822
    ],
    'user_cancel_reassign' => [
      'title' => t('Delete the account and make its content belong to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
      '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]),
    ],
    'user_cancel_delete' => [
823 824
      'title' => t('Delete the account and its content.'),
      'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
825
      'access' => \Drupal::currentUser()->hasPermission('administer users'),
826 827
    ],
  ];
828
  // Allow modules to customize account cancellation methods.
829
  \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
830 831

  // Turn all methods into real form elements.
832 833
  $form = [
    '#options' => [],
834
    '#default_value' => $user_settings->get('cancel_method'),
835
  ];
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
  foreach ($methods as $name => $method) {
    $form['#options'][$name] = $method['title'];
    // Add the description for the confirmation form. This description is never
    // shown for the cancel method option, only on the confirmation form.
    // Therefore, we use a custom #confirm_description property.
    if (isset($method['description'])) {
      $form[$name]['#confirm_description'] = $method['description'];
    }
    if (isset($method['access'])) {
      $form[$name]['#access'] = $method['access'];
    }
  }
  return $form;
}

851 852 853
/**
 * Delete a user.
 *
854
 * @param int $uid
855 856 857
 *   A user ID.
 */
function user_delete($uid) {
858
  user_delete_multiple([$uid]);
859 860 861 862 863
}

/**
 * Delete multiple user accounts.
 *
864
 * @param int[] $uids
865
 *   An array of user IDs.
866
 *
867 868
 * @see hook_ENTITY_TYPE_predelete()
 * @see hook_ENTITY_TYPE_delete()
869 870
 */
function user_delete_multiple(array $uids) {
871
  entity_delete_multiple('user', $uids);
872 873
}

874
/**
875 876 877 878
 * Generate an array for rendering the given user.
 *
 * When viewing a user profile, the $page array contains:
 *
879 880
 * - $page['content']['member_for']:
 *   Contains the default "Member for" profile data for a user.
881
 * - $page['content']['#user']:
882 883
 *   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.
886
 *
887
 * @param \Drupal\user\UserInterface $account
888
 *   A user object.
889
 * @param string $view_mode
890
 *   View mode, e.g. 'full'.
891
 * @param string|null $langcode
892 893
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
894
 *
895
 * @return array
896 897
 *   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);
900 901 902
}

/**
903
 * Constructs a drupal_render() style array from an array of loaded users.
904
 *
905
 * @param \Drupal\user\UserInterface[] $accounts
906
 *   An array of user accounts as returned by User::loadMultiple().
907
 * @param string $view_mode
908
 *   (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
909
 * @param string|null $langcode
910 911
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
912
 *
913
 * @return array
914
 *   An array in the format expected by drupal_render().
915
 */
916
function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
917
  return entity_view_multiple($accounts, $view_mode, $langcode);
918 919
}

920
/**
921
 * Implements hook_mail().
922 923
 */
function user_mail($key, &$message, $params) {
924
  $token_service = \Drupal::token();
925
  $language_manager = \Drupal::languageManager();
926
  $langcode = $message['langcode'];
927
  $variables = ['user' => $params['account']];
928

929
  $language = $language_manager->getLanguage($params['account']->getPreferredLangcode());
930 931
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);
932
  $mail_config = \Drupal::config('user.mail');
933

934 935
  $token_options = ['langcode' => $langcode, 'callback' => 'user_mail_tokens', 'clear' => TRUE];
  $message['subject'] .= PlainTextOutput::renderFromHtml($token_service->replace($mail_config->get($key . '.subject'), $variables, $token_options));
936
  $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);
937

938 939
  $language_manager->setConfigOverrideLanguage($original_language);

940 941 942 943 944
}

/**
 * Token callback to add unsafe tokens for user mails.
 *
945 946 947
 * This function is used by \Drupal\Core\Utility\Token::replace() to set up
 * some additional tokens that can be used in email messages generated by
 * user_mail().
948
 *
949
 * @param array $replacements
950 951
 *   An associative array variable containing mappings from token names to
 *   values (for use with strtr()).
952
 * @param array $data
953 954 955
 *   An associative array of token replacement values. If the 'user' element
 *   exists, it must contain a user account object with the following
 *   properties:
956
 *   - login: The UNIX timestamp of the user's last login.
957
 *   - pass: The hashed account login password.
958 959 960
 * @param array $options
 *   A keyed array of settings and flags to control the token replacement
 *   process. See \Drupal\Core\Utility\Token::replace().
961 962 963
 */
function user_mail_tokens(&$replacements, $data, $options) {
  if (isset($data['user'])) {
964 965
    $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
    $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
966 967 968
  }
}

969 970
/*** Administrative features ***********************************************/

971
/**
972
 * Retrieves the names of roles matching specified conditions.
973
 *
974 975 976 977 978 979 980
 * @param bool $membersonly
 *   (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
 *   FALSE.
 * @param string|null $permission
 *   (optional) A string containing a permission. If set, only roles
 *    containing that permission are returned. Defaults to NULL, which
 *    returns all roles.
981
 *
982
 * @return array
983 984
 *   An associative array with the role id as the key and the role name as
 *   value.
985
 */
986
function user_role_names($membersonly = FALSE, $permission = NULL) {
987
  return array_map(function ($item) {
988 989 990 991
    return $item->label();
  }, user_roles($membersonly, $permission));
}

992
/**
993
 * Implements hook_ENTITY_TYPE_insert() for user_role entities.
994 995
 */
function user_user_role_insert(RoleInterface $role) {
996
  // Ignore the authenticated and anonymous roles or the role is being synced.
997
  if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
998 999 1000
    return;
  }

1001
  $add_id = 'user_add_role_action.' . $role->id();
1002
  if (!Action::load($add_id)) {
1003
    $action = Action::create([
1004 1005
      'id' => $add_id,
      'type' => 'user',
1006
      'label' => t('Add the @label role to the selected user(s)', ['@label' => $role->label()]),
1007
      'configuration' => [
1008
        'rid' => $role->id(),
1009
      ],
1010
      'plugin' => 'user_add_role_action',
1011
    ]);
1012
    $action->trustData()->save();
1013 1014
  }
  $remove_id = 'user_remove_role_action.' . $role->id();
1015
  if (!Action::load($remove_id)) {
1016
    $action = Action::create([
1017 1018
      'id' => $remove_id,
      'type' => 'user',
1019
      'label' => t('Remove the @label role from the selected user(s)', ['@label' => $role->label()]),
1020
      'configuration' => [
1021
        'rid' => $role->id(),
1022
      ],
1023
      'plugin' => 'user_remove_role_action',
1024
    ]);
1025
    $action->trustData()->save();
1026
  }
1027 1028 1029
}

/**
1030
 * Implements hook_ENTITY_TYPE_delete() for user_role entities.
1031 1032
 */
function user_user_role_delete(RoleInterface $role) {
1033 1034
  // Delete role references for all users.
  $user_storage = \Drupal::entityManager()->getStorage('user');
1035
  $user_storage->deleteRoleReferences([$role->id()]);
1036

1037
  // Ignore the authenticated and anonymous roles or the role is being synced.
1038
  if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
1039 1040 1041
    return;
  }