annotate core/modules/user/user.module @ 19:fa3358dc1485 tip

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