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
const USERNAME_MAX_LENGTH = 60;
33

34 35 36
/**
 * Only administrators can create user accounts.
 */
37
const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
38 39 40 41

/**
 * Visitors can create their own accounts.
 */
42
const USER_REGISTER_VISITORS = 'visitors';
43 44 45 46 47

/**
 * Visitors can create accounts, but they don't become active without
 * administrative approval.
 */
48
const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
49

50
/**
51
 * Implements hook_help().
52
 */
53
function user_help($route_name, RouteMatchInterface $route_match) {
54 55
  switch ($route_name) {
    case 'help.page.user':
56 57
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
58
      $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>.', array(':user_docs' => 'https://www.drupal.org/documentation/modules/user')) . '</p>';
59 60 61
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating and managing users') . '</dt>';
62
      $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.', array(':people' => \Drupal::url('entity.user.collection'))) . '</dd>';
63
      $output .= '<dt>' . t('Configuring user roles') . '</dt>';
64
      $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>.', array(':roles' => \Drupal::url('entity.user_role.collection'))) . '</dd>';
65
      $output .= '<dt>' . t('Setting permissions') . '</dt>';
66
      $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).', array(':permissions_user' => \Drupal::url('user.admin_permissions'))) . '</dd>';
67
      $output .= '<dt>' . t('Managing account settings') . '</dt>';
68
      $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).', array(':accounts'  => \Drupal::url('entity.user.admin_form'))) . '</dd>';
69
      $output .= '<dt>' . t('Managing user account fields') . '</dt>';
70
      $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>.', array(':field_help'=>(\Drupal::moduleHandler()->moduleExists('field')) ? \Drupal::url('help.page', array('name' => 'field')) : '#', ':accounts' => \Drupal::url('entity.user.admin_form'))) . '</dd>';
71 72
      $output .= '</dl>';
      return $output;
73 74

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

    case 'user.admin_permissions':
78
      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.', array(':role' => \Drupal::url('entity.user_role.collection'), ':settings' => \Drupal::url('entity.user.admin_form'))) . '</p>';
79

80
    case 'entity.user_role.collection':
81
      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.', array(':permissions' => \Drupal::url('user.admin_permissions'))) . '</p>';
82

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

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

89
    case 'entity.entity_view_display.user.default':
90 91 92
      return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
  }
}
93

94
/**
95
 * Implements hook_theme().
96 97 98
 */
function user_theme() {
  return array(
99
    'user' => array(
100
      'render element' => 'elements',
101
    ),
102
    'username' => array(
103
      'variables' => array('account' => NULL, 'attributes' => array(), 'link_options' => array()),
104
    ),
105 106 107
  );
}

108
/**
109
 * Implements hook_js_settings_alter().
110
 */
111
function user_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
112 113 114
  // 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.
115 116 117
  // Similarly, provide a permissions hash, so that permission-dependent data
  // can be reliably cached on the client side.
  $user = \Drupal::currentUser();
118
  $settings['user']['uid'] = $user->id();
119
  $settings['user']['permissionsHash'] = \Drupal::service('user_permissions_hash_generator')->generate($user);
120 121
}

122 123 124 125 126 127 128 129 130
/**
 * 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() {
131 132
  $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
  return isset($field_definitions['user_picture']);
133 134
}

135
/**
136
 * Implements hook_entity_extra_field_info().
137
 */
138
function user_entity_extra_field_info() {
139 140 141 142 143 144 145 146 147 148
  $fields['user']['user']['form']['account'] = array(
    'label' => t('User name and password'),
    'description' => t('User module account form elements.'),
    'weight' => -10,
  );
  $fields['user']['user']['form']['language'] = array(
    'label' => t('Language settings'),
    'description' => t('User module form element.'),
    'weight' => 0,
  );
149
  if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
150 151 152 153 154 155 156 157 158 159 160
    $fields['user']['user']['form']['timezone'] = array(
      'label' => t('Timezone'),
      'description' => t('System module form element.'),
      'weight' => 6,
    );
  }

  $fields['user']['user']['display']['member_for'] = array(
    'label' => t('Member for'),
    'description' => t('User module \'member for\' view element.'),
    'weight' => 5,
161
  );
162

163
  return $fields;
164 165
}

166
/**
167
 * Loads multiple users based on certain conditions.
168
 *
169 170 171
 * 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.
172
 *
173 174
 * @param array $uids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
175
 * @param bool $reset
176 177
 *   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.
178
 *
179
 * @return array
180 181
 *   An array of user objects, indexed by uid.
 *
182
 * @see entity_load_multiple()
183
 * @see \Drupal\user\Entity\User::load()
184 185
 * @see user_load_by_mail()
 * @see user_load_by_name()
186
 * @see \Drupal\Core\Entity\Query\QueryInterface
187 188 189
 *
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal\user\Entity\User::loadMultiple().
190
 */
191
function user_load_multiple(array $uids = NULL, $reset = FALSE) {
192 193 194 195
  if ($reset) {
    \Drupal::entityManager()->getStorage('user')->resetCache($uids);
  }
  return User::loadMultiple($uids);
196
}
197 198

/**
199 200
 * Loads a user object.
 *
201
 * @param int $uid
202
 *   Integer specifying the user ID to load.
203
 * @param bool $reset
204 205 206
 *   TRUE to reset the internal cache and load from the database; FALSE
 *   (default) to load from the internal cache, if set.
 *
207
 * @return \Drupal\user\UserInterface
208
 *   A fully-loaded user object upon successful user load, or NULL if the user
209 210
 *   cannot be loaded.
 *
211 212 213
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal\user\Entity\User::load().
 *
214
 * @see \Drupal\user\Entity\User::loadMultiple()
215 216
 */
function user_load($uid, $reset = FALSE) {
217 218 219 220
  if ($reset) {
    \Drupal::entityManager()->getStorage('user')->resetCache(array($uid));
  }
  return User::load($uid);
221 222 223
}

/**
224
 * Fetches a user object by email address.
225
 *
226
 * @param string $mail
227
 *   String with the account's email address.
228
 * @return object|bool
229 230 231
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
232
 * @see \Drupal\user\Entity\User::loadMultiple()
233 234
 */
function user_load_by_mail($mail) {
235
  $users = entity_load_multiple_by_properties('user', array('mail' => $mail));
236
  return $users ? reset($users) : FALSE;
237 238 239
}

/**
240
 * Fetches a user object by account name.
241
 *
242
 * @param string $name
243
 *   String with the account's user name.
244
 * @return object|bool
245 246 247
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
248
 * @see \Drupal\user\Entity\User::loadMultiple()
249 250
 */
function user_load_by_name($name) {
251
  $users = entity_load_multiple_by_properties('user', array('name' => $name));
252
  return $users ? reset($users) : FALSE;
253 254
}

255 256
/**
 * Verify the syntax of the given name.
257 258 259 260 261 262 263 264
 *
 * @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.
 *
265
 */
266
function user_validate_name($name) {
267
  $definition = BaseFieldDefinition::create('string')
268
    ->addConstraint('UserName', array());
269
  $data = \Drupal::typedDataManager()->create($definition);
270 271 272 273
  $data->setValue($name);
  $violations = $data->validate();
  if (count($violations) > 0) {
    return $violations[0]->getMessage();
274
  }
275 276
}

277 278 279
/**
 * Generate a random alphanumeric password.
 */
280 281
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
282 283
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
284
  // of 'I', 1, and 'l'.
285
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
286

287 288
  // Zero-based count of characters in the allowable list:
  $len = strlen($allowable_characters) - 1;
289

290 291
  // Declare the password as a blank string.
  $pass = '';
292

293
  // Loop the number of times specified by $length.
294
  for ($i = 0; $i < $length; $i++) {
295 296 297 298
    do {
      // Find a secure random number within the range needed.
      $index = ord(Crypt::randomBytes(1));
    } while ($index > $len);
299 300 301

    // Each iteration, pick a random character from the
    // allowable string and append it to the password:
302
    $pass .= $allowable_characters[$index];
303 304 305
  }

  return $pass;
306 307
}

308 309 310
/**
 * Determine the permissions for one or more roles.
 *
311 312
 * @param array $roles
 *   An array of role IDs.
313
 *
314 315 316
 * @return array
 *   An array indexed by role ID. Each value is an array of permission strings
 *   for the given role.
317
 */
318 319 320 321
function user_role_permissions(array $roles) {
  if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
    return _user_role_permissions_update($roles);
  }
322
  $entities = Role::loadMultiple($roles);
323
  $role_permissions = array();
324
  foreach ($roles as $rid) {
325
    $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : array();
326
  }
327 328
  return $role_permissions;
}
329

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
/**
 * 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) {
  $role_permissions = array();
  foreach ($roles as $rid) {
347
    $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: array();
348 349 350 351
  }
  return $role_permissions;
}

352
/**
353
 * Checks for usernames blocked by user administration.
354
 *
355
 * @param string $name
356 357
 *   A string containing a name of the user.
 *
358 359
 * @return bool
 *   TRUE if the user is blocked, FALSE otherwise.
360 361
 */
function user_is_blocked($name) {
362 363
  return (bool) \Drupal::entityQuery('user')
    ->condition('name', $name)
364
    ->condition('status', 0)
365
    ->execute();
366 367
}

368
/**
369
 * Implements hook_ENTITY_TYPE_view() for user entities.
370
 */
371
function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
372
  if ($display->getComponent('member_for')) {
373
    $build['member_for'] = array(
374
      '#type' => 'item',
375
      '#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . \Drupal::service('date.formatter')->formatTimeDiffSince($account->getCreatedTime()),
376 377
    );
  }
378 379
}

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
/**
 * 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()]));
      }
    }
  }
}

397
/**
398
 * Implements hook_preprocess_HOOK() for block templates.
399 400
 */
function user_preprocess_block(&$variables) {
401
  if ($variables['configuration']['provider'] == 'user') {
402
    switch ($variables['elements']['#plugin_id']) {
403
      case 'user_login_block':
404
        $variables['attributes']['role'] = 'form';
405 406 407 408 409
        break;
    }
  }
}

410 411 412
/**
 * Format a username.
 *
413
 * @param \Drupal\Core\Session\AccountInterface $account
414 415
 *   The account object for the user whose name is to be formatted.
 *
416
 * @return string
417
 *   An unsanitized string with the username to display.
418
 *
419
 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
420
 *   Use \Drupal\Core\Session\AccountInterface::getDisplayName().
421 422
 *
 * @todo Remove usage in https://www.drupal.org/node/2311219.
423
 */
424
function user_format_name(AccountInterface $account) {
425
  return $account->getDisplayName();
426 427
}

428 429 430 431 432 433 434
/**
 * Implements hook_template_preprocess_default_variables_alter().
 *
 * @see user_user_login()
 * @see user_user_logout()
 */
function user_template_preprocess_default_variables_alter(&$variables) {
435
  $user = \Drupal::currentUser();
436 437

  $variables['user'] = clone $user;
438
  // Remove password and session IDs, since themes should not need nor see them.
439 440
  unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);

441
  $variables['is_admin'] = $user->hasPermission('access administration pages');
442
  $variables['logged_in'] = $user->isAuthenticated();
443 444
}

445
/**
446 447 448 449 450 451
 * Prepares variables for username templates.
 *
 * Default template: username.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
452
 *   - account: The user account (\Drupal\Core\Session\AccountInterface).
453
 *
454
 * Modules that make any changes to variables like 'name' or 'extra' must ensure
455
 * that the final string is safe.
456 457
 */
function template_preprocess_username(&$variables) {
458
  $account = $variables['account'] ?: new AnonymousUserSession();
459 460

  $variables['extra'] = '';
461 462 463 464 465
  $variables['uid'] = $account->id();
  if (empty($variables['uid'])) {
    if (theme_get_setting('features.comment_user_verification')) {
      $variables['extra'] = ' (' . t('not verified') . ')';
    }
466 467 468 469 470 471 472
  }

  // 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.
473 474
  $name  = $account->getDisplayName();
  $variables['name_raw'] = $account->getUsername();
475
  if (Unicode::strlen($name) > 20) {
476
    $name = Unicode::truncate($name, 15, FALSE, TRUE);
477 478 479 480
    $variables['truncated'] = TRUE;
  }
  else {
    $variables['truncated'] = FALSE;
481
  }
482
  $variables['name'] = $name;
483
  $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
484

485
  $external = FALSE;
486 487 488
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
489
    $variables['attributes']['title'] = t('View user profile.');
490 491 492 493 494 495
    $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.
496
    $variables['attributes']['rel'] = 'nofollow';
497 498
    $variables['link_path'] = $account->homepage;
    $variables['homepage'] = $account->homepage;
499
    $external = TRUE;
500
  }
501
  // We have a link path, so we should generate a URL.
502
  if (isset($variables['link_path'])) {
503 504 505 506 507 508 509 510 511
    if ($external) {
      $variables['attributes']['href'] = Url::fromUri($variables['link_path'], $variables['link_options'])
        ->toString();
    }
    else {
      $variables['attributes']['href'] = Url::fromRoute('entity.user.canonical', array(
        'user' => $variables['uid'],
      ))->toString();
    }
512 513 514
  }
}

515
/**
516
 * Finalizes the login process and logs in a user.
517
 *
518 519 520
 * 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.
521
 *
522
 * The current user is replaced with the passed in account.
523
 *
524
 * @param \Drupal\user\UserInterface $account
525
 *   The account to log in.
526 527
 *
 * @see hook_user_login()
528
 */
529
function user_login_finalize(UserInterface $account) {
530
  \Drupal::currentUser()->setAccount($account);
531
  \Drupal::logger('user')->notice('Session opened for %name.', array('%name' => $account->getUsername()));
532 533
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
534
  $account->setLastLoginTime(REQUEST_TIME);
535
  \Drupal::entityManager()
536
    ->getStorage('user')
537
    ->updateLastLoginTimestamp($account);
538

539
  // Regenerate the session ID to prevent against session fixation attacks.
540 541 542
  // 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.
543
  \Drupal::service('session')->migrate();
544
  \Drupal::service('session')->set('uid', $account->id());
545
  \Drupal::moduleHandler()->invokeAll('user_login', array($account));
546 547
}

548 549 550
/**
 * Implements hook_user_login().
 */
551
function user_user_login($account) {
552 553 554 555 556 557 558 559 560 561 562 563 564 565
  // 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');
}

566 567 568
/**
 * Generates a unique URL for a user to login and reset their password.
 *
569 570
 * @param \Drupal\user\UserInterface $account
 *   An object containing the user account.
571 572 573
 * @param array $options
 *   (optional) A keyed array of settings. Supported options are:
 *   - langcode: A language code to be used when generating locale-sensitive
574
 *    URLs. If langcode is NULL the users preferred language is used.
575
 *
576
 * @return string
577 578 579
 *   A unique URL that provides a one-time log in for the user, from which
 *   they can change their password.
 */
580
function user_pass_reset_url($account, $options = array()) {
581
  $timestamp = REQUEST_TIME;
582
  $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
583 584 585 586
  return \Drupal::url('user.reset',
    array(
      'uid' => $account->id(),
      'timestamp' => $timestamp,
587
      'hash' => user_pass_rehash($account, $timestamp),
588 589 590 591 592 593
    ),
    array(
      'absolute' => TRUE,
      'language' => \Drupal::languageManager()->getLanguage($langcode)
    )
  );
594 595
}

596
/**
597 598
 * Generates a URL to confirm an account cancellation request.
 *
599
 * @param \Drupal\user\UserInterface $account
600
 *   The user account object.
601 602 603
 * @param array $options
 *   (optional) A keyed array of settings. Supported options are:
 *   - langcode: A language code to be used when generating locale-sensitive
604
 *     URLs. If langcode is NULL the users preferred language is used.
605
 *
606
 * @return string
607 608
 *   A unique URL that may be used to confirm the cancellation of the user
 *   account.
609 610
 *
 * @see user_mail_tokens()
611
 * @see \Drupal\user\Controller\UserController::confirmCancel()
612
 */
613
function user_cancel_url(UserInterface $account, $options = array()) {
614
  $timestamp = REQUEST_TIME;
615
  $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
616
  $url_options = array('absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode));
617 618 619
  return \Drupal::url('user.cancel_confirm', [
    'user' => $account->id(),
    'timestamp' => $timestamp,
620
    'hashed_pass' => user_pass_rehash($account, $timestamp)
621
  ], $url_options);
622 623
}

624 625 626 627 628 629
/**
 * 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
630 631 632
 * 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.
633 634
 * For a usage example, see user_cancel_url() and
 * \Drupal\user\Controller\UserController::confirmCancel().
635
 *
636 637
 * @param \Drupal\user\UserInterface $account
 *   An object containing the user account.
638 639
 * @param int $timestamp
 *   A UNIX timestamp, typically REQUEST_TIME.
640
 *
641
 * @return string
642 643
 *   A string that is safe for use in URLs and SQL statements.
 */
644 645 646 647 648 649
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());
650 651
}

652
/**
653 654 655 656 657 658
 * 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.
 *
659
 * @param array $edit
660
 *   An array of submitted form values.
661
 * @param int $uid
662
 *   The user ID of the user account to cancel.
663
 * @param string $method
664
 *   The account cancellation method to use.
665
 *
666
 * @see _user_cancel()
667
 */
668
function user_cancel($edit, $uid, $method) {
669
  $account = User::load($uid);
670 671 672

  if (!$account) {
    drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error');
673
    \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', array('%id' => $uid));
674 675 676 677 678 679 680 681 682 683
    return;
  }

  // Initialize batch (to set title).
  $batch = array(
    'title' => t('Cancelling account'),
    'operations' => array(),
  );
  batch_set($batch);

684
  // When the 'user_cancel_delete' method is used, user_delete() is called,
685 686 687
  // 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.
688 689
  if ($method != 'user_cancel_delete') {
    // Allow modules to add further sets to this batch.
690
    \Drupal::moduleHandler()->invokeAll('user_cancel', array($edit, $account, $method));
691
  }
692 693 694 695 696 697 698 699

  // Finish the batch and actually cancel the account.
  $batch = array(
    'title' => t('Cancelling user account'),
    'operations' => array(
      array('_user_cancel', array($edit, $account, $method)),
    ),
  );
700 701

  // After cancelling account, ensure that user is logged out.
702
  if ($account->id() == \Drupal::currentUser()->id()) {
703 704 705 706 707
    // 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';
  }

708 709 710 711 712 713 714
  batch_set($batch);

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

/**
715 716 717
 * Implements callback_batch_operation().
 *
 * Last step for cancelling a user account.
718 719 720
 *
 * Since batch and session API require a valid user account, the actual
 * cancellation of a user account needs to happen last.
721 722 723 724 725 726
 * @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.
727 728 729 730
 *
 * @see user_cancel()
 */
function _user_cancel($edit, $account, $method) {
731
  $logger = \Drupal::logger('user');
732 733 734 735 736 737 738 739 740

  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);
      }
741
      $account->block();
742
      $account->save();
743 744
      drupal_set_message(t('%name has been disabled.', array('%name' => $account->getDisplayName())));
      $logger->notice('Blocked user: %name %email.', array('%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>'));
745 746 747 748 749 750 751 752
      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);
      }
753
      $account->delete();
754 755
      drupal_set_message(t('%name has been deleted.', array('%name' => $account->getDisplayName())));
      $logger->notice('Deleted user: %name %email.', array('%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>'));
756 757 758
      break;
  }

759 760 761 762
  // 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().
763 764
  if ($account->id() == \Drupal::currentUser()->id()) {
    \Drupal::currentUser()->setAccount(new AnonymousUserSession());
765
  }
766 767
}

768
/**
769 770
 * Implements callback_batch_finished().
 *
771 772 773 774 775 776 777
 * 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.
778
  \Drupal::service('session')->migrate();
779 780
}

781 782 783 784 785 786 787 788 789 790 791 792
/**
 * 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() {
793
  $user_settings = \Drupal::config('user.settings');
794 795 796 797
  $anonymous_name = $user_settings->get('anonymous');
  $methods = array(
    'user_cancel_block' => array(
      'title' => t('Disable the account and keep its content.'),
798
      '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.'),
799 800 801 802 803 804 805 806 807 808 809 810
    ),
    'user_cancel_block_unpublish' => array(
      '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.'),
    ),
    'user_cancel_reassign' => array(
      'title' => t('Delete the account and make its content belong to the %anonymous-name user.', array('%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.', array('%anonymous-name' => $anonymous_name)),
    ),
    'user_cancel_delete' => array(
      '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.'),
811
      'access' => \Drupal::currentUser()->hasPermission('administer users'),
812 813 814
    ),
  );
  // Allow modules to customize account cancellation methods.
815
  \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836

  // Turn all methods into real form elements.
  $form = array(
    '#options' => array(),
    '#default_value' => $user_settings->get('cancel_method'),
  );
  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;
}

837 838 839
/**
 * Delete a user.
 *
840
 * @param int $uid
841 842 843 844 845 846 847 848 849
 *   A user ID.
 */
function user_delete($uid) {
  user_delete_multiple(array($uid));
}

/**
 * Delete multiple user accounts.
 *
850
 * @param int[] $uids
851
 *   An array of user IDs.
852
 *
853 854
 * @see hook_ENTITY_TYPE_predelete()
 * @see hook_ENTITY_TYPE_delete()
855 856
 */
function user_delete_multiple(array $uids) {
857
  entity_delete_multiple('user', $uids);
858 859
}

860
/**
861 862 863 864
 * Generate an array for rendering the given user.
 *
 * When viewing a user profile, the $page array contains:
 *
865 866
 * - $page['content']['member_for']:
 *   Contains the default "Member for" profile data for a user.
867
 * - $page['content']['#user']:
868 869
 *   The user account of the profile being viewed.
 *
870
 * To theme user profiles, copy core/modules/user/templates/user.html.twig
871
 * to your theme directory, and edit it as instructed in that file's comments.
872
 *
873
 * @param \Drupal\user\UserInterface $account
874
 *   A user object.
875
 * @param string $view_mode
876
 *   View mode, e.g. 'full'.
877
 * @param string|null $langcode
878 879
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
880
 *
881
 * @return array
882 883
 *   An array as expected by drupal_render().
 */
884
function user_view($account, $view_mode = 'full', $langcode = NULL) {
885
  return entity_view($account, $view_mode, $langcode);
886 887 888
}

/**
889
 * Constructs a drupal_render() style array from an array of loaded users.
890
 *
891
 * @param \Drupal\user\UserInterface[] $accounts
892
 *   An array of user accounts as returned by User::loadMultiple().
893
 * @param string $view_mode
894
 *   (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
895
 * @param string|null $langcode
896 897
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
898
 *
899
 * @return array
900
 *   An array in the format expected by drupal_render().
901
 */
902
function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
903
  return entity_view_multiple($accounts, $view_mode, $langcode);
904 905
}

906
/**
907
 * Implements hook_mail().
908 909
 */
function user_mail($key, &$message, $params) {
910
  $token_service = \Drupal::token();
911
  $language_manager = \Drupal::languageManager();
912
  $langcode = $message['langcode'];
913
  $variables = array('user' => $params['account']);
914

915
  $language = \Drupal::languageManager()->getLanguage($params['account']->getPreferredLangcode());
916 917
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);
918
  $mail_config = \Drupal::config('user.mail');
919

920 921
  $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));
922
  $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);
923

924 925
  $language_manager->setConfigOverrideLanguage($original_language);

926 927 928 929 930
}

/**
 * Token callback to add unsafe tokens for user mails.
 *
931 932 933
 * 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().
934
 *
935
 * @param array $replacements
936 937
 *   An associative array variable containing mappings from token names to
 *   values (for use with strtr()).
938
 * @param array $data
939 940 941
 *   An associative array of token replacement values. If the 'user' element
 *   exists, it must contain a user account object with the following
 *   properties:
942
 *   - login: The UNIX timestamp of the user's last login.
943
 *   - pass: The hashed account login password.
944 945 946
 * @param array $options
 *   A keyed array of settings and flags to control the token replacement
 *   process. See \Drupal\Core\Utility\Token::replace().
947 948 949
 */
function user_mail_tokens(&$replacements, $data, $options) {
  if (isset($data['user'])) {
950 951
    $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
    $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
952 953 954
  }
}

955 956
/*** Administrative features ***********************************************/

957
/**
958
 * Retrieves the names of roles matching specified conditions.
959
 *
960 961 962 963 964 965 966
 * @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.
967
 *
968
 * @return array
969 970
 *   An associative array with the role id as the key and the role name as
 *   value.
971
 */
972
function user_role_names($membersonly = FALSE, $permission = NULL) {
973
  return array_map(function ($item) {
974 975 976 977
    return $item->label();
  }, user_roles($membersonly, $permission));
}

978
/**
979
 * Implements hook_ENTITY_TYPE_insert() for user_role entities.
980 981
 */
function user_user_role_insert(RoleInterface $role) {
982
  // Ignore the authenticated and anonymous roles or the role is being synced.
983
  if (in_array($role->id(), array(RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID)) || $role->isSyncing()) {
984 985 986
    return;
  }

987 988
  $add_id = 'user_add_role_action.' . $role->id();
  if (!entity_load('action', $add_id)) {
989
    $action = Action::create(array(
990 991 992 993 994 995 996 997
      'id' => $add_id,
      'type' => 'user',
      'label' => t('Add the @label role to the selected users', array('@label' => $role->label())),
      'configuration' => array(
        'rid' => $role->id(),
      ),
      'plugin' => 'user_add_role_action',
    ));
998
    $action->trustData()->save();
999 1000 1001
  }
  $remove_id = 'user_remove_role_action.' . $role->id();
  if (!entity_load('action', $remove_id)) {
1002
    $action = Action::create(array(
1003 1004 1005 1006 1007 1008 1009 1010
      'id' => $remove_id,
      'type' => 'user',
      'label' => t('Remove the @label role from the selected users', array('@label' => $role->label())),
      'configuration' => array(
        'rid' => $role->id(),
      ),
      'plugin' => 'user_remove_role_action',
    ));
1011
    $action->trustData()->save();
1012
  }
1013 1014 1015
}

/**
1016
 * Implements hook_ENTITY_TYPE_delete() for user_role entities.
1017 1018
 */
function user_user_role_delete(RoleInterface $role) {
1019 1020 1021 1022
  // Delete role references for all users.
  $user_storage = \Drupal::entityManager()->getStorage('user');
  $user_storage->deleteRoleReferences(array($role->id()));

1023
  // Ignore the authenticated and anonymous roles or the role is being synced.
1024
  if (in_array($role->id(), array(RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID)) || $role->isSyncing()) {
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    return;
  }

  $actions = entity_load_multiple('action', array(
    'user_add_role_action.' . $role->id(),
    'user_remove_role_action.' . $role->id(),
  ));
  foreach ($actions as $action) {
    $action->delete();
  }
}

1037 1038 1039
/**
 * Retrieve an array of roles matching specified conditions.
 *
1040 1041 1042 1043 1044 1045 1046
 * @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.
1047
 *
1048
 * @return \Drupal\user\RoleInterface[]
1049 1050 1051
 *   An associative array with the role id as the key and the role object as
 *   value.
 */
1052
function user_roles($membersonly = FALSE, $permission = NULL) {
1053
  $roles = Role::loadMultiple();
1054
  if ($membersonly) {
1055
    unset($roles[RoleInterface::ANONYMOUS_ID]);
1056 1057 1058
  }

  if (!empty($permission)) {
1059 1060 1061
    $roles = array_filter($roles, function ($role) use ($permission) {
      return $role->hasPermission($permission);
    });
1062
  }
1063

1064
  return $roles;
1065 1066
}

1067
/**
1068 1069
 * Fetches a user role by role ID.
 *
1070
 * @param string $rid
1071
 *   A string representing the role ID.
1072
 *
1073
 * @return \Drupal\user\RoleInterface|null
1074
 *   A fully-loaded role object if a role with the given ID exists, or NULL
1075
 *   otherwise.
1076 1077 1078
 *
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal\user\Entity\Role::load().
1079 1080
 */
function user_role_load($rid) {
1081
  return Role::load($rid);
1082 1083 1084
}

/**
1085
 * Change permissions for a user role.
1086
 *
1087 1088
 * This function may be used to grant and revoke multiple permissions at once.
 * For example, when a form exposes checkboxes to configure permissions for a
1089 1090
 * role, the form submit handler may directly pass the submitted values for the
 * checkboxes form element to this function.
1091
 *
1092
 * @param mixed $rid
1093
 *   The ID of a user role to alter.
1094 1095 1096 1097 1098 1099
 * @param array $permissions
 *   (optional) An associative array, where the key holds the permission name
 *   and the value determines whether to grant or revoke that permission. Any
 *   value that evaluates to TRUE will cause the permission to be granted.
 *   Any value that evaluates to FALSE will cause the permission to be
 *   revoked.
1100 1101
 *   @code
 *     array(
1102 1103 1104 1105 1106
 *       'administer nodes' => 0,                // Revoke 'administer nodes'
 *       'administer blocks' => FALSE,           // Revoke 'administer blocks'
 *       'access user profiles' => 1,            // Grant 'access user profiles'
 *       'access content' => TRUE,               // Grant 'access content'
 *       'access comments' => 'access comments', // Grant 'access comments'
1107 1108 1109 1110 1111 1112
 *     )
 *   @endcode
 *   Existing permissions are not changed, unless specified in $permissions.
 *
 * @see user_role_grant_permissions()
 * @see user_role_revoke_permissions()
1113
 */
1114 1115 1116 1117 1118
function user_role_change_permissions($rid, array $permissions = array()) {
  // Grant new permissions for the role.
  $grant = array_filter($permissions);
  if (!empty($grant)) {
    user_role_grant_permissions($rid, array_keys($grant));
1119
  }
1120 1121 1122 1123 1124 1125
  // Revoke permissions for the role.
  $revoke = array_diff_assoc($permissions, $grant);
  if (!empty($revoke)) {
    user_role_revoke_permissions($rid, array_keys($revoke));
  }
}
1126