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

3
use Drupal\Component\Utility\Crypt;
4
use Drupal\Component\Utility\SafeMarkup;
5
use Drupal\Component\Utility\Unicode;
6
use Drupal\Core\Asset\AttachedAssetsInterface;
7
use Drupal\Core\Cache\Cache;
8 9
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Field\BaseFieldDefinition;
10
use Drupal\Core\Form\FormStateInterface;
11
use Drupal\Core\Render\Element;
12
use Drupal\Core\Routing\RouteMatchInterface;
13
use Drupal\Core\Session\AccountInterface;
14
use Drupal\Core\Session\AnonymousUserSession;
15
use Drupal\Core\Site\Settings;
16
use Drupal\Core\Url;
17
use Drupal\user\Entity\Role;
18
use Drupal\user\Entity\User;
19
use Drupal\user\RoleInterface;
20
use Drupal\user\UserInterface;
Crell's avatar
Crell committed
21

22 23 24 25 26
/**
 * @file
 * Enables the user registration and login system.
 */

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 66 67
      $output .= '<dt>' . t('Setting permissions') . '</dt>';
      $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>';
      $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
 * Implements hook_preprocess_HOOK() for block templates.
382 383
 */
function user_preprocess_block(&$variables) {
384
  if ($variables['configuration']['provider'] == 'user') {
385
    switch ($variables['elements']['#plugin_id']) {
386
      case 'user_login_block':
387
        $variables['attributes']['role'] = 'form';
388 389 390 391 392
        break;
    }
  }
}

393 394 395
/**
 * Format a username.
 *
396
 * @param \Drupal\Core\Session\AccountInterface $account
397 398
 *   The account object for the user whose name is to be formatted.
 *
399
 * @return string
400
 *   An unsanitized string with the username to display. The code receiving
401
 *   this result must ensure that \Drupal\Component\Utility\SafeMarkup::checkPlain()
402
 *   is called on it before it is printed to the page.
403
 *
404 405
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal\Core\Session\Interface::getUsername().
406
 */
407 408
function user_format_name(AccountInterface $account) {
  return $account->getUsername();
409 410
}

411 412 413 414 415 416 417
/**
 * Implements hook_template_preprocess_default_variables_alter().
 *
 * @see user_user_login()
 * @see user_user_logout()
 */
function user_template_preprocess_default_variables_alter(&$variables) {
418
  $user = \Drupal::currentUser();
419

420 421 422 423 424 425
  // If this function is called from the installer after Drupal has been
  // installed then $user will not be set.
  if (!is_object($user)) {
    return;
  }

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

430
  $variables['is_admin'] = $user->hasPermission('access administration pages');
431
  $variables['logged_in'] = $user->isAuthenticated();
432 433
}

434
/**
435 436 437 438 439 440
 * Prepares variables for username templates.
 *
 * Default template: username.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
441
 *   - account: The user account (\Drupal\Core\Session\AccountInterface).
442
 *
443
 * Modules that make any changes to variables like 'name' or 'extra' must ensure
444
 * that the final string is safe to include directly in the output by using
445
 * \Drupal\Component\Utility\SafeMarkup::checkPlain() or
446
 * \Drupal\Component\Utility\Xss::filter().
447 448
 */
function template_preprocess_username(&$variables) {
449
  $account = $variables['account'] ?: new AnonymousUserSession();
450 451

  $variables['extra'] = '';
452 453 454 455 456
  $variables['uid'] = $account->id();
  if (empty($variables['uid'])) {
    if (theme_get_setting('features.comment_user_verification')) {
      $variables['extra'] = ' (' . t('not verified') . ')';
    }
457 458 459 460 461 462 463
  }

  // 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.
464
  $name = $variables['name_raw'] = $account->getUsername();
465
  if (Unicode::strlen($name) > 20) {
466
    $name = Unicode::truncate($name, 15, FALSE, TRUE);
467 468 469 470
    $variables['truncated'] = TRUE;
  }
  else {
    $variables['truncated'] = FALSE;
471
  }
472
  $variables['name'] = SafeMarkup::checkPlain($name);
473
  $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
474

475
  $external = FALSE;
476 477 478
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
479
    $variables['attributes']['title'] = t('View user profile.');
480 481 482 483 484 485
    $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.
486
    $variables['attributes']['rel'] = 'nofollow';
487 488
    $variables['link_path'] = $account->homepage;
    $variables['homepage'] = $account->homepage;
489
    $external = TRUE;
490
  }
491
  // We have a link path, so we should generate a URL.
492
  if (isset($variables['link_path'])) {
493 494 495 496 497 498 499 500 501
    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();
    }
502 503 504
  }
}

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

529
  // Regenerate the session ID to prevent against session fixation attacks.
530 531 532
  // 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.
533
  \Drupal::service('session')->migrate();
534
  \Drupal::service('session')->set('uid', $account->id());
535
  \Drupal::moduleHandler()->invokeAll('user_login', array($account));
536 537
}

538 539 540
/**
 * Implements hook_user_login().
 */
541
function user_user_login($account) {
542 543 544 545 546 547 548 549 550 551 552 553 554 555
  // 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');
}

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

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

614 615 616 617 618 619
/**
 * 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
620 621 622
 * 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.
623 624
 * For a usage example, see user_cancel_url() and
 * \Drupal\user\Controller\UserController::confirmCancel().
625
 *
626 627
 * @param \Drupal\user\UserInterface $account
 *   An object containing the user account.
628 629
 * @param int $timestamp
 *   A UNIX timestamp, typically REQUEST_TIME.
630
 *
631
 * @return string
632 633
 *   A string that is safe for use in URLs and SQL statements.
 */
634 635 636 637 638 639
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());
640 641
}

642
/**
643 644 645 646 647 648
 * 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.
 *
649
 * @param array $edit
650
 *   An array of submitted form values.
651
 * @param int $uid
652
 *   The user ID of the user account to cancel.
653
 * @param string $method
654
 *   The account cancellation method to use.
655
 *
656
 * @see _user_cancel()
657
 */
658
function user_cancel($edit, $uid, $method) {
659
  $account = User::load($uid);
660 661 662

  if (!$account) {
    drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error');
663
    \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', array('%id' => $uid));
664 665 666 667 668 669 670 671 672 673
    return;
  }

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

674
  // When the 'user_cancel_delete' method is used, user_delete() is called,
675 676 677
  // 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.
678 679
  if ($method != 'user_cancel_delete') {
    // Allow modules to add further sets to this batch.
680
    \Drupal::moduleHandler()->invokeAll('user_cancel', array($edit, $account, $method));
681
  }
682 683 684 685 686 687 688 689

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

  // After cancelling account, ensure that user is logged out.
692
  if ($account->id() == \Drupal::currentUser()->id()) {
693 694 695 696 697
    // 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';
  }

698 699 700 701 702 703 704
  batch_set($batch);

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

/**
705 706 707
 * Implements callback_batch_operation().
 *
 * Last step for cancelling a user account.
708 709 710
 *
 * Since batch and session API require a valid user account, the actual
 * cancellation of a user account needs to happen last.
711 712 713 714 715 716
 * @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.
717 718 719 720
 *
 * @see user_cancel()
 */
function _user_cancel($edit, $account, $method) {
721
  $logger = \Drupal::logger('user');
722 723 724 725 726 727 728 729 730

  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);
      }
731
      $account->block();
732
      $account->save();
733
      drupal_set_message(t('%name has been disabled.', array('%name' => $account->getUsername())));
734
      $logger->notice('Blocked user: %name %email.', array('%name' => $account->getUsername(), '%email' => '<' . $account->getEmail() . '>'));
735 736 737 738 739 740 741 742
      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);
      }
743
      $account->delete();
744
      drupal_set_message(t('%name has been deleted.', array('%name' => $account->getUsername())));
745
      $logger->notice('Deleted user: %name %email.', array('%name' => $account->getUsername(), '%email' => '<' . $account->getEmail() . '>'));
746 747 748
      break;
  }

749 750 751 752
  // 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().
753 754
  if ($account->id() == \Drupal::currentUser()->id()) {
    \Drupal::currentUser()->setAccount(new AnonymousUserSession());
755
  }
756 757
}

758
/**
759 760
 * Implements callback_batch_finished().
 *
761 762 763 764 765 766 767
 * 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.
768
  \Drupal::service('session')->migrate();
769 770
}

771 772 773 774 775 776 777 778 779 780 781 782
/**
 * 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() {
783
  $user_settings = \Drupal::config('user.settings');
784 785 786 787
  $anonymous_name = $user_settings->get('anonymous');
  $methods = array(
    'user_cancel_block' => array(
      'title' => t('Disable the account and keep its content.'),
788
      '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.'),
789 790 791 792 793 794 795 796 797 798 799 800
    ),
    '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.'),
801
      'access' => \Drupal::currentUser()->hasPermission('administer users'),
802 803 804
    ),
  );
  // Allow modules to customize account cancellation methods.
805
  \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826

  // 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;
}

827 828 829
/**
 * Delete a user.
 *
830
 * @param int $uid
831 832 833 834 835 836 837 838 839
 *   A user ID.
 */
function user_delete($uid) {
  user_delete_multiple(array($uid));
}

/**
 * Delete multiple user accounts.
 *
840
 * @param int[] $uids
841
 *   An array of user IDs.
842
 *
843 844
 * @see hook_ENTITY_TYPE_predelete()
 * @see hook_ENTITY_TYPE_delete()
845 846
 */
function user_delete_multiple(array $uids) {
847
  entity_delete_multiple('user', $uids);
848 849
}

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

/**
879
 * Constructs a drupal_render() style array from an array of loaded users.
880
 *
881
 * @param \Drupal\user\UserInterface[] $account
882
 *   An array of user accounts as returned by User::loadMultiple().
883
 * @param string $view_mode
884
 *   (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
885
 * @param string|null $langcode
886 887
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
888
 *
889
 * @return array
890
 *   An array in the format expected by drupal_render().
891
 */
892
function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
893
  return entity_view_multiple($accounts, $view_mode, $langcode);
894 895
}

896
/**
897
 * Implements hook_mail().
898 899
 */
function user_mail($key, &$message, $params) {
900
  $token_service = \Drupal::token();
901
  $language_manager = \Drupal::languageManager();
902
  $langcode = $message['langcode'];
903
  $variables = array('user' => $params['account']);
904

905
  $language = \Drupal::languageManager()->getLanguage($params['account']->getPreferredLangcode());
906 907
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);
908
  $mail_config = \Drupal::config('user.mail');
909 910

   // We do not sanitize the token replacement, since the output of this
911
   // replacement is intended for an email message, not a web browser.
912
  $token_options = array('langcode' => $langcode, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE);
913 914
  $message['subject'] .= $token_service->replace($mail_config->get($key . '.subject'), $variables, $token_options);
  $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);
915

916 917
  $language_manager->setConfigOverrideLanguage($original_language);

918 919 920 921 922
}

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

947 948
/*** Administrative features ***********************************************/

949
/**
950
 * Retrieves the names of roles matching specified conditions.
951
 *
952 953 954 955 956 957 958
 * @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.
959
 *
960
 * @return array
961 962
 *   An associative array with the role id as the key and the role name as
 *   value.
963
 */
964
function user_role_names($membersonly = FALSE, $permission = NULL) {
965
  return array_map(function ($item) {
966 967 968 969
    return $item->label();
  }, user_roles($membersonly, $permission));
}

970
/**
971
 * Implements hook_ENTITY_TYPE_insert() for user_role entities.
972 973
 */
function user_user_role_insert(RoleInterface $role) {
974
  // Ignore the authenticated and anonymous roles or the role is being synced.
975
  if (in_array($role->id(), array(RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID)) || $role->isSyncing()) {
976 977 978
    return;
  }

979 980 981 982 983 984 985 986 987 988 989
  $add_id = 'user_add_role_action.' . $role->id();
  if (!entity_load('action', $add_id)) {
    $action = entity_create('action', array(
      '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',
    ));
990
    $action->trustData()->save();
991 992 993 994 995 996 997 998 999 1000 1001 1002
  }
  $remove_id = 'user_remove_role_action.' . $role->id();
  if (!entity_load('action', $remove_id)) {
    $action = entity_create('action', array(
      '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',
    ));
1003
    $action->trustData()->save();
1004
  }
1005 1006 1007
}

/**
1008
 * Implements hook_ENTITY_TYPE_delete() for user_role entities.
1009 1010
 */
function user_user_role_delete(RoleInterface $role) {
1011 1012 1013 1014
  // Delete role references for all users.
  $user_storage = \Drupal::entityManager()->getStorage('user');
  $user_storage->deleteRoleReferences(array($role->id()));

1015
  // Ignore the authenticated and anonymous roles or the role is being synced.
1016
  if (in_array($role->id(), array(RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID)) || $role->isSyncing()) {
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    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();
  }
}

1029 1030 1031
/**
 * Retrieve an array of roles matching specified conditions.
 *
1032 1033 1034 1035 1036 1037 1038
 * @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.
1039
 *
1040
 * @return \Drupal\user\RoleInterface[]
1041 1042 1043
 *   An associative array with the role id as the key and the role object as
 *   value.
 */
1044
function user_roles($membersonly = FALSE, $permission = NULL) {
1045 1046 1047 1048 1049
  $user_roles = &drupal_static(__FUNCTION__);

  // Do not cache roles for specific permissions. This data is not requested
  // frequently enough to justify the additional memory use.
  if (empty($permission)) {
1050
    $cid = $membersonly ? RoleInterface::AUTHENTICATED_ID : RoleInterface::ANONYMOUS_ID;
1051 1052 1053 1054 1055
    if (isset($user_roles[$cid])) {
      return $user_roles[$cid];
    }
  }

1056
  $roles = Role::loadMultiple();
1057
  if ($membersonly) {
1058
    unset($roles[RoleInterface::ANONYMOUS_ID]);
1059 1060 1061
  }

  if (!empty($permission)) {
1062 1063 1064
    $roles = array_filter($roles, function ($role) use ($permission) {
      return $role->hasPermission($permission);
    });
1065
  }
1066

1067 1068 1069 1070
  if (empty($permission)) {
    $user_roles[$cid] = $roles;
  }

1071
  return $roles;
1072 1073
}

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

/**
1092
 * Change permissions for a user role.
1093
 *
1094 1095
 * 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
1096 1097
 * role, the form submit handler may directly pass the submitted values for the
 * checkboxes form element to this function.
1098
 *
1099
 * @param mixed $rid
1100
 *   The ID of a user role to alter.
1101 1102 1103 1104 1105 1106
 * @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.
1107 1108
 *   @code
 *     array(
1109 1110 1111 1112 1113
 *       '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'
1114 1115 1116 1117 1118 1119
 *     )
 *   @endcode
 *   Existing permissions are not changed, unless specified in $permissions.
 *
 * @see user_role_grant_permissions()
 * @see user_role_revoke_permissions()
1120
 */
1121 1122 1123 1124 1125
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));