annotate core/modules/user/user.module @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 1fec387a4317
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /**
Chris@0 4 * @file
Chris@0 5 * Enables the user registration and login system.
Chris@0 6 */
Chris@0 7
Chris@0 8 use Drupal\Component\Utility\Crypt;
Chris@0 9 use Drupal\Component\Render\PlainTextOutput;
Chris@0 10 use Drupal\Component\Utility\Unicode;
Chris@0 11 use Drupal\Core\Asset\AttachedAssetsInterface;
Chris@0 12 use Drupal\Core\Cache\Cache;
Chris@0 13 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
Chris@0 14 use Drupal\Core\Field\BaseFieldDefinition;
Chris@0 15 use Drupal\Core\Render\Element;
Chris@0 16 use Drupal\Core\Routing\RouteMatchInterface;
Chris@0 17 use Drupal\Core\Session\AccountInterface;
Chris@0 18 use Drupal\Core\Session\AnonymousUserSession;
Chris@0 19 use Drupal\Core\Site\Settings;
Chris@0 20 use Drupal\Core\Url;
Chris@0 21 use Drupal\system\Entity\Action;
Chris@0 22 use Drupal\user\Entity\Role;
Chris@0 23 use Drupal\user\Entity\User;
Chris@0 24 use Drupal\user\RoleInterface;
Chris@0 25 use Drupal\user\UserInterface;
Chris@0 26
Chris@0 27 /**
Chris@0 28 * Maximum length of username text field.
Chris@0 29 *
Chris@0 30 * Keep this under 191 characters so we can use a unique constraint in MySQL.
Chris@0 31 *
Chris@0 32 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
Chris@0 33 * Use \Drupal\user\UserInterface::USERNAME_MAX_LENGTH instead.
Chris@0 34 *
Chris@0 35 * @see https://www.drupal.org/node/2831620
Chris@0 36 */
Chris@0 37 const USERNAME_MAX_LENGTH = 60;
Chris@0 38
Chris@0 39 /**
Chris@0 40 * Only administrators can create user accounts.
Chris@0 41 *
Chris@0 42 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
Chris@0 43 * Use \Drupal\user\UserInterface::REGISTER_ADMINISTRATORS_ONLY instead.
Chris@0 44 *
Chris@0 45 * @see https://www.drupal.org/node/2831620
Chris@0 46 */
Chris@0 47 const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
Chris@0 48
Chris@0 49 /**
Chris@0 50 * Visitors can create their own accounts.
Chris@0 51 *
Chris@0 52 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
Chris@0 53 * Use \Drupal\user\UserInterface::REGISTER_VISITORS instead.
Chris@0 54 *
Chris@0 55 * @see https://www.drupal.org/node/2831620
Chris@0 56 */
Chris@0 57 const USER_REGISTER_VISITORS = 'visitors';
Chris@0 58
Chris@0 59 /**
Chris@0 60 * Visitors can create accounts, but they don't become active without
Chris@0 61 * administrative approval.
Chris@0 62 *
Chris@0 63 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
Chris@0 64 * Use \Drupal\user\UserInterface::REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL
Chris@0 65 * instead.
Chris@0 66 *
Chris@0 67 * @see https://www.drupal.org/node/2831620
Chris@0 68 */
Chris@0 69 const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
Chris@0 70
Chris@0 71 /**
Chris@0 72 * Implements hook_help().
Chris@0 73 */
Chris@0 74 function user_help($route_name, RouteMatchInterface $route_match) {
Chris@0 75 switch ($route_name) {
Chris@0 76 case 'help.page.user':
Chris@0 77 $output = '';
Chris@0 78 $output .= '<h3>' . t('About') . '</h3>';
Chris@0 79 $output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles and permissions. For more information, see the <a href=":user_docs">online documentation for the User module</a>.', [':user_docs' => 'https://www.drupal.org/documentation/modules/user']) . '</p>';
Chris@0 80 $output .= '<h3>' . t('Uses') . '</h3>';
Chris@0 81 $output .= '<dl>';
Chris@0 82 $output .= '<dt>' . t('Creating and managing users') . '</dt>';
Chris@0 83 $output .= '<dd>' . t('Through the <a href=":people">People administration page</a> you can add and cancel user accounts and assign users to roles. By editing one particular user you can change their username, email address, password, and information in other fields.', [':people' => \Drupal::url('entity.user.collection')]) . '</dd>';
Chris@0 84 $output .= '<dt>' . t('Configuring user roles') . '</dt>';
Chris@0 85 $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. Typically there are two pre-defined roles: <em>Anonymous user</em> (users that are not logged in), and <em>Authenticated user</em> (users that are registered and logged in). Depending on how your site was set up, an <em>Administrator</em> role may also be available: users with this role will automatically be assigned any new permissions whenever a module is enabled. You can create additional roles on the <a href=":roles">Roles administration page</a>.', [':roles' => \Drupal::url('entity.user_role.collection')]) . '</dd>';
Chris@0 86 $output .= '<dt>' . t('Setting permissions') . '</dt>';
Chris@0 87 $output .= '<dd>' . t('After creating roles, you can set permissions for each role on the <a href=":permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing content, editing or creating a particular type of content, administering settings for a particular module, or using a particular function of the site (such as search).', [':permissions_user' => \Drupal::url('user.admin_permissions')]) . '</dd>';
Chris@0 88 $output .= '<dt>' . t('Managing account settings') . '</dt>';
Chris@0 89 $output .= '<dd>' . t('The <a href=":accounts">Account settings page</a> allows you to manage settings for the displayed name of the Anonymous user role, personal contact forms, user registration settings, and account cancellation settings. On this page you can also manage settings for account personalization, and adapt the text for the email messages that users receive when they register or request a password recovery. You may also set which role is automatically assigned new permissions whenever a module is enabled (the Administrator role).', [':accounts' => \Drupal::url('entity.user.admin_form')]) . '</dd>';
Chris@0 90 $output .= '<dt>' . t('Managing user account fields') . '</dt>';
Chris@0 91 $output .= '<dd>' . t('Because User accounts are an entity type, you can extend them by adding fields through the Manage fields tab on the <a href=":accounts">Account settings page</a>. By adding fields for e.g., a picture, a biography, or address, you can a create a custom profile for the users of the website. For background information on entities and fields, see the <a href=":field_help">Field module help page</a>.', [':field_help' => (\Drupal::moduleHandler()->moduleExists('field')) ? \Drupal::url('help.page', ['name' => 'field']) : '#', ':accounts' => \Drupal::url('entity.user.admin_form')]) . '</dd>';
Chris@0 92 $output .= '</dl>';
Chris@0 93 return $output;
Chris@0 94
Chris@0 95 case 'user.admin_create':
Chris@0 96 return '<p>' . t("This web page allows administrators to register new users. Users' email addresses and usernames must be unique.") . '</p>';
Chris@0 97
Chris@0 98 case 'user.admin_permissions':
Chris@0 99 return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href=":role">Roles</a> page to create a role.) Any permissions granted to the Authenticated user role will be given to any user who is logged in to your site. From the <a href=":settings">Account settings</a> page, you can make any role into an Administrator role for the site, meaning that role will be granted all new permissions automatically. You should be careful to ensure that only trusted users are given this access and level of control of your site.', [':role' => \Drupal::url('entity.user_role.collection'), ':settings' => \Drupal::url('entity.user.admin_form')]) . '</p>';
Chris@0 100
Chris@0 101 case 'entity.user_role.collection':
Chris@0 102 return '<p>' . t('A role defines a group of users that have certain privileges. These privileges are defined on the <a href=":permissions">Permissions page</a>. Here, you can define the names and the display sort order of the roles on your site. It is recommended to order roles from least permissive (for example, Anonymous user) to most permissive (for example, Administrator user). Users who are not logged in have the Anonymous user role. Users who are logged in have the Authenticated user role, plus any other roles granted to their user account.', [':permissions' => \Drupal::url('user.admin_permissions')]) . '</p>';
Chris@0 103
Chris@0 104 case 'entity.user.field_ui_fields':
Chris@0 105 return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';
Chris@0 106
Chris@0 107 case 'entity.entity_form_display.user.default':
Chris@0 108 return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';
Chris@0 109
Chris@0 110 case 'entity.entity_view_display.user.default':
Chris@0 111 return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
Chris@0 112 }
Chris@0 113 }
Chris@0 114
Chris@0 115 /**
Chris@0 116 * Implements hook_theme().
Chris@0 117 */
Chris@0 118 function user_theme() {
Chris@0 119 return [
Chris@0 120 'user' => [
Chris@0 121 'render element' => 'elements',
Chris@0 122 ],
Chris@0 123 'username' => [
Chris@0 124 'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
Chris@0 125 ],
Chris@0 126 ];
Chris@0 127 }
Chris@0 128
Chris@0 129 /**
Chris@0 130 * Implements hook_js_settings_alter().
Chris@0 131 */
Chris@0 132 function user_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
Chris@0 133 // Provide the user ID in drupalSettings to allow JavaScript code to customize
Chris@0 134 // the experience for the end user, rather than the server side, which would
Chris@0 135 // break the render cache.
Chris@0 136 // Similarly, provide a permissions hash, so that permission-dependent data
Chris@0 137 // can be reliably cached on the client side.
Chris@0 138 $user = \Drupal::currentUser();
Chris@0 139 $settings['user']['uid'] = $user->id();
Chris@0 140 $settings['user']['permissionsHash'] = \Drupal::service('user_permissions_hash_generator')->generate($user);
Chris@0 141 }
Chris@0 142
Chris@0 143 /**
Chris@0 144 * Returns whether this site supports the default user picture feature.
Chris@0 145 *
Chris@0 146 * This approach preserves compatibility with node/comment templates. Alternate
Chris@0 147 * user picture implementations (e.g., Gravatar) should provide their own
Chris@0 148 * add/edit/delete forms and populate the 'picture' variable during the
Chris@0 149 * preprocess stage.
Chris@0 150 */
Chris@0 151 function user_picture_enabled() {
Chris@0 152 $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
Chris@0 153 return isset($field_definitions['user_picture']);
Chris@0 154 }
Chris@0 155
Chris@0 156 /**
Chris@0 157 * Implements hook_entity_extra_field_info().
Chris@0 158 */
Chris@0 159 function user_entity_extra_field_info() {
Chris@0 160 $fields['user']['user']['form']['account'] = [
Chris@0 161 'label' => t('User name and password'),
Chris@0 162 'description' => t('User module account form elements.'),
Chris@0 163 'weight' => -10,
Chris@0 164 ];
Chris@0 165 $fields['user']['user']['form']['language'] = [
Chris@0 166 'label' => t('Language settings'),
Chris@0 167 'description' => t('User module form element.'),
Chris@0 168 'weight' => 0,
Chris@0 169 ];
Chris@0 170 if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
Chris@0 171 $fields['user']['user']['form']['timezone'] = [
Chris@0 172 'label' => t('Timezone'),
Chris@0 173 'description' => t('System module form element.'),
Chris@0 174 'weight' => 6,
Chris@0 175 ];
Chris@0 176 }
Chris@0 177
Chris@0 178 $fields['user']['user']['display']['member_for'] = [
Chris@0 179 'label' => t('Member for'),
Chris@0 180 'description' => t("User module 'member for' view element."),
Chris@0 181 'weight' => 5,
Chris@0 182 ];
Chris@0 183
Chris@0 184 return $fields;
Chris@0 185 }
Chris@0 186
Chris@0 187 /**
Chris@0 188 * Loads multiple users based on certain conditions.
Chris@0 189 *
Chris@0 190 * This function should be used whenever you need to load more than one user
Chris@0 191 * from the database. Users are loaded into memory and will not require
Chris@0 192 * database access if loaded again during the same page request.
Chris@0 193 *
Chris@0 194 * @param array $uids
Chris@0 195 * (optional) An array of entity IDs. If omitted, all entities are loaded.
Chris@0 196 * @param bool $reset
Chris@0 197 * A boolean indicating that the internal cache should be reset. Use this if
Chris@0 198 * loading a user object which has been altered during the page request.
Chris@0 199 *
Chris@0 200 * @return array
Chris@0 201 * An array of user objects, indexed by uid.
Chris@0 202 *
Chris@0 203 * @see entity_load_multiple()
Chris@0 204 * @see \Drupal\user\Entity\User::load()
Chris@0 205 * @see user_load_by_mail()
Chris@0 206 * @see user_load_by_name()
Chris@0 207 * @see \Drupal\Core\Entity\Query\QueryInterface
Chris@0 208 *
Chris@0 209 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
Chris@0 210 * Use \Drupal\user\Entity\User::loadMultiple().
Chris@0 211 */
Chris@0 212 function user_load_multiple(array $uids = NULL, $reset = FALSE) {
Chris@0 213 if ($reset) {
Chris@0 214 \Drupal::entityManager()->getStorage('user')->resetCache($uids);
Chris@0 215 }
Chris@0 216 return User::loadMultiple($uids);
Chris@0 217 }
Chris@0 218
Chris@0 219 /**
Chris@0 220 * Loads a user object.
Chris@0 221 *
Chris@0 222 * @param int $uid
Chris@0 223 * Integer specifying the user ID to load.
Chris@0 224 * @param bool $reset
Chris@0 225 * TRUE to reset the internal cache and load from the database; FALSE
Chris@0 226 * (default) to load from the internal cache, if set.
Chris@0 227 *
Chris@0 228 * @return \Drupal\user\UserInterface
Chris@0 229 * A fully-loaded user object upon successful user load, or NULL if the user
Chris@0 230 * cannot be loaded.
Chris@0 231 *
Chris@0 232 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
Chris@0 233 * Use \Drupal\user\Entity\User::load().
Chris@0 234 *
Chris@0 235 * @see \Drupal\user\Entity\User::loadMultiple()
Chris@0 236 */
Chris@0 237 function user_load($uid, $reset = FALSE) {
Chris@0 238 if ($reset) {
Chris@0 239 \Drupal::entityManager()->getStorage('user')->resetCache([$uid]);
Chris@0 240 }
Chris@0 241 return User::load($uid);
Chris@0 242 }
Chris@0 243
Chris@0 244 /**
Chris@0 245 * Fetches a user object by email address.
Chris@0 246 *
Chris@0 247 * @param string $mail
Chris@0 248 * String with the account's email address.
Chris@0 249 * @return object|bool
Chris@0 250 * A fully-loaded $user object upon successful user load or FALSE if user
Chris@0 251 * cannot be loaded.
Chris@0 252 *
Chris@0 253 * @see \Drupal\user\Entity\User::loadMultiple()
Chris@0 254 */
Chris@0 255 function user_load_by_mail($mail) {
Chris@0 256 $users = \Drupal::entityTypeManager()->getStorage('user')
Chris@0 257 ->loadByProperties(['mail' => $mail]);
Chris@0 258 return $users ? reset($users) : FALSE;
Chris@0 259 }
Chris@0 260
Chris@0 261 /**
Chris@0 262 * Fetches a user object by account name.
Chris@0 263 *
Chris@0 264 * @param string $name
Chris@0 265 * String with the account's user name.
Chris@0 266 * @return object|bool
Chris@0 267 * A fully-loaded $user object upon successful user load or FALSE if user
Chris@0 268 * cannot be loaded.
Chris@0 269 *
Chris@0 270 * @see \Drupal\user\Entity\User::loadMultiple()
Chris@0 271 */
Chris@0 272 function user_load_by_name($name) {
Chris@0 273 $users = \Drupal::entityTypeManager()->getStorage('user')
Chris@0 274 ->loadByProperties(['name' => $name]);
Chris@0 275 return $users ? reset($users) : FALSE;
Chris@0 276 }
Chris@0 277
Chris@0 278 /**
Chris@0 279 * Verify the syntax of the given name.
Chris@0 280 *
Chris@0 281 * @param string $name
Chris@0 282 * The user name to validate.
Chris@0 283 *
Chris@0 284 * @return string|null
Chris@0 285 * A translated violation message if the name is invalid or NULL if the name
Chris@0 286 * is valid.
Chris@0 287 */
Chris@0 288 function user_validate_name($name) {
Chris@0 289 $definition = BaseFieldDefinition::create('string')
Chris@0 290 ->addConstraint('UserName', []);
Chris@0 291 $data = \Drupal::typedDataManager()->create($definition);
Chris@0 292 $data->setValue($name);
Chris@0 293 $violations = $data->validate();
Chris@0 294 if (count($violations) > 0) {
Chris@0 295 return $violations[0]->getMessage();
Chris@0 296 }
Chris@0 297 }
Chris@0 298
Chris@0 299 /**
Chris@0 300 * Generate a random alphanumeric password.
Chris@0 301 */
Chris@0 302 function user_password($length = 10) {
Chris@0 303 // This variable contains the list of allowable characters for the
Chris@0 304 // password. Note that the number 0 and the letter 'O' have been
Chris@0 305 // removed to avoid confusion between the two. The same is true
Chris@0 306 // of 'I', 1, and 'l'.
Chris@0 307 $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
Chris@0 308
Chris@0 309 // Zero-based count of characters in the allowable list:
Chris@0 310 $len = strlen($allowable_characters) - 1;
Chris@0 311
Chris@0 312 // Declare the password as a blank string.
Chris@0 313 $pass = '';
Chris@0 314
Chris@0 315 // Loop the number of times specified by $length.
Chris@0 316 for ($i = 0; $i < $length; $i++) {
Chris@0 317 do {
Chris@0 318 // Find a secure random number within the range needed.
Chris@0 319 $index = ord(Crypt::randomBytes(1));
Chris@0 320 } while ($index > $len);
Chris@0 321
Chris@0 322 // Each iteration, pick a random character from the
Chris@0 323 // allowable string and append it to the password:
Chris@0 324 $pass .= $allowable_characters[$index];
Chris@0 325 }
Chris@0 326
Chris@0 327 return $pass;
Chris@0 328 }
Chris@0 329
Chris@0 330 /**
Chris@0 331 * Determine the permissions for one or more roles.
Chris@0 332 *
Chris@0 333 * @param array $roles
Chris@0 334 * An array of role IDs.
Chris@0 335 *
Chris@0 336 * @return array
Chris@0 337 * An array indexed by role ID. Each value is an array of permission strings
Chris@0 338 * for the given role.
Chris@0 339 */
Chris@0 340 function user_role_permissions(array $roles) {
Chris@0 341 if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
Chris@0 342 return _user_role_permissions_update($roles);
Chris@0 343 }
Chris@0 344 $entities = Role::loadMultiple($roles);
Chris@0 345 $role_permissions = [];
Chris@0 346 foreach ($roles as $rid) {
Chris@0 347 $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : [];
Chris@0 348 }
Chris@0 349 return $role_permissions;
Chris@0 350 }
Chris@0 351
Chris@0 352 /**
Chris@0 353 * Determine the permissions for one or more roles during update.
Chris@0 354 *
Chris@0 355 * A separate version is needed because during update the entity system can't
Chris@0 356 * be used and in non-update situations the entity system is preferred because
Chris@0 357 * of the hook system.
Chris@0 358 *
Chris@0 359 * @param array $roles
Chris@0 360 * An array of role IDs.
Chris@0 361 *
Chris@0 362 * @return array
Chris@0 363 * An array indexed by role ID. Each value is an array of permission strings
Chris@0 364 * for the given role.
Chris@0 365 */
Chris@0 366 function _user_role_permissions_update($roles) {
Chris@0 367 $role_permissions = [];
Chris@0 368 foreach ($roles as $rid) {
Chris@0 369 $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: [];
Chris@0 370 }
Chris@0 371 return $role_permissions;
Chris@0 372 }
Chris@0 373
Chris@0 374 /**
Chris@0 375 * Checks for usernames blocked by user administration.
Chris@0 376 *
Chris@0 377 * @param string $name
Chris@0 378 * A string containing a name of the user.
Chris@0 379 *
Chris@0 380 * @return bool
Chris@0 381 * TRUE if the user is blocked, FALSE otherwise.
Chris@0 382 */
Chris@0 383 function user_is_blocked($name) {
Chris@0 384 return (bool) \Drupal::entityQuery('user')
Chris@0 385 ->condition('name', $name)
Chris@0 386 ->condition('status', 0)
Chris@0 387 ->execute();
Chris@0 388 }
Chris@0 389
Chris@0 390 /**
Chris@0 391 * Implements hook_ENTITY_TYPE_view() for user entities.
Chris@0 392 */
Chris@0 393 function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
Chris@0 394 if ($display->getComponent('member_for')) {
Chris@0 395 $build['member_for'] = [
Chris@0 396 '#type' => 'item',
Chris@0 397 '#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . \Drupal::service('date.formatter')->formatTimeDiffSince($account->getCreatedTime()),
Chris@0 398 ];
Chris@0 399 }
Chris@0 400 }
Chris@0 401
Chris@0 402 /**
Chris@0 403 * Implements hook_ENTITY_TYPE_view_alter() for user entities.
Chris@0 404 *
Chris@0 405 * This function adds a default alt tag to the user_picture field to maintain
Chris@0 406 * accessibility.
Chris@0 407 */
Chris@0 408 function user_user_view_alter(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
Chris@0 409 if (user_picture_enabled() && !empty($build['user_picture'])) {
Chris@0 410 foreach (Element::children($build['user_picture']) as $key) {
Chris@0 411 $item = $build['user_picture'][$key]['#item'];
Chris@0 412 if (!$item->get('alt')->getValue()) {
Chris@0 413 $item->get('alt')->setValue(\Drupal::translation()->translate('Profile picture for user @username', ['@username' => $account->getUsername()]));
Chris@0 414 }
Chris@0 415 }
Chris@0 416 }
Chris@0 417 }
Chris@0 418
Chris@0 419 /**
Chris@0 420 * Implements hook_preprocess_HOOK() for block templates.
Chris@0 421 */
Chris@0 422 function user_preprocess_block(&$variables) {
Chris@0 423 if ($variables['configuration']['provider'] == 'user') {
Chris@0 424 switch ($variables['elements']['#plugin_id']) {
Chris@0 425 case 'user_login_block':
Chris@0 426 $variables['attributes']['role'] = 'form';
Chris@0 427 break;
Chris@0 428 }
Chris@0 429 }
Chris@0 430 }
Chris@0 431
Chris@0 432 /**
Chris@0 433 * Format a username.
Chris@0 434 *
Chris@0 435 * @param \Drupal\Core\Session\AccountInterface $account
Chris@0 436 * The account object for the user whose name is to be formatted.
Chris@0 437 *
Chris@0 438 * @return string
Chris@0 439 * An unsanitized string with the username to display.
Chris@0 440 *
Chris@0 441 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
Chris@0 442 * Use \Drupal\Core\Session\AccountInterface::getDisplayName().
Chris@0 443 *
Chris@0 444 * @todo Remove usage in https://www.drupal.org/node/2311219.
Chris@0 445 */
Chris@0 446 function user_format_name(AccountInterface $account) {
Chris@0 447 return $account->getDisplayName();
Chris@0 448 }
Chris@0 449
Chris@0 450 /**
Chris@0 451 * Implements hook_template_preprocess_default_variables_alter().
Chris@0 452 *
Chris@0 453 * @see user_user_login()
Chris@0 454 * @see user_user_logout()
Chris@0 455 */
Chris@0 456 function user_template_preprocess_default_variables_alter(&$variables) {
Chris@0 457 $user = \Drupal::currentUser();
Chris@0 458
Chris@0 459 $variables['user'] = clone $user;
Chris@0 460 // Remove password and session IDs, since themes should not need nor see them.
Chris@0 461 unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
Chris@0 462
Chris@0 463 $variables['is_admin'] = $user->hasPermission('access administration pages');
Chris@0 464 $variables['logged_in'] = $user->isAuthenticated();
Chris@0 465 }
Chris@0 466
Chris@0 467 /**
Chris@0 468 * Prepares variables for username templates.
Chris@0 469 *
Chris@0 470 * Default template: username.html.twig.
Chris@0 471 *
Chris@0 472 * Modules that make any changes to variables like 'name' or 'extra' must ensure
Chris@0 473 * that the final string is safe.
Chris@0 474 *
Chris@0 475 * @param array $variables
Chris@0 476 * An associative array containing:
Chris@0 477 * - account: The user account (\Drupal\Core\Session\AccountInterface).
Chris@0 478 */
Chris@0 479 function template_preprocess_username(&$variables) {
Chris@0 480 $account = $variables['account'] ?: new AnonymousUserSession();
Chris@0 481
Chris@0 482 $variables['extra'] = '';
Chris@0 483 $variables['uid'] = $account->id();
Chris@0 484 if (empty($variables['uid'])) {
Chris@0 485 if (theme_get_setting('features.comment_user_verification')) {
Chris@0 486 $variables['extra'] = ' (' . t('not verified') . ')';
Chris@0 487 }
Chris@0 488 }
Chris@0 489
Chris@0 490 // Set the name to a formatted name that is safe for printing and
Chris@0 491 // that won't break tables by being too long. Keep an unshortened,
Chris@0 492 // unsanitized version, in case other preprocess functions want to implement
Chris@0 493 // their own shortening logic or add markup. If they do so, they must ensure
Chris@0 494 // that $variables['name'] is safe for printing.
Chris@0 495 $name = $account->getDisplayName();
Chris@0 496 $variables['name_raw'] = $account->getUsername();
Chris@0 497 if (Unicode::strlen($name) > 20) {
Chris@0 498 $name = Unicode::truncate($name, 15, FALSE, TRUE);
Chris@0 499 $variables['truncated'] = TRUE;
Chris@0 500 }
Chris@0 501 else {
Chris@0 502 $variables['truncated'] = FALSE;
Chris@0 503 }
Chris@0 504 $variables['name'] = $name;
Chris@0 505 $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
Chris@0 506
Chris@0 507 $external = FALSE;
Chris@0 508 // Populate link path and attributes if appropriate.
Chris@0 509 if ($variables['uid'] && $variables['profile_access']) {
Chris@0 510 // We are linking to a local user.
Chris@0 511 $variables['attributes']['title'] = t('View user profile.');
Chris@0 512 $variables['link_path'] = 'user/' . $variables['uid'];
Chris@0 513 }
Chris@0 514 elseif (!empty($account->homepage)) {
Chris@0 515 // Like the 'class' attribute, the 'rel' attribute can hold a
Chris@0 516 // space-separated set of values, so initialize it as an array to make it
Chris@0 517 // easier for other preprocess functions to append to it.
Chris@0 518 $variables['attributes']['rel'] = 'nofollow';
Chris@0 519 $variables['link_path'] = $account->homepage;
Chris@0 520 $variables['homepage'] = $account->homepage;
Chris@0 521 $external = TRUE;
Chris@0 522 }
Chris@0 523 // We have a link path, so we should generate a URL.
Chris@0 524 if (isset($variables['link_path'])) {
Chris@0 525 if ($external) {
Chris@0 526 $variables['attributes']['href'] = Url::fromUri($variables['link_path'], $variables['link_options'])
Chris@0 527 ->toString();
Chris@0 528 }
Chris@0 529 else {
Chris@0 530 $variables['attributes']['href'] = Url::fromRoute('entity.user.canonical', [
Chris@0 531 'user' => $variables['uid'],
Chris@0 532 ])->toString();
Chris@0 533 }
Chris@0 534 }
Chris@0 535 }
Chris@0 536
Chris@0 537 /**
Chris@0 538 * Finalizes the login process and logs in a user.
Chris@0 539 *
Chris@0 540 * The function logs in the user, records a watchdog message about the new
Chris@0 541 * session, saves the login timestamp, calls hook_user_login(), and generates a
Chris@0 542 * new session.
Chris@0 543 *
Chris@0 544 * The current user is replaced with the passed in account.
Chris@0 545 *
Chris@0 546 * @param \Drupal\user\UserInterface $account
Chris@0 547 * The account to log in.
Chris@0 548 *
Chris@0 549 * @see hook_user_login()
Chris@0 550 */
Chris@0 551 function user_login_finalize(UserInterface $account) {
Chris@0 552 \Drupal::currentUser()->setAccount($account);
Chris@0 553 \Drupal::logger('user')->notice('Session opened for %name.', ['%name' => $account->getUsername()]);
Chris@0 554 // Update the user table timestamp noting user has logged in.
Chris@0 555 // This is also used to invalidate one-time login links.
Chris@0 556 $account->setLastLoginTime(REQUEST_TIME);
Chris@0 557 \Drupal::entityManager()
Chris@0 558 ->getStorage('user')
Chris@0 559 ->updateLastLoginTimestamp($account);
Chris@0 560
Chris@0 561 // Regenerate the session ID to prevent against session fixation attacks.
Chris@0 562 // This is called before hook_user_login() in case one of those functions
Chris@0 563 // fails or incorrectly does a redirect which would leave the old session
Chris@0 564 // in place.
Chris@0 565 \Drupal::service('session')->migrate();
Chris@0 566 \Drupal::service('session')->set('uid', $account->id());
Chris@0 567 \Drupal::moduleHandler()->invokeAll('user_login', [$account]);
Chris@0 568 }
Chris@0 569
Chris@0 570 /**
Chris@0 571 * Implements hook_user_login().
Chris@0 572 */
Chris@0 573 function user_user_login($account) {
Chris@0 574 // Reset static cache of default variables in template_preprocess() to reflect
Chris@0 575 // the new user.
Chris@0 576 drupal_static_reset('template_preprocess');
Chris@0 577 }
Chris@0 578
Chris@0 579 /**
Chris@0 580 * Implements hook_user_logout().
Chris@0 581 */
Chris@0 582 function user_user_logout($account) {
Chris@0 583 // Reset static cache of default variables in template_preprocess() to reflect
Chris@0 584 // the new user.
Chris@0 585 drupal_static_reset('template_preprocess');
Chris@0 586 }
Chris@0 587
Chris@0 588 /**
Chris@0 589 * Generates a unique URL for a user to log in and reset their password.
Chris@0 590 *
Chris@0 591 * @param \Drupal\user\UserInterface $account
Chris@0 592 * An object containing the user account.
Chris@0 593 * @param array $options
Chris@0 594 * (optional) A keyed array of settings. Supported options are:
Chris@0 595 * - langcode: A language code to be used when generating locale-sensitive
Chris@0 596 * URLs. If langcode is NULL the users preferred language is used.
Chris@0 597 *
Chris@0 598 * @return string
Chris@0 599 * A unique URL that provides a one-time log in for the user, from which
Chris@0 600 * they can change their password.
Chris@0 601 */
Chris@0 602 function user_pass_reset_url($account, $options = []) {
Chris@0 603 $timestamp = REQUEST_TIME;
Chris@0 604 $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
Chris@0 605 return \Drupal::url('user.reset',
Chris@0 606 [
Chris@0 607 'uid' => $account->id(),
Chris@0 608 'timestamp' => $timestamp,
Chris@0 609 'hash' => user_pass_rehash($account, $timestamp),
Chris@0 610 ],
Chris@0 611 [
Chris@0 612 'absolute' => TRUE,
Chris@0 613 'language' => \Drupal::languageManager()->getLanguage($langcode)
Chris@0 614 ]
Chris@0 615 );
Chris@0 616 }
Chris@0 617
Chris@0 618 /**
Chris@0 619 * Generates a URL to confirm an account cancellation request.
Chris@0 620 *
Chris@0 621 * @param \Drupal\user\UserInterface $account
Chris@0 622 * The user account object.
Chris@0 623 * @param array $options
Chris@0 624 * (optional) A keyed array of settings. Supported options are:
Chris@0 625 * - langcode: A language code to be used when generating locale-sensitive
Chris@0 626 * URLs. If langcode is NULL the users preferred language is used.
Chris@0 627 *
Chris@0 628 * @return string
Chris@0 629 * A unique URL that may be used to confirm the cancellation of the user
Chris@0 630 * account.
Chris@0 631 *
Chris@0 632 * @see user_mail_tokens()
Chris@0 633 * @see \Drupal\user\Controller\UserController::confirmCancel()
Chris@0 634 */
Chris@0 635 function user_cancel_url(UserInterface $account, $options = []) {
Chris@0 636 $timestamp = REQUEST_TIME;
Chris@0 637 $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
Chris@0 638 $url_options = ['absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode)];
Chris@0 639 return \Drupal::url('user.cancel_confirm', [
Chris@0 640 'user' => $account->id(),
Chris@0 641 'timestamp' => $timestamp,
Chris@0 642 'hashed_pass' => user_pass_rehash($account, $timestamp)
Chris@0 643 ], $url_options);
Chris@0 644 }
Chris@0 645
Chris@0 646 /**
Chris@0 647 * Creates a unique hash value for use in time-dependent per-user URLs.
Chris@0 648 *
Chris@0 649 * This hash is normally used to build a unique and secure URL that is sent to
Chris@0 650 * the user by email for purposes such as resetting the user's password. In
Chris@0 651 * order to validate the URL, the same hash can be generated again, from the
Chris@0 652 * same information, and compared to the hash value from the URL. The hash
Chris@0 653 * contains the time stamp, the user's last login time, the numeric user ID,
Chris@0 654 * and the user's email address.
Chris@0 655 * For a usage example, see user_cancel_url() and
Chris@0 656 * \Drupal\user\Controller\UserController::confirmCancel().
Chris@0 657 *
Chris@0 658 * @param \Drupal\user\UserInterface $account
Chris@0 659 * An object containing the user account.
Chris@0 660 * @param int $timestamp
Chris@0 661 * A UNIX timestamp, typically REQUEST_TIME.
Chris@0 662 *
Chris@0 663 * @return string
Chris@0 664 * A string that is safe for use in URLs and SQL statements.
Chris@0 665 */
Chris@0 666 function user_pass_rehash(UserInterface $account, $timestamp) {
Chris@0 667 $data = $timestamp;
Chris@0 668 $data .= $account->getLastLoginTime();
Chris@0 669 $data .= $account->id();
Chris@0 670 $data .= $account->getEmail();
Chris@0 671 return Crypt::hmacBase64($data, Settings::getHashSalt() . $account->getPassword());
Chris@0 672 }
Chris@0 673
Chris@0 674 /**
Chris@0 675 * Cancel a user account.
Chris@0 676 *
Chris@0 677 * Since the user cancellation process needs to be run in a batch, either
Chris@0 678 * Form API will invoke it, or batch_process() needs to be invoked after calling
Chris@0 679 * this function and should define the path to redirect to.
Chris@0 680 *
Chris@0 681 * @param array $edit
Chris@0 682 * An array of submitted form values.
Chris@0 683 * @param int $uid
Chris@0 684 * The user ID of the user account to cancel.
Chris@0 685 * @param string $method
Chris@0 686 * The account cancellation method to use.
Chris@0 687 *
Chris@0 688 * @see _user_cancel()
Chris@0 689 */
Chris@0 690 function user_cancel($edit, $uid, $method) {
Chris@0 691 $account = User::load($uid);
Chris@0 692
Chris@0 693 if (!$account) {
Chris@0 694 drupal_set_message(t('The user account %id does not exist.', ['%id' => $uid]), 'error');
Chris@0 695 \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
Chris@0 696 return;
Chris@0 697 }
Chris@0 698
Chris@0 699 // Initialize batch (to set title).
Chris@0 700 $batch = [
Chris@0 701 'title' => t('Cancelling account'),
Chris@0 702 'operations' => [],
Chris@0 703 ];
Chris@0 704 batch_set($batch);
Chris@0 705
Chris@0 706 // When the 'user_cancel_delete' method is used, user_delete() is called,
Chris@0 707 // which invokes hook_ENTITY_TYPE_predelete() and hook_ENTITY_TYPE_delete()
Chris@0 708 // for the user entity. Modules should use those hooks to respond to the
Chris@0 709 // account deletion.
Chris@0 710 if ($method != 'user_cancel_delete') {
Chris@0 711 // Allow modules to add further sets to this batch.
Chris@0 712 \Drupal::moduleHandler()->invokeAll('user_cancel', [$edit, $account, $method]);
Chris@0 713 }
Chris@0 714
Chris@0 715 // Finish the batch and actually cancel the account.
Chris@0 716 $batch = [
Chris@0 717 'title' => t('Cancelling user account'),
Chris@0 718 'operations' => [
Chris@0 719 ['_user_cancel', [$edit, $account, $method]],
Chris@0 720 ],
Chris@0 721 ];
Chris@0 722
Chris@0 723 // After cancelling account, ensure that user is logged out.
Chris@0 724 if ($account->id() == \Drupal::currentUser()->id()) {
Chris@0 725 // Batch API stores data in the session, so use the finished operation to
Chris@0 726 // manipulate the current user's session id.
Chris@0 727 $batch['finished'] = '_user_cancel_session_regenerate';
Chris@0 728 }
Chris@0 729
Chris@0 730 batch_set($batch);
Chris@0 731
Chris@0 732 // Batch processing is either handled via Form API or has to be invoked
Chris@0 733 // manually.
Chris@0 734 }
Chris@0 735
Chris@0 736 /**
Chris@0 737 * Implements callback_batch_operation().
Chris@0 738 *
Chris@0 739 * Last step for cancelling a user account.
Chris@0 740 *
Chris@0 741 * Since batch and session API require a valid user account, the actual
Chris@0 742 * cancellation of a user account needs to happen last.
Chris@0 743 * @param array $edit
Chris@0 744 * An array of submitted form values.
Chris@0 745 * @param \Drupal\user\UserInterface $account
Chris@0 746 * The user ID of the user account to cancel.
Chris@0 747 * @param string $method
Chris@0 748 * The account cancellation method to use.
Chris@0 749 *
Chris@0 750 * @see user_cancel()
Chris@0 751 */
Chris@0 752 function _user_cancel($edit, $account, $method) {
Chris@0 753 $logger = \Drupal::logger('user');
Chris@0 754
Chris@0 755 switch ($method) {
Chris@0 756 case 'user_cancel_block':
Chris@0 757 case 'user_cancel_block_unpublish':
Chris@0 758 default:
Chris@0 759 // Send account blocked notification if option was checked.
Chris@0 760 if (!empty($edit['user_cancel_notify'])) {
Chris@0 761 _user_mail_notify('status_blocked', $account);
Chris@0 762 }
Chris@0 763 $account->block();
Chris@0 764 $account->save();
Chris@0 765 drupal_set_message(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
Chris@0 766 $logger->notice('Blocked user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
Chris@0 767 break;
Chris@0 768
Chris@0 769 case 'user_cancel_reassign':
Chris@0 770 case 'user_cancel_delete':
Chris@0 771 // Send account canceled notification if option was checked.
Chris@0 772 if (!empty($edit['user_cancel_notify'])) {
Chris@0 773 _user_mail_notify('status_canceled', $account);
Chris@0 774 }
Chris@0 775 $account->delete();
Chris@0 776 drupal_set_message(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
Chris@0 777 $logger->notice('Deleted user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
Chris@0 778 break;
Chris@0 779 }
Chris@0 780
Chris@0 781 // After cancelling account, ensure that user is logged out. We can't destroy
Chris@0 782 // their session though, as we might have information in it, and we can't
Chris@0 783 // regenerate it because batch API uses the session ID, we will regenerate it
Chris@0 784 // in _user_cancel_session_regenerate().
Chris@0 785 if ($account->id() == \Drupal::currentUser()->id()) {
Chris@0 786 \Drupal::currentUser()->setAccount(new AnonymousUserSession());
Chris@0 787 }
Chris@0 788 }
Chris@0 789
Chris@0 790 /**
Chris@0 791 * Implements callback_batch_finished().
Chris@0 792 *
Chris@0 793 * Finished batch processing callback for cancelling a user account.
Chris@0 794 *
Chris@0 795 * @see user_cancel()
Chris@0 796 */
Chris@0 797 function _user_cancel_session_regenerate() {
Chris@0 798 // Regenerate the users session instead of calling session_destroy() as we
Chris@0 799 // want to preserve any messages that might have been set.
Chris@0 800 \Drupal::service('session')->migrate();
Chris@0 801 }
Chris@0 802
Chris@0 803 /**
Chris@0 804 * Helper function to return available account cancellation methods.
Chris@0 805 *
Chris@0 806 * See documentation of hook_user_cancel_methods_alter().
Chris@0 807 *
Chris@0 808 * @return array
Chris@0 809 * An array containing all account cancellation methods as form elements.
Chris@0 810 *
Chris@0 811 * @see hook_user_cancel_methods_alter()
Chris@0 812 * @see user_admin_settings()
Chris@0 813 */
Chris@0 814 function user_cancel_methods() {
Chris@0 815 $user_settings = \Drupal::config('user.settings');
Chris@0 816 $anonymous_name = $user_settings->get('anonymous');
Chris@0 817 $methods = [
Chris@0 818 'user_cancel_block' => [
Chris@0 819 'title' => t('Disable the account and keep its content.'),
Chris@0 820 'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your username.'),
Chris@0 821 ],
Chris@0 822 'user_cancel_block_unpublish' => [
Chris@0 823 'title' => t('Disable the account and unpublish its content.'),
Chris@0 824 'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'),
Chris@0 825 ],
Chris@0 826 'user_cancel_reassign' => [
Chris@0 827 'title' => t('Delete the account and make its content belong to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
Chris@0 828 'description' => t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
Chris@0 829 ],
Chris@0 830 'user_cancel_delete' => [
Chris@0 831 'title' => t('Delete the account and its content.'),
Chris@0 832 'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
Chris@0 833 'access' => \Drupal::currentUser()->hasPermission('administer users'),
Chris@0 834 ],
Chris@0 835 ];
Chris@0 836 // Allow modules to customize account cancellation methods.
Chris@0 837 \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
Chris@0 838
Chris@0 839 // Turn all methods into real form elements.
Chris@0 840 $form = [
Chris@0 841 '#options' => [],
Chris@0 842 '#default_value' => $user_settings->get('cancel_method'),
Chris@0 843 ];
Chris@0 844 foreach ($methods as $name => $method) {
Chris@0 845 $form['#options'][$name] = $method['title'];
Chris@0 846 // Add the description for the confirmation form. This description is never
Chris@0 847 // shown for the cancel method option, only on the confirmation form.
Chris@0 848 // Therefore, we use a custom #confirm_description property.
Chris@0 849 if (isset($method['description'])) {
Chris@0 850 $form[$name]['#confirm_description'] = $method['description'];
Chris@0 851 }
Chris@0 852 if (isset($method['access'])) {
Chris@0 853 $form[$name]['#access'] = $method['access'];
Chris@0 854 }
Chris@0 855 }
Chris@0 856 return $form;
Chris@0 857 }
Chris@0 858
Chris@0 859 /**
Chris@0 860 * Delete a user.
Chris@0 861 *
Chris@0 862 * @param int $uid
Chris@0 863 * A user ID.
Chris@0 864 */
Chris@0 865 function user_delete($uid) {
Chris@0 866 user_delete_multiple([$uid]);
Chris@0 867 }
Chris@0 868
Chris@0 869 /**
Chris@0 870 * Delete multiple user accounts.
Chris@0 871 *
Chris@0 872 * @param int[] $uids
Chris@0 873 * An array of user IDs.
Chris@0 874 *
Chris@0 875 * @see hook_ENTITY_TYPE_predelete()
Chris@0 876 * @see hook_ENTITY_TYPE_delete()
Chris@0 877 */
Chris@0 878 function user_delete_multiple(array $uids) {
Chris@0 879 entity_delete_multiple('user', $uids);
Chris@0 880 }
Chris@0 881
Chris@0 882 /**
Chris@0 883 * Generate an array for rendering the given user.
Chris@0 884 *
Chris@0 885 * When viewing a user profile, the $page array contains:
Chris@0 886 *
Chris@0 887 * - $page['content']['member_for']:
Chris@0 888 * Contains the default "Member for" profile data for a user.
Chris@0 889 * - $page['content']['#user']:
Chris@0 890 * The user account of the profile being viewed.
Chris@0 891 *
Chris@0 892 * To theme user profiles, copy core/modules/user/templates/user.html.twig
Chris@0 893 * to your theme directory, and edit it as instructed in that file's comments.
Chris@0 894 *
Chris@0 895 * @param \Drupal\user\UserInterface $account
Chris@0 896 * A user object.
Chris@0 897 * @param string $view_mode
Chris@0 898 * View mode, e.g. 'full'.
Chris@0 899 * @param string|null $langcode
Chris@0 900 * (optional) A language code to use for rendering. Defaults to the global
Chris@0 901 * content language of the current request.
Chris@0 902 *
Chris@0 903 * @return array
Chris@0 904 * An array as expected by drupal_render().
Chris@0 905 */
Chris@0 906 function user_view($account, $view_mode = 'full', $langcode = NULL) {
Chris@0 907 return entity_view($account, $view_mode, $langcode);
Chris@0 908 }
Chris@0 909
Chris@0 910 /**
Chris@0 911 * Constructs a drupal_render() style array from an array of loaded users.
Chris@0 912 *
Chris@0 913 * @param \Drupal\user\UserInterface[] $accounts
Chris@0 914 * An array of user accounts as returned by User::loadMultiple().
Chris@0 915 * @param string $view_mode
Chris@0 916 * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
Chris@0 917 * @param string|null $langcode
Chris@0 918 * (optional) A language code to use for rendering. Defaults to the global
Chris@0 919 * content language of the current request.
Chris@0 920 *
Chris@0 921 * @return array
Chris@0 922 * An array in the format expected by drupal_render().
Chris@0 923 */
Chris@0 924 function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
Chris@0 925 return entity_view_multiple($accounts, $view_mode, $langcode);
Chris@0 926 }
Chris@0 927
Chris@0 928 /**
Chris@0 929 * Implements hook_mail().
Chris@0 930 */
Chris@0 931 function user_mail($key, &$message, $params) {
Chris@0 932 $token_service = \Drupal::token();
Chris@0 933 $language_manager = \Drupal::languageManager();
Chris@0 934 $langcode = $message['langcode'];
Chris@0 935 $variables = ['user' => $params['account']];
Chris@0 936
Chris@0 937 $language = $language_manager->getLanguage($params['account']->getPreferredLangcode());
Chris@0 938 $original_language = $language_manager->getConfigOverrideLanguage();
Chris@0 939 $language_manager->setConfigOverrideLanguage($language);
Chris@0 940 $mail_config = \Drupal::config('user.mail');
Chris@0 941
Chris@0 942 $token_options = ['langcode' => $langcode, 'callback' => 'user_mail_tokens', 'clear' => TRUE];
Chris@0 943 $message['subject'] .= PlainTextOutput::renderFromHtml($token_service->replace($mail_config->get($key . '.subject'), $variables, $token_options));
Chris@0 944 $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);
Chris@0 945
Chris@0 946 $language_manager->setConfigOverrideLanguage($original_language);
Chris@0 947
Chris@0 948 }
Chris@0 949
Chris@0 950 /**
Chris@0 951 * Token callback to add unsafe tokens for user mails.
Chris@0 952 *
Chris@0 953 * This function is used by \Drupal\Core\Utility\Token::replace() to set up
Chris@0 954 * some additional tokens that can be used in email messages generated by
Chris@0 955 * user_mail().
Chris@0 956 *
Chris@0 957 * @param array $replacements
Chris@0 958 * An associative array variable containing mappings from token names to
Chris@0 959 * values (for use with strtr()).
Chris@0 960 * @param array $data
Chris@0 961 * An associative array of token replacement values. If the 'user' element
Chris@0 962 * exists, it must contain a user account object with the following
Chris@0 963 * properties:
Chris@0 964 * - login: The UNIX timestamp of the user's last login.
Chris@0 965 * - pass: The hashed account login password.
Chris@0 966 * @param array $options
Chris@0 967 * A keyed array of settings and flags to control the token replacement
Chris@0 968 * process. See \Drupal\Core\Utility\Token::replace().
Chris@0 969 */
Chris@0 970 function user_mail_tokens(&$replacements, $data, $options) {
Chris@0 971 if (isset($data['user'])) {
Chris@0 972 $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
Chris@0 973 $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
Chris@0 974 }
Chris@0 975 }
Chris@0 976
Chris@0 977 /*** Administrative features ***********************************************/
Chris@0 978
Chris@0 979 /**
Chris@0 980 * Retrieves the names of roles matching specified conditions.
Chris@0 981 *
Chris@0 982 * @param bool $membersonly
Chris@0 983 * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
Chris@0 984 * FALSE.
Chris@0 985 * @param string|null $permission
Chris@0 986 * (optional) A string containing a permission. If set, only roles
Chris@0 987 * containing that permission are returned. Defaults to NULL, which
Chris@0 988 * returns all roles.
Chris@0 989 *
Chris@0 990 * @return array
Chris@0 991 * An associative array with the role id as the key and the role name as
Chris@0 992 * value.
Chris@0 993 */
Chris@0 994 function user_role_names($membersonly = FALSE, $permission = NULL) {
Chris@0 995 return array_map(function ($item) {
Chris@0 996 return $item->label();
Chris@0 997 }, user_roles($membersonly, $permission));
Chris@0 998 }
Chris@0 999
Chris@0 1000 /**
Chris@0 1001 * Implements hook_ENTITY_TYPE_insert() for user_role entities.
Chris@0 1002 */
Chris@0 1003 function user_user_role_insert(RoleInterface $role) {
Chris@0 1004 // Ignore the authenticated and anonymous roles or the role is being synced.
Chris@0 1005 if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
Chris@0 1006 return;
Chris@0 1007 }
Chris@0 1008
Chris@0 1009 $add_id = 'user_add_role_action.' . $role->id();
Chris@0 1010 if (!Action::load($add_id)) {
Chris@0 1011 $action = Action::create([
Chris@0 1012 'id' => $add_id,
Chris@0 1013 'type' => 'user',
Chris@0 1014 'label' => t('Add the @label role to the selected user(s)', ['@label' => $role->label()]),
Chris@0 1015 'configuration' => [
Chris@0 1016 'rid' => $role->id(),
Chris@0 1017 ],
Chris@0 1018 'plugin' => 'user_add_role_action',
Chris@0 1019 ]);
Chris@0 1020 $action->trustData()->save();
Chris@0 1021 }
Chris@0 1022 $remove_id = 'user_remove_role_action.' . $role->id();
Chris@0 1023 if (!Action::load($remove_id)) {
Chris@0 1024 $action = Action::create([
Chris@0 1025 'id' => $remove_id,
Chris@0 1026 'type' => 'user',
Chris@0 1027 'label' => t('Remove the @label role from the selected user(s)', ['@label' => $role->label()]),
Chris@0 1028 'configuration' => [
Chris@0 1029 'rid' => $role->id(),
Chris@0 1030 ],
Chris@0 1031 'plugin' => 'user_remove_role_action',
Chris@0 1032 ]);
Chris@0 1033 $action->trustData()->save();
Chris@0 1034 }
Chris@0 1035 }
Chris@0 1036
Chris@0 1037 /**
Chris@0 1038 * Implements hook_ENTITY_TYPE_delete() for user_role entities.
Chris@0 1039 */
Chris@0 1040 function user_user_role_delete(RoleInterface $role) {
Chris@0 1041 // Delete role references for all users.
Chris@0 1042 $user_storage = \Drupal::entityManager()->getStorage('user');
Chris@0 1043 $user_storage->deleteRoleReferences([$role->id()]);
Chris@0 1044
Chris@0 1045 // Ignore the authenticated and anonymous roles or the role is being synced.
Chris@0 1046 if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
Chris@0 1047 return;
Chris@0 1048 }
Chris@0 1049
Chris@0 1050 $actions = Action::loadMultiple([
Chris@0 1051 'user_add_role_action.' . $role->id(),
Chris@0 1052 'user_remove_role_action.' . $role->id(),
Chris@0 1053 ]);
Chris@0 1054 foreach ($actions as $action) {
Chris@0 1055 $action->delete();
Chris@0 1056 }
Chris@0 1057 }
Chris@0 1058
Chris@0 1059 /**
Chris@0 1060 * Retrieve an array of roles matching specified conditions.
Chris@0 1061 *
Chris@0 1062 * @param bool $membersonly
Chris@0 1063 * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
Chris@0 1064 * FALSE.
Chris@0 1065 * @param string|null $permission
Chris@0 1066 * (optional) A string containing a permission. If set, only roles
Chris@0 1067 * containing that permission are returned. Defaults to NULL, which
Chris@0 1068 * returns all roles.
Chris@0 1069 *
Chris@0 1070 * @return \Drupal\user\RoleInterface[]
Chris@0 1071 * An associative array with the role id as the key and the role object as
Chris@0 1072 * value.
Chris@0 1073 */
Chris@0 1074 function user_roles($membersonly = FALSE, $permission = NULL) {
Chris@0 1075 $roles = Role::loadMultiple();
Chris@0 1076 if ($membersonly) {
Chris@0 1077 unset($roles[RoleInterface::ANONYMOUS_ID]);
Chris@0 1078 }
Chris@0 1079
Chris@0 1080 if (!empty($permission)) {
Chris@0 1081 $roles = array_filter($roles, function ($role) use ($permission) {
Chris@0 1082 return $role->hasPermission($permission);
Chris@0 1083 });
Chris@0 1084 }
Chris@0 1085
Chris@0 1086 return $roles;
Chris@0 1087 }
Chris@0 1088
Chris@0 1089 /**
Chris@0 1090 * Fetches a user role by role ID.
Chris@0 1091 *
Chris@0 1092 * @param string $rid
Chris@0 1093 * A string representing the role ID.
Chris@0 1094 *
Chris@0 1095 * @return \Drupal\user\RoleInterface|null
Chris@0 1096 * A fully-loaded role object if a role with the given ID exists, or NULL
Chris@0 1097 * otherwise.
Chris@0 1098 *
Chris@0 1099 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
Chris@0 1100 * Use \Drupal\user\Entity\Role::load().
Chris@0 1101 */
Chris@0 1102 function user_role_load($rid) {
Chris@0 1103 return Role::load($rid);
Chris@0 1104 }
Chris@0 1105
Chris@0 1106 /**
Chris@0 1107 * Change permissions for a user role.
Chris@0 1108 *
Chris@0 1109 * This function may be used to grant and revoke multiple permissions at once.
Chris@0 1110 * For example, when a form exposes checkboxes to configure permissions for a
Chris@0 1111 * role, the form submit handler may directly pass the submitted values for the
Chris@0 1112 * checkboxes form element to this function.
Chris@0 1113 *
Chris@0 1114 * @param mixed $rid
Chris@0 1115 * The ID of a user role to alter.
Chris@0 1116 * @param array $permissions
Chris@0 1117 * (optional) An associative array, where the key holds the permission name
Chris@0 1118 * and the value determines whether to grant or revoke that permission. Any
Chris@0 1119 * value that evaluates to TRUE will cause the permission to be granted.
Chris@0 1120 * Any value that evaluates to FALSE will cause the permission to be
Chris@0 1121 * revoked.
Chris@0 1122 * @code
Chris@0 1123 * array(
Chris@0 1124 * 'administer nodes' => 0, // Revoke 'administer nodes'
Chris@0 1125 * 'administer blocks' => FALSE, // Revoke 'administer blocks'
Chris@0 1126 * 'access user profiles' => 1, // Grant 'access user profiles'
Chris@0 1127 * 'access content' => TRUE, // Grant 'access content'
Chris@0 1128 * 'access comments' => 'access comments', // Grant 'access comments'
Chris@0 1129 * )
Chris@0 1130 * @endcode
Chris@0 1131 * Existing permissions are not changed, unless specified in $permissions.
Chris@0 1132 *
Chris@0 1133 * @see user_role_grant_permissions()
Chris@0 1134 * @see user_role_revoke_permissions()
Chris@0 1135 */
Chris@0 1136 function user_role_change_permissions($rid, array $permissions = []) {
Chris@0 1137 // Grant new permissions for the role.
Chris@0 1138 $grant = array_filter($permissions);
Chris@0 1139 if (!empty($grant)) {
Chris@0 1140 user_role_grant_permissions($rid, array_keys($grant));
Chris@0 1141 }
Chris@0 1142 // Revoke permissions for the role.
Chris@0 1143 $revoke = array_diff_assoc($permissions, $grant);
Chris@0 1144 if (!empty($revoke)) {
Chris@0 1145 user_role_revoke_permissions($rid, array_keys($revoke));
Chris@0 1146 }
Chris@0 1147 }
Chris@0 1148
Chris@0 1149 /**
Chris@0 1150 * Grant permissions to a user role.
Chris@0 1151 *
Chris@0 1152 * @param mixed $rid
Chris@0 1153 * The ID of a user role to alter.
Chris@0 1154 * @param array $permissions
Chris@0 1155 * (optional) A list of permission names to grant.
Chris@0 1156 *
Chris@0 1157 * @see user_role_change_permissions()
Chris@0 1158 * @see user_role_revoke_permissions()
Chris@0 1159 */
Chris@0 1160 function user_role_grant_permissions($rid, array $permissions = []) {
Chris@0 1161 // Grant new permissions for the role.
Chris@0 1162 if ($role = Role::load($rid)) {
Chris@0 1163 foreach ($permissions as $permission) {
Chris@0 1164 $role->grantPermission($permission);
Chris@0 1165 }
Chris@0 1166 $role->trustData()->save();
Chris@0 1167 }
Chris@0 1168 }
Chris@0 1169
Chris@0 1170 /**
Chris@0 1171 * Revoke permissions from a user role.
Chris@0 1172 *
Chris@0 1173 * @param mixed $rid
Chris@0 1174 * The ID of a user role to alter.
Chris@0 1175 * @param array $permissions
Chris@0 1176 * (optional) A list of permission names to revoke.
Chris@0 1177 *
Chris@0 1178 * @see user_role_change_permissions()
Chris@0 1179 * @see user_role_grant_permissions()
Chris@0 1180 */
Chris@0 1181 function user_role_revoke_permissions($rid, array $permissions = []) {
Chris@0 1182 // Revoke permissions for the role.
Chris@0 1183 $role = Role::load($rid);
Chris@0 1184 foreach ($permissions as $permission) {
Chris@0 1185 $role->revokePermission($permission);
Chris@0 1186 }
Chris@0 1187 $role->trustData()->save();
Chris@0 1188 }
Chris@0 1189
Chris@0 1190 /**
Chris@0 1191 * Conditionally create and send a notification email when a certain
Chris@0 1192 * operation happens on the given user account.
Chris@0 1193 *
Chris@0 1194 * @param string $op
Chris@0 1195 * The operation being performed on the account. Possible values:
Chris@0 1196 * - 'register_admin_created': Welcome message for user created by the admin.
Chris@0 1197 * - 'register_no_approval_required': Welcome message when user
Chris@0 1198 * self-registers.
Chris@0 1199 * - 'register_pending_approval': Welcome message, user pending admin
Chris@0 1200 * approval.
Chris@0 1201 * - 'password_reset': Password recovery request.
Chris@0 1202 * - 'status_activated': Account activated.
Chris@0 1203 * - 'status_blocked': Account blocked.
Chris@0 1204 * - 'cancel_confirm': Account cancellation request.
Chris@0 1205 * - 'status_canceled': Account canceled.
Chris@0 1206 *
Chris@0 1207 * @param \Drupal\Core\Session\AccountInterface $account
Chris@0 1208 * The user object of the account being notified. Must contain at
Chris@0 1209 * least the fields 'uid', 'name', and 'mail'.
Chris@0 1210 * @param string $langcode
Chris@0 1211 * (optional) Language code to use for the notification, overriding account
Chris@0 1212 * language.
Chris@0 1213 *
Chris@0 1214 * @return array
Chris@0 1215 * An array containing various information about the message.
Chris@0 1216 * See \Drupal\Core\Mail\MailManagerInterface::mail() for details.
Chris@0 1217 *
Chris@0 1218 * @see user_mail_tokens()
Chris@0 1219 */
Chris@0 1220 function _user_mail_notify($op, $account, $langcode = NULL) {
Chris@0 1221 if (\Drupal::config('user.settings')->get('notify.' . $op)) {
Chris@0 1222 $params['account'] = $account;
Chris@0 1223 $langcode = $langcode ? $langcode : $account->getPreferredLangcode();
Chris@0 1224 // Get the custom site notification email to use as the from email address
Chris@0 1225 // if it has been set.
Chris@0 1226 $site_mail = \Drupal::config('system.site')->get('mail_notification');
Chris@0 1227 // If the custom site notification email has not been set, we use the site
Chris@0 1228 // default for this.
Chris@0 1229 if (empty($site_mail)) {
Chris@0 1230 $site_mail = \Drupal::config('system.site')->get('mail');
Chris@0 1231 }
Chris@0 1232 if (empty($site_mail)) {
Chris@0 1233 $site_mail = ini_get('sendmail_from');
Chris@0 1234 }
Chris@0 1235 $mail = \Drupal::service('plugin.manager.mail')->mail('user', $op, $account->getEmail(), $langcode, $params, $site_mail);
Chris@0 1236 if ($op == 'register_pending_approval') {
Chris@0 1237 // If a user registered requiring admin approval, notify the admin, too.
Chris@0 1238 // We use the site default language for this.
Chris@0 1239 \Drupal::service('plugin.manager.mail')->mail('user', 'register_pending_approval_admin', $site_mail, \Drupal::languageManager()->getDefaultLanguage()->getId(), $params);
Chris@0 1240 }
Chris@0 1241 }
Chris@0 1242 return empty($mail) ? NULL : $mail['result'];
Chris@0 1243 }
Chris@0 1244
Chris@0 1245 /**
Chris@0 1246 * Implements hook_element_info_alter().
Chris@0 1247 */
Chris@0 1248 function user_element_info_alter(array &$types) {
Chris@0 1249 if (isset($types['password_confirm'])) {
Chris@0 1250 $types['password_confirm']['#process'][] = 'user_form_process_password_confirm';
Chris@0 1251 }
Chris@0 1252 }
Chris@0 1253
Chris@0 1254 /**
Chris@0 1255 * Form element process handler for client-side password validation.
Chris@0 1256 *
Chris@0 1257 * This #process handler is automatically invoked for 'password_confirm' form
Chris@0 1258 * elements to add the JavaScript and string translations for dynamic password
Chris@0 1259 * validation.
Chris@0 1260 */
Chris@0 1261 function user_form_process_password_confirm($element) {
Chris@0 1262 $password_settings = [
Chris@0 1263 'confirmTitle' => t('Passwords match:'),
Chris@0 1264 'confirmSuccess' => t('yes'),
Chris@0 1265 'confirmFailure' => t('no'),
Chris@0 1266 'showStrengthIndicator' => FALSE,
Chris@0 1267 ];
Chris@0 1268
Chris@0 1269 if (\Drupal::config('user.settings')->get('password_strength')) {
Chris@0 1270 $password_settings['showStrengthIndicator'] = TRUE;
Chris@0 1271 $password_settings += [
Chris@0 1272 'strengthTitle' => t('Password strength:'),
Chris@0 1273 'hasWeaknesses' => t('Recommendations to make your password stronger:'),
Chris@0 1274 'tooShort' => t('Make it at least 12 characters'),
Chris@0 1275 'addLowerCase' => t('Add lowercase letters'),
Chris@0 1276 'addUpperCase' => t('Add uppercase letters'),
Chris@0 1277 'addNumbers' => t('Add numbers'),
Chris@0 1278 'addPunctuation' => t('Add punctuation'),
Chris@0 1279 'sameAsUsername' => t('Make it different from your username'),
Chris@0 1280 'weak' => t('Weak'),
Chris@0 1281 'fair' => t('Fair'),
Chris@0 1282 'good' => t('Good'),
Chris@0 1283 'strong' => t('Strong'),
Chris@0 1284 'username' => \Drupal::currentUser()->getUsername(),
Chris@0 1285 ];
Chris@0 1286 }
Chris@0 1287
Chris@0 1288 $element['#attached']['library'][] = 'user/drupal.user';
Chris@0 1289 $element['#attached']['drupalSettings']['password'] = $password_settings;
Chris@0 1290
Chris@0 1291 return $element;
Chris@0 1292 }
Chris@0 1293
Chris@0 1294 /**
Chris@0 1295 * Implements hook_modules_uninstalled().
Chris@0 1296 */
Chris@0 1297 function user_modules_uninstalled($modules) {
Chris@0 1298 // Remove any potentially orphan module data stored for users.
Chris@0 1299 \Drupal::service('user.data')->delete($modules);
Chris@0 1300 }
Chris@0 1301
Chris@0 1302 /**
Chris@0 1303 * Saves visitor information as a cookie so it can be reused.
Chris@0 1304 *
Chris@0 1305 * @param array $values
Chris@0 1306 * An array of key/value pairs to be saved into a cookie.
Chris@0 1307 */
Chris@0 1308 function user_cookie_save(array $values) {
Chris@0 1309 foreach ($values as $field => $value) {
Chris@0 1310 // Set cookie for 365 days.
Chris@0 1311 setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
Chris@0 1312 }
Chris@0 1313 }
Chris@0 1314
Chris@0 1315 /**
Chris@0 1316 * Delete a visitor information cookie.
Chris@0 1317 *
Chris@0 1318 * @param string $cookie_name
Chris@0 1319 * A cookie name such as 'homepage'.
Chris@0 1320 */
Chris@0 1321 function user_cookie_delete($cookie_name) {
Chris@0 1322 setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
Chris@0 1323 }
Chris@0 1324
Chris@0 1325 /**
Chris@0 1326 * Implements hook_toolbar().
Chris@0 1327 */
Chris@0 1328 function user_toolbar() {
Chris@0 1329 $user = \Drupal::currentUser();
Chris@0 1330
Chris@0 1331 // Add logout & user account links or login link.
Chris@0 1332 $links_cache_contexts = [];
Chris@0 1333 if ($user->isAuthenticated()) {
Chris@0 1334 $links = [
Chris@0 1335 'account' => [
Chris@0 1336 'title' => t('View profile'),
Chris@0 1337 'url' => Url::fromRoute('user.page'),
Chris@0 1338 'attributes' => [
Chris@0 1339 'title' => t('User account'),
Chris@0 1340 ],
Chris@0 1341 ],
Chris@0 1342 'account_edit' => [
Chris@0 1343 'title' => t('Edit profile'),
Chris@0 1344 'url' => Url::fromRoute('entity.user.edit_form', ['user' => $user->id()]),
Chris@0 1345 'attributes' => [
Chris@0 1346 'title' => t('Edit user account'),
Chris@0 1347 ],
Chris@0 1348 ],
Chris@0 1349 'logout' => [
Chris@0 1350 'title' => t('Log out'),
Chris@0 1351 'url' => Url::fromRoute('user.logout'),
Chris@0 1352 ],
Chris@0 1353 ];
Chris@0 1354 // The "Edit user account" link is per-user.
Chris@0 1355 $links_cache_contexts[] = 'user';
Chris@0 1356 }
Chris@0 1357 else {
Chris@0 1358 $links = [
Chris@0 1359 'login' => [
Chris@0 1360 'title' => t('Log in'),
Chris@0 1361 'url' => Url::fromRoute('user.page'),
Chris@0 1362 ],
Chris@0 1363 ];
Chris@0 1364 }
Chris@0 1365
Chris@0 1366 $items['user'] = [
Chris@0 1367 '#type' => 'toolbar_item',
Chris@0 1368 'tab' => [
Chris@0 1369 '#type' => 'link',
Chris@0 1370 '#title' => $user->getDisplayName(),
Chris@0 1371 '#url' => Url::fromRoute('user.page'),
Chris@0 1372 '#attributes' => [
Chris@0 1373 'title' => t('My account'),
Chris@0 1374 'class' => ['toolbar-icon', 'toolbar-icon-user'],
Chris@0 1375 ],
Chris@0 1376 '#cache' => [
Chris@0 1377 'contexts' => [
Chris@0 1378 // Cacheable per user, because the current user's name is shown.
Chris@0 1379 'user',
Chris@0 1380 ],
Chris@0 1381 ],
Chris@0 1382 ],
Chris@0 1383 'tray' => [
Chris@0 1384 '#heading' => t('User account actions'),
Chris@0 1385 'user_links' => [
Chris@0 1386 '#cache' => [
Chris@0 1387 // Cacheable per "authenticated or not", because the links to
Chris@0 1388 // display depend on that.
Chris@0 1389 'contexts' => Cache::mergeContexts(['user.roles:authenticated'], $links_cache_contexts),
Chris@0 1390 ],
Chris@0 1391 '#theme' => 'links__toolbar_user',
Chris@0 1392 '#links' => $links,
Chris@0 1393 '#attributes' => [
Chris@0 1394 'class' => ['toolbar-menu'],
Chris@0 1395 ],
Chris@0 1396 ],
Chris@0 1397 ],
Chris@0 1398 '#weight' => 100,
Chris@0 1399 '#attached' => [
Chris@0 1400 'library' => [
Chris@0 1401 'user/drupal.user.icons',
Chris@0 1402 ],
Chris@0 1403 ],
Chris@0 1404 ];
Chris@0 1405
Chris@0 1406 return $items;
Chris@0 1407 }
Chris@0 1408
Chris@0 1409 /**
Chris@0 1410 * Logs the current user out.
Chris@0 1411 */
Chris@0 1412 function user_logout() {
Chris@0 1413 $user = \Drupal::currentUser();
Chris@0 1414
Chris@0 1415 \Drupal::logger('user')->notice('Session closed for %name.', ['%name' => $user->getAccountName()]);
Chris@0 1416
Chris@0 1417 \Drupal::moduleHandler()->invokeAll('user_logout', [$user]);
Chris@0 1418
Chris@0 1419 // Destroy the current session, and reset $user to the anonymous user.
Chris@0 1420 // Note: In Symfony the session is intended to be destroyed with
Chris@0 1421 // Session::invalidate(). Regrettably this method is currently broken and may
Chris@0 1422 // lead to the creation of spurious session records in the database.
Chris@0 1423 // @see https://github.com/symfony/symfony/issues/12375
Chris@0 1424 \Drupal::service('session_manager')->destroy();
Chris@0 1425 $user->setAccount(new AnonymousUserSession());
Chris@0 1426 }
Chris@0 1427
Chris@0 1428 /**
Chris@0 1429 * Prepares variables for user templates.
Chris@0 1430 *
Chris@0 1431 * Default template: user.html.twig.
Chris@0 1432 *
Chris@0 1433 * @param array $variables
Chris@0 1434 * An associative array containing:
Chris@0 1435 * - elements: An associative array containing the user information and any
Chris@0 1436 * fields attached to the user. Properties used:
Chris@0 1437 * - #user: A \Drupal\user\Entity\User object. The user account of the
Chris@0 1438 * profile being viewed.
Chris@0 1439 * - attributes: HTML attributes for the containing element.
Chris@0 1440 */
Chris@0 1441 function template_preprocess_user(&$variables) {
Chris@0 1442 $variables['user'] = $variables['elements']['#user'];
Chris@0 1443 // Helpful $content variable for templates.
Chris@0 1444 foreach (Element::children($variables['elements']) as $key) {
Chris@0 1445 $variables['content'][$key] = $variables['elements'][$key];
Chris@0 1446 }
Chris@0 1447 }