Chris@0: ' . t('About') . '';
Chris@0: $output .= '
' . 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 online documentation for the User module.', [':user_docs' => 'https://www.drupal.org/documentation/modules/user']) . '
';
Chris@0: $output .= '' . t('Uses') . '
';
Chris@0: $output .= '';
Chris@0: $output .= '- ' . t('Creating and managing users') . '
';
Chris@18: $output .= '- ' . t('Through the People administration page 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()]) . '
';
Chris@0: $output .= '- ' . t('Configuring user roles') . '
';
Chris@18: $output .= '- ' . t('Roles are used to group and classify users; each user can be assigned one or more roles. Typically there are two pre-defined roles: Anonymous user (users that are not logged in), and Authenticated user (users that are registered and logged in). Depending on how your site was set up, an Administrator 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 Roles administration page.', [':roles' => Url::fromRoute('entity.user_role.collection')->toString()]) . '
';
Chris@0: $output .= '- ' . t('Setting permissions') . '
';
Chris@18: $output .= '- ' . t('After creating roles, you can set permissions for each role on the Permissions page. 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()]) . '
';
Chris@0: $output .= '- ' . t('Managing account settings') . '
';
Chris@18: $output .= '- ' . t('The Account settings page 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()]) . '
';
Chris@0: $output .= '- ' . t('Managing user account fields') . '
';
Chris@18: $output .= '- ' . t('Because User accounts are an entity type, you can extend them by adding fields through the Manage fields tab on the Account settings page. 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 Field module help page.', [':field_help' => (\Drupal::moduleHandler()->moduleExists('field')) ? Url::fromRoute('help.page', ['name' => 'field'])->toString() : '#', ':accounts' => Url::fromRoute('entity.user.admin_form')->toString()]) . '
';
Chris@0: $output .= '
';
Chris@0: return $output;
Chris@0:
Chris@0: case 'user.admin_create':
Chris@0: return '' . t("This web page allows administrators to register new users. Users' email addresses and usernames must be unique.") . '
';
Chris@0:
Chris@0: case 'user.admin_permissions':
Chris@18: return '' . 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 Roles 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 Account settings 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()]) . '
';
Chris@0:
Chris@0: case 'entity.user_role.collection':
Chris@18: return '' . t('A role defines a group of users that have certain privileges. These privileges are defined on the Permissions page. 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()]) . '
';
Chris@0:
Chris@0: case 'entity.user.field_ui_fields':
Chris@0: return '' . t('This form lets administrators add and edit fields for storing user data.') . '
';
Chris@0:
Chris@0: case 'entity.entity_form_display.user.default':
Chris@0: return '' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '
';
Chris@0:
Chris@0: case 'entity.entity_view_display.user.default':
Chris@0: return '' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '
';
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_theme().
Chris@0: */
Chris@0: function user_theme() {
Chris@0: return [
Chris@0: 'user' => [
Chris@0: 'render element' => 'elements',
Chris@0: ],
Chris@0: 'username' => [
Chris@0: 'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
Chris@0: ],
Chris@0: ];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_js_settings_alter().
Chris@0: */
Chris@0: function user_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
Chris@0: // Provide the user ID in drupalSettings to allow JavaScript code to customize
Chris@0: // the experience for the end user, rather than the server side, which would
Chris@0: // break the render cache.
Chris@0: // Similarly, provide a permissions hash, so that permission-dependent data
Chris@0: // can be reliably cached on the client side.
Chris@0: $user = \Drupal::currentUser();
Chris@0: $settings['user']['uid'] = $user->id();
Chris@0: $settings['user']['permissionsHash'] = \Drupal::service('user_permissions_hash_generator')->generate($user);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Returns whether this site supports the default user picture feature.
Chris@0: *
Chris@0: * This approach preserves compatibility with node/comment templates. Alternate
Chris@0: * user picture implementations (e.g., Gravatar) should provide their own
Chris@0: * add/edit/delete forms and populate the 'picture' variable during the
Chris@0: * preprocess stage.
Chris@0: */
Chris@0: function user_picture_enabled() {
Chris@0: $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
Chris@0: return isset($field_definitions['user_picture']);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_entity_extra_field_info().
Chris@0: */
Chris@0: function user_entity_extra_field_info() {
Chris@0: $fields['user']['user']['form']['account'] = [
Chris@0: 'label' => t('User name and password'),
Chris@0: 'description' => t('User module account form elements.'),
Chris@0: 'weight' => -10,
Chris@0: ];
Chris@0: $fields['user']['user']['form']['language'] = [
Chris@0: 'label' => t('Language settings'),
Chris@0: 'description' => t('User module form element.'),
Chris@0: 'weight' => 0,
Chris@0: ];
Chris@0: if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
Chris@0: $fields['user']['user']['form']['timezone'] = [
Chris@0: 'label' => t('Timezone'),
Chris@0: 'description' => t('System module form element.'),
Chris@0: 'weight' => 6,
Chris@0: ];
Chris@0: }
Chris@0:
Chris@0: $fields['user']['user']['display']['member_for'] = [
Chris@0: 'label' => t('Member for'),
Chris@0: 'description' => t("User module 'member for' view element."),
Chris@0: 'weight' => 5,
Chris@0: ];
Chris@0:
Chris@0: return $fields;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Loads multiple users based on certain conditions.
Chris@0: *
Chris@0: * This function should be used whenever you need to load more than one user
Chris@0: * from the database. Users are loaded into memory and will not require
Chris@0: * database access if loaded again during the same page request.
Chris@0: *
Chris@0: * @param array $uids
Chris@0: * (optional) An array of entity IDs. If omitted, all entities are loaded.
Chris@0: * @param bool $reset
Chris@0: * A boolean indicating that the internal cache should be reset. Use this if
Chris@0: * loading a user object which has been altered during the page request.
Chris@0: *
Chris@0: * @return array
Chris@0: * An array of user objects, indexed by uid.
Chris@0: *
Chris@18: * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use
Chris@18: * \Drupal\user\Entity\User::loadMultiple().
Chris@0: *
Chris@18: * @see https://www.drupal.org/node/2266845
Chris@0: */
Chris@0: function user_load_multiple(array $uids = NULL, $reset = FALSE) {
Chris@18: @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: if ($reset) {
Chris@0: \Drupal::entityManager()->getStorage('user')->resetCache($uids);
Chris@0: }
Chris@0: return User::loadMultiple($uids);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Loads a user object.
Chris@0: *
Chris@0: * @param int $uid
Chris@0: * Integer specifying the user ID to load.
Chris@0: * @param bool $reset
Chris@0: * TRUE to reset the internal cache and load from the database; FALSE
Chris@0: * (default) to load from the internal cache, if set.
Chris@0: *
Chris@0: * @return \Drupal\user\UserInterface
Chris@0: * A fully-loaded user object upon successful user load, or NULL if the user
Chris@0: * cannot be loaded.
Chris@0: *
Chris@18: * @deprecated iin Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use
Chris@18: * Drupal\user\Entity\User::load().
Chris@0: *
Chris@18: * @see https://www.drupal.org/node/2266845
Chris@0: */
Chris@0: function user_load($uid, $reset = FALSE) {
Chris@18: @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: if ($reset) {
Chris@0: \Drupal::entityManager()->getStorage('user')->resetCache([$uid]);
Chris@0: }
Chris@0: return User::load($uid);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Fetches a user object by email address.
Chris@0: *
Chris@0: * @param string $mail
Chris@0: * String with the account's email address.
Chris@0: * @return object|bool
Chris@0: * A fully-loaded $user object upon successful user load or FALSE if user
Chris@0: * cannot be loaded.
Chris@0: *
Chris@0: * @see \Drupal\user\Entity\User::loadMultiple()
Chris@0: */
Chris@0: function user_load_by_mail($mail) {
Chris@0: $users = \Drupal::entityTypeManager()->getStorage('user')
Chris@0: ->loadByProperties(['mail' => $mail]);
Chris@0: return $users ? reset($users) : FALSE;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Fetches a user object by account name.
Chris@0: *
Chris@0: * @param string $name
Chris@0: * String with the account's user name.
Chris@0: * @return object|bool
Chris@0: * A fully-loaded $user object upon successful user load or FALSE if user
Chris@0: * cannot be loaded.
Chris@0: *
Chris@0: * @see \Drupal\user\Entity\User::loadMultiple()
Chris@0: */
Chris@0: function user_load_by_name($name) {
Chris@0: $users = \Drupal::entityTypeManager()->getStorage('user')
Chris@0: ->loadByProperties(['name' => $name]);
Chris@0: return $users ? reset($users) : FALSE;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Verify the syntax of the given name.
Chris@0: *
Chris@0: * @param string $name
Chris@0: * The user name to validate.
Chris@0: *
Chris@0: * @return string|null
Chris@0: * A translated violation message if the name is invalid or NULL if the name
Chris@0: * is valid.
Chris@0: */
Chris@0: function user_validate_name($name) {
Chris@0: $definition = BaseFieldDefinition::create('string')
Chris@0: ->addConstraint('UserName', []);
Chris@0: $data = \Drupal::typedDataManager()->create($definition);
Chris@0: $data->setValue($name);
Chris@0: $violations = $data->validate();
Chris@0: if (count($violations) > 0) {
Chris@0: return $violations[0]->getMessage();
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Generate a random alphanumeric password.
Chris@0: */
Chris@0: function user_password($length = 10) {
Chris@0: // This variable contains the list of allowable characters for the
Chris@0: // password. Note that the number 0 and the letter 'O' have been
Chris@0: // removed to avoid confusion between the two. The same is true
Chris@0: // of 'I', 1, and 'l'.
Chris@0: $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
Chris@0:
Chris@0: // Zero-based count of characters in the allowable list:
Chris@0: $len = strlen($allowable_characters) - 1;
Chris@0:
Chris@0: // Declare the password as a blank string.
Chris@0: $pass = '';
Chris@0:
Chris@0: // Loop the number of times specified by $length.
Chris@0: for ($i = 0; $i < $length; $i++) {
Chris@0: do {
Chris@0: // Find a secure random number within the range needed.
Chris@0: $index = ord(Crypt::randomBytes(1));
Chris@0: } while ($index > $len);
Chris@0:
Chris@0: // Each iteration, pick a random character from the
Chris@0: // allowable string and append it to the password:
Chris@0: $pass .= $allowable_characters[$index];
Chris@0: }
Chris@0:
Chris@0: return $pass;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Determine the permissions for one or more roles.
Chris@0: *
Chris@0: * @param array $roles
Chris@0: * An array of role IDs.
Chris@0: *
Chris@0: * @return array
Chris@0: * An array indexed by role ID. Each value is an array of permission strings
Chris@0: * for the given role.
Chris@0: */
Chris@0: function user_role_permissions(array $roles) {
Chris@0: if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
Chris@0: return _user_role_permissions_update($roles);
Chris@0: }
Chris@0: $entities = Role::loadMultiple($roles);
Chris@0: $role_permissions = [];
Chris@0: foreach ($roles as $rid) {
Chris@0: $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : [];
Chris@0: }
Chris@0: return $role_permissions;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Determine the permissions for one or more roles during update.
Chris@0: *
Chris@0: * A separate version is needed because during update the entity system can't
Chris@0: * be used and in non-update situations the entity system is preferred because
Chris@0: * of the hook system.
Chris@0: *
Chris@0: * @param array $roles
Chris@0: * An array of role IDs.
Chris@0: *
Chris@0: * @return array
Chris@0: * An array indexed by role ID. Each value is an array of permission strings
Chris@0: * for the given role.
Chris@0: */
Chris@0: function _user_role_permissions_update($roles) {
Chris@0: $role_permissions = [];
Chris@0: foreach ($roles as $rid) {
Chris@0: $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: [];
Chris@0: }
Chris@0: return $role_permissions;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Checks for usernames blocked by user administration.
Chris@0: *
Chris@0: * @param string $name
Chris@0: * A string containing a name of the user.
Chris@0: *
Chris@0: * @return bool
Chris@0: * TRUE if the user is blocked, FALSE otherwise.
Chris@0: */
Chris@0: function user_is_blocked($name) {
Chris@0: return (bool) \Drupal::entityQuery('user')
Chris@0: ->condition('name', $name)
Chris@0: ->condition('status', 0)
Chris@0: ->execute();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_ENTITY_TYPE_view() for user entities.
Chris@0: */
Chris@0: function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
Chris@0: if ($display->getComponent('member_for')) {
Chris@0: $build['member_for'] = [
Chris@0: '#type' => 'item',
Chris@0: '#markup' => '' . t('Member for') . '
' . \Drupal::service('date.formatter')->formatTimeDiffSince($account->getCreatedTime()),
Chris@0: ];
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_ENTITY_TYPE_view_alter() for user entities.
Chris@0: *
Chris@0: * This function adds a default alt tag to the user_picture field to maintain
Chris@0: * accessibility.
Chris@0: */
Chris@0: function user_user_view_alter(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
Chris@0: if (user_picture_enabled() && !empty($build['user_picture'])) {
Chris@0: foreach (Element::children($build['user_picture']) as $key) {
Chris@0: $item = $build['user_picture'][$key]['#item'];
Chris@0: if (!$item->get('alt')->getValue()) {
Chris@18: $item->get('alt')->setValue(\Drupal::translation()->translate('Profile picture for user @username', ['@username' => $account->getAccountName()]));
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_preprocess_HOOK() for block templates.
Chris@0: */
Chris@0: function user_preprocess_block(&$variables) {
Chris@0: if ($variables['configuration']['provider'] == 'user') {
Chris@0: switch ($variables['elements']['#plugin_id']) {
Chris@0: case 'user_login_block':
Chris@0: $variables['attributes']['role'] = 'form';
Chris@0: break;
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Format a username.
Chris@0: *
Chris@0: * @param \Drupal\Core\Session\AccountInterface $account
Chris@0: * The account object for the user whose name is to be formatted.
Chris@0: *
Chris@0: * @return string
Chris@0: * An unsanitized string with the username to display.
Chris@0: *
Chris@0: * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
Chris@0: * Use \Drupal\Core\Session\AccountInterface::getDisplayName().
Chris@0: *
Chris@0: * @todo Remove usage in https://www.drupal.org/node/2311219.
Chris@0: */
Chris@0: function user_format_name(AccountInterface $account) {
Chris@0: return $account->getDisplayName();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_template_preprocess_default_variables_alter().
Chris@0: *
Chris@0: * @see user_user_login()
Chris@0: * @see user_user_logout()
Chris@0: */
Chris@0: function user_template_preprocess_default_variables_alter(&$variables) {
Chris@0: $user = \Drupal::currentUser();
Chris@0:
Chris@0: $variables['user'] = clone $user;
Chris@0: // Remove password and session IDs, since themes should not need nor see them.
Chris@0: unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
Chris@0:
Chris@0: $variables['is_admin'] = $user->hasPermission('access administration pages');
Chris@0: $variables['logged_in'] = $user->isAuthenticated();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Prepares variables for username templates.
Chris@0: *
Chris@0: * Default template: username.html.twig.
Chris@0: *
Chris@0: * Modules that make any changes to variables like 'name' or 'extra' must ensure
Chris@0: * that the final string is safe.
Chris@0: *
Chris@0: * @param array $variables
Chris@0: * An associative array containing:
Chris@0: * - account: The user account (\Drupal\Core\Session\AccountInterface).
Chris@0: */
Chris@0: function template_preprocess_username(&$variables) {
Chris@0: $account = $variables['account'] ?: new AnonymousUserSession();
Chris@0:
Chris@0: $variables['extra'] = '';
Chris@0: $variables['uid'] = $account->id();
Chris@0: if (empty($variables['uid'])) {
Chris@0: if (theme_get_setting('features.comment_user_verification')) {
Chris@0: $variables['extra'] = ' (' . t('not verified') . ')';
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: // Set the name to a formatted name that is safe for printing and
Chris@0: // that won't break tables by being too long. Keep an unshortened,
Chris@0: // unsanitized version, in case other preprocess functions want to implement
Chris@0: // their own shortening logic or add markup. If they do so, they must ensure
Chris@0: // that $variables['name'] is safe for printing.
Chris@17: $name = $account->getDisplayName();
Chris@18: $variables['name_raw'] = $account->getAccountName();
Chris@17: if (mb_strlen($name) > 20) {
Chris@0: $name = Unicode::truncate($name, 15, FALSE, TRUE);
Chris@0: $variables['truncated'] = TRUE;
Chris@0: }
Chris@0: else {
Chris@0: $variables['truncated'] = FALSE;
Chris@0: }
Chris@0: $variables['name'] = $name;
Chris@18: if ($account instanceof AccessibleInterface) {
Chris@18: $variables['profile_access'] = $account->access('view');
Chris@18: }
Chris@18: else {
Chris@18: $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
Chris@18: }
Chris@0:
Chris@0: $external = FALSE;
Chris@0: // Populate link path and attributes if appropriate.
Chris@0: if ($variables['uid'] && $variables['profile_access']) {
Chris@0: // We are linking to a local user.
Chris@0: $variables['attributes']['title'] = t('View user profile.');
Chris@0: $variables['link_path'] = 'user/' . $variables['uid'];
Chris@0: }
Chris@0: elseif (!empty($account->homepage)) {
Chris@0: // Like the 'class' attribute, the 'rel' attribute can hold a
Chris@0: // space-separated set of values, so initialize it as an array to make it
Chris@0: // easier for other preprocess functions to append to it.
Chris@0: $variables['attributes']['rel'] = 'nofollow';
Chris@0: $variables['link_path'] = $account->homepage;
Chris@0: $variables['homepage'] = $account->homepage;
Chris@0: $external = TRUE;
Chris@0: }
Chris@0: // We have a link path, so we should generate a URL.
Chris@0: if (isset($variables['link_path'])) {
Chris@0: if ($external) {
Chris@0: $variables['attributes']['href'] = Url::fromUri($variables['link_path'], $variables['link_options'])
Chris@0: ->toString();
Chris@0: }
Chris@0: else {
Chris@0: $variables['attributes']['href'] = Url::fromRoute('entity.user.canonical', [
Chris@0: 'user' => $variables['uid'],
Chris@0: ])->toString();
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Finalizes the login process and logs in a user.
Chris@0: *
Chris@0: * The function logs in the user, records a watchdog message about the new
Chris@0: * session, saves the login timestamp, calls hook_user_login(), and generates a
Chris@0: * new session.
Chris@0: *
Chris@0: * The current user is replaced with the passed in account.
Chris@0: *
Chris@0: * @param \Drupal\user\UserInterface $account
Chris@0: * The account to log in.
Chris@0: *
Chris@0: * @see hook_user_login()
Chris@0: */
Chris@0: function user_login_finalize(UserInterface $account) {
Chris@0: \Drupal::currentUser()->setAccount($account);
Chris@18: \Drupal::logger('user')->notice('Session opened for %name.', ['%name' => $account->getAccountName()]);
Chris@0: // Update the user table timestamp noting user has logged in.
Chris@0: // This is also used to invalidate one-time login links.
Chris@0: $account->setLastLoginTime(REQUEST_TIME);
Chris@0: \Drupal::entityManager()
Chris@0: ->getStorage('user')
Chris@0: ->updateLastLoginTimestamp($account);
Chris@0:
Chris@0: // Regenerate the session ID to prevent against session fixation attacks.
Chris@0: // This is called before hook_user_login() in case one of those functions
Chris@0: // fails or incorrectly does a redirect which would leave the old session
Chris@0: // in place.
Chris@0: \Drupal::service('session')->migrate();
Chris@0: \Drupal::service('session')->set('uid', $account->id());
Chris@0: \Drupal::moduleHandler()->invokeAll('user_login', [$account]);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_user_login().
Chris@0: */
Chris@17: function user_user_login(UserInterface $account) {
Chris@0: // Reset static cache of default variables in template_preprocess() to reflect
Chris@0: // the new user.
Chris@0: drupal_static_reset('template_preprocess');
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_user_logout().
Chris@0: */
Chris@17: function user_user_logout(AccountInterface $account) {
Chris@0: // Reset static cache of default variables in template_preprocess() to reflect
Chris@0: // the new user.
Chris@0: drupal_static_reset('template_preprocess');
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Generates a unique URL for a user to log in and reset their password.
Chris@0: *
Chris@0: * @param \Drupal\user\UserInterface $account
Chris@0: * An object containing the user account.
Chris@0: * @param array $options
Chris@0: * (optional) A keyed array of settings. Supported options are:
Chris@0: * - langcode: A language code to be used when generating locale-sensitive
Chris@0: * URLs. If langcode is NULL the users preferred language is used.
Chris@0: *
Chris@0: * @return string
Chris@0: * A unique URL that provides a one-time log in for the user, from which
Chris@0: * they can change their password.
Chris@0: */
Chris@0: function user_pass_reset_url($account, $options = []) {
Chris@0: $timestamp = REQUEST_TIME;
Chris@0: $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
Chris@18: return Url::fromRoute('user.reset',
Chris@0: [
Chris@0: 'uid' => $account->id(),
Chris@0: 'timestamp' => $timestamp,
Chris@0: 'hash' => user_pass_rehash($account, $timestamp),
Chris@0: ],
Chris@0: [
Chris@0: 'absolute' => TRUE,
Chris@17: 'language' => \Drupal::languageManager()->getLanguage($langcode),
Chris@0: ]
Chris@18: )->toString();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Generates a URL to confirm an account cancellation request.
Chris@0: *
Chris@0: * @param \Drupal\user\UserInterface $account
Chris@0: * The user account object.
Chris@0: * @param array $options
Chris@0: * (optional) A keyed array of settings. Supported options are:
Chris@0: * - langcode: A language code to be used when generating locale-sensitive
Chris@0: * URLs. If langcode is NULL the users preferred language is used.
Chris@0: *
Chris@0: * @return string
Chris@0: * A unique URL that may be used to confirm the cancellation of the user
Chris@0: * account.
Chris@0: *
Chris@0: * @see user_mail_tokens()
Chris@0: * @see \Drupal\user\Controller\UserController::confirmCancel()
Chris@0: */
Chris@0: function user_cancel_url(UserInterface $account, $options = []) {
Chris@0: $timestamp = REQUEST_TIME;
Chris@0: $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
Chris@0: $url_options = ['absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode)];
Chris@18: return Url::fromRoute('user.cancel_confirm', [
Chris@0: 'user' => $account->id(),
Chris@0: 'timestamp' => $timestamp,
Chris@17: 'hashed_pass' => user_pass_rehash($account, $timestamp),
Chris@18: ], $url_options)->toString();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Creates a unique hash value for use in time-dependent per-user URLs.
Chris@0: *
Chris@0: * This hash is normally used to build a unique and secure URL that is sent to
Chris@0: * the user by email for purposes such as resetting the user's password. In
Chris@0: * order to validate the URL, the same hash can be generated again, from the
Chris@0: * same information, and compared to the hash value from the URL. The hash
Chris@0: * contains the time stamp, the user's last login time, the numeric user ID,
Chris@0: * and the user's email address.
Chris@0: * For a usage example, see user_cancel_url() and
Chris@0: * \Drupal\user\Controller\UserController::confirmCancel().
Chris@0: *
Chris@0: * @param \Drupal\user\UserInterface $account
Chris@0: * An object containing the user account.
Chris@0: * @param int $timestamp
Chris@0: * A UNIX timestamp, typically REQUEST_TIME.
Chris@0: *
Chris@0: * @return string
Chris@0: * A string that is safe for use in URLs and SQL statements.
Chris@0: */
Chris@0: function user_pass_rehash(UserInterface $account, $timestamp) {
Chris@0: $data = $timestamp;
Chris@0: $data .= $account->getLastLoginTime();
Chris@0: $data .= $account->id();
Chris@0: $data .= $account->getEmail();
Chris@0: return Crypt::hmacBase64($data, Settings::getHashSalt() . $account->getPassword());
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Cancel a user account.
Chris@0: *
Chris@0: * Since the user cancellation process needs to be run in a batch, either
Chris@0: * Form API will invoke it, or batch_process() needs to be invoked after calling
Chris@0: * this function and should define the path to redirect to.
Chris@0: *
Chris@0: * @param array $edit
Chris@0: * An array of submitted form values.
Chris@0: * @param int $uid
Chris@0: * The user ID of the user account to cancel.
Chris@0: * @param string $method
Chris@0: * The account cancellation method to use.
Chris@0: *
Chris@0: * @see _user_cancel()
Chris@0: */
Chris@0: function user_cancel($edit, $uid, $method) {
Chris@0: $account = User::load($uid);
Chris@0:
Chris@0: if (!$account) {
Chris@17: \Drupal::messenger()->addError(t('The user account %id does not exist.', ['%id' => $uid]));
Chris@0: \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
Chris@0: return;
Chris@0: }
Chris@0:
Chris@0: // Initialize batch (to set title).
Chris@0: $batch = [
Chris@0: 'title' => t('Cancelling account'),
Chris@0: 'operations' => [],
Chris@0: ];
Chris@0: batch_set($batch);
Chris@0:
Chris@0: // When the 'user_cancel_delete' method is used, user_delete() is called,
Chris@0: // which invokes hook_ENTITY_TYPE_predelete() and hook_ENTITY_TYPE_delete()
Chris@0: // for the user entity. Modules should use those hooks to respond to the
Chris@0: // account deletion.
Chris@0: if ($method != 'user_cancel_delete') {
Chris@0: // Allow modules to add further sets to this batch.
Chris@0: \Drupal::moduleHandler()->invokeAll('user_cancel', [$edit, $account, $method]);
Chris@0: }
Chris@0:
Chris@0: // Finish the batch and actually cancel the account.
Chris@0: $batch = [
Chris@0: 'title' => t('Cancelling user account'),
Chris@0: 'operations' => [
Chris@0: ['_user_cancel', [$edit, $account, $method]],
Chris@0: ],
Chris@0: ];
Chris@0:
Chris@0: // After cancelling account, ensure that user is logged out.
Chris@0: if ($account->id() == \Drupal::currentUser()->id()) {
Chris@0: // Batch API stores data in the session, so use the finished operation to
Chris@0: // manipulate the current user's session id.
Chris@0: $batch['finished'] = '_user_cancel_session_regenerate';
Chris@0: }
Chris@0:
Chris@0: batch_set($batch);
Chris@0:
Chris@0: // Batch processing is either handled via Form API or has to be invoked
Chris@0: // manually.
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements callback_batch_operation().
Chris@0: *
Chris@0: * Last step for cancelling a user account.
Chris@0: *
Chris@0: * Since batch and session API require a valid user account, the actual
Chris@0: * cancellation of a user account needs to happen last.
Chris@0: * @param array $edit
Chris@0: * An array of submitted form values.
Chris@0: * @param \Drupal\user\UserInterface $account
Chris@0: * The user ID of the user account to cancel.
Chris@0: * @param string $method
Chris@0: * The account cancellation method to use.
Chris@0: *
Chris@0: * @see user_cancel()
Chris@0: */
Chris@0: function _user_cancel($edit, $account, $method) {
Chris@0: $logger = \Drupal::logger('user');
Chris@0:
Chris@0: switch ($method) {
Chris@0: case 'user_cancel_block':
Chris@0: case 'user_cancel_block_unpublish':
Chris@0: default:
Chris@0: // Send account blocked notification if option was checked.
Chris@0: if (!empty($edit['user_cancel_notify'])) {
Chris@0: _user_mail_notify('status_blocked', $account);
Chris@0: }
Chris@0: $account->block();
Chris@0: $account->save();
Chris@17: \Drupal::messenger()->addStatus(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
Chris@0: $logger->notice('Blocked user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
Chris@0: break;
Chris@0:
Chris@0: case 'user_cancel_reassign':
Chris@0: case 'user_cancel_delete':
Chris@0: // Send account canceled notification if option was checked.
Chris@0: if (!empty($edit['user_cancel_notify'])) {
Chris@0: _user_mail_notify('status_canceled', $account);
Chris@0: }
Chris@0: $account->delete();
Chris@17: \Drupal::messenger()->addStatus(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
Chris@0: $logger->notice('Deleted user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
Chris@0: break;
Chris@0: }
Chris@0:
Chris@0: // After cancelling account, ensure that user is logged out. We can't destroy
Chris@0: // their session though, as we might have information in it, and we can't
Chris@0: // regenerate it because batch API uses the session ID, we will regenerate it
Chris@0: // in _user_cancel_session_regenerate().
Chris@0: if ($account->id() == \Drupal::currentUser()->id()) {
Chris@0: \Drupal::currentUser()->setAccount(new AnonymousUserSession());
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements callback_batch_finished().
Chris@0: *
Chris@0: * Finished batch processing callback for cancelling a user account.
Chris@0: *
Chris@0: * @see user_cancel()
Chris@0: */
Chris@0: function _user_cancel_session_regenerate() {
Chris@0: // Regenerate the users session instead of calling session_destroy() as we
Chris@0: // want to preserve any messages that might have been set.
Chris@0: \Drupal::service('session')->migrate();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Helper function to return available account cancellation methods.
Chris@0: *
Chris@0: * See documentation of hook_user_cancel_methods_alter().
Chris@0: *
Chris@0: * @return array
Chris@0: * An array containing all account cancellation methods as form elements.
Chris@0: *
Chris@0: * @see hook_user_cancel_methods_alter()
Chris@0: * @see user_admin_settings()
Chris@0: */
Chris@0: function user_cancel_methods() {
Chris@0: $user_settings = \Drupal::config('user.settings');
Chris@0: $anonymous_name = $user_settings->get('anonymous');
Chris@0: $methods = [
Chris@0: 'user_cancel_block' => [
Chris@0: 'title' => t('Disable the account and keep its content.'),
Chris@0: '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: ],
Chris@0: 'user_cancel_block_unpublish' => [
Chris@0: 'title' => t('Disable the account and unpublish its content.'),
Chris@0: '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: ],
Chris@0: 'user_cancel_reassign' => [
Chris@0: 'title' => t('Delete the account and make its content belong to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
Chris@0: '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: ],
Chris@0: 'user_cancel_delete' => [
Chris@0: 'title' => t('Delete the account and its content.'),
Chris@0: 'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
Chris@0: 'access' => \Drupal::currentUser()->hasPermission('administer users'),
Chris@0: ],
Chris@0: ];
Chris@0: // Allow modules to customize account cancellation methods.
Chris@0: \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
Chris@0:
Chris@0: // Turn all methods into real form elements.
Chris@0: $form = [
Chris@0: '#options' => [],
Chris@0: '#default_value' => $user_settings->get('cancel_method'),
Chris@0: ];
Chris@0: foreach ($methods as $name => $method) {
Chris@0: $form['#options'][$name] = $method['title'];
Chris@0: // Add the description for the confirmation form. This description is never
Chris@0: // shown for the cancel method option, only on the confirmation form.
Chris@0: // Therefore, we use a custom #confirm_description property.
Chris@0: if (isset($method['description'])) {
Chris@0: $form[$name]['#confirm_description'] = $method['description'];
Chris@0: }
Chris@0: if (isset($method['access'])) {
Chris@0: $form[$name]['#access'] = $method['access'];
Chris@0: }
Chris@0: }
Chris@0: return $form;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Delete a user.
Chris@0: *
Chris@0: * @param int $uid
Chris@0: * A user ID.
Chris@0: */
Chris@0: function user_delete($uid) {
Chris@0: user_delete_multiple([$uid]);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Delete multiple user accounts.
Chris@0: *
Chris@0: * @param int[] $uids
Chris@0: * An array of user IDs.
Chris@0: *
Chris@0: * @see hook_ENTITY_TYPE_predelete()
Chris@0: * @see hook_ENTITY_TYPE_delete()
Chris@0: */
Chris@0: function user_delete_multiple(array $uids) {
Chris@0: entity_delete_multiple('user', $uids);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Generate an array for rendering the given user.
Chris@0: *
Chris@0: * When viewing a user profile, the $page array contains:
Chris@0: *
Chris@0: * - $page['content']['member_for']:
Chris@0: * Contains the default "Member for" profile data for a user.
Chris@0: * - $page['content']['#user']:
Chris@0: * The user account of the profile being viewed.
Chris@0: *
Chris@0: * To theme user profiles, copy core/modules/user/templates/user.html.twig
Chris@0: * to your theme directory, and edit it as instructed in that file's comments.
Chris@0: *
Chris@0: * @param \Drupal\user\UserInterface $account
Chris@0: * A user object.
Chris@0: * @param string $view_mode
Chris@0: * View mode, e.g. 'full'.
Chris@0: * @param string|null $langcode
Chris@0: * (optional) A language code to use for rendering. Defaults to the global
Chris@0: * content language of the current request.
Chris@0: *
Chris@0: * @return array
Chris@16: * An array as expected by \Drupal\Core\Render\RendererInterface::render().
Chris@0: */
Chris@0: function user_view($account, $view_mode = 'full', $langcode = NULL) {
Chris@0: return entity_view($account, $view_mode, $langcode);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Constructs a drupal_render() style array from an array of loaded users.
Chris@0: *
Chris@0: * @param \Drupal\user\UserInterface[] $accounts
Chris@0: * An array of user accounts as returned by User::loadMultiple().
Chris@0: * @param string $view_mode
Chris@0: * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
Chris@0: * @param string|null $langcode
Chris@0: * (optional) A language code to use for rendering. Defaults to the global
Chris@0: * content language of the current request.
Chris@0: *
Chris@0: * @return array
Chris@16: * An array in the format expected by
Chris@16: * \Drupal\Core\Render\RendererInterface::render().
Chris@0: */
Chris@0: function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
Chris@0: return entity_view_multiple($accounts, $view_mode, $langcode);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_mail().
Chris@0: */
Chris@0: function user_mail($key, &$message, $params) {
Chris@0: $token_service = \Drupal::token();
Chris@0: $language_manager = \Drupal::languageManager();
Chris@0: $langcode = $message['langcode'];
Chris@0: $variables = ['user' => $params['account']];
Chris@0:
Chris@0: $language = $language_manager->getLanguage($params['account']->getPreferredLangcode());
Chris@0: $original_language = $language_manager->getConfigOverrideLanguage();
Chris@0: $language_manager->setConfigOverrideLanguage($language);
Chris@0: $mail_config = \Drupal::config('user.mail');
Chris@0:
Chris@0: $token_options = ['langcode' => $langcode, 'callback' => 'user_mail_tokens', 'clear' => TRUE];
Chris@0: $message['subject'] .= PlainTextOutput::renderFromHtml($token_service->replace($mail_config->get($key . '.subject'), $variables, $token_options));
Chris@0: $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);
Chris@0:
Chris@0: $language_manager->setConfigOverrideLanguage($original_language);
Chris@0:
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Token callback to add unsafe tokens for user mails.
Chris@0: *
Chris@0: * This function is used by \Drupal\Core\Utility\Token::replace() to set up
Chris@0: * some additional tokens that can be used in email messages generated by
Chris@0: * user_mail().
Chris@0: *
Chris@0: * @param array $replacements
Chris@0: * An associative array variable containing mappings from token names to
Chris@0: * values (for use with strtr()).
Chris@0: * @param array $data
Chris@0: * An associative array of token replacement values. If the 'user' element
Chris@0: * exists, it must contain a user account object with the following
Chris@0: * properties:
Chris@0: * - login: The UNIX timestamp of the user's last login.
Chris@0: * - pass: The hashed account login password.
Chris@0: * @param array $options
Chris@0: * A keyed array of settings and flags to control the token replacement
Chris@0: * process. See \Drupal\Core\Utility\Token::replace().
Chris@0: */
Chris@0: function user_mail_tokens(&$replacements, $data, $options) {
Chris@0: if (isset($data['user'])) {
Chris@0: $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
Chris@0: $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Retrieves the names of roles matching specified conditions.
Chris@0: *
Chris@0: * @param bool $membersonly
Chris@0: * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
Chris@0: * FALSE.
Chris@0: * @param string|null $permission
Chris@0: * (optional) A string containing a permission. If set, only roles
Chris@0: * containing that permission are returned. Defaults to NULL, which
Chris@0: * returns all roles.
Chris@0: *
Chris@0: * @return array
Chris@0: * An associative array with the role id as the key and the role name as
Chris@0: * value.
Chris@0: */
Chris@0: function user_role_names($membersonly = FALSE, $permission = NULL) {
Chris@0: return array_map(function ($item) {
Chris@0: return $item->label();
Chris@0: }, user_roles($membersonly, $permission));
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_ENTITY_TYPE_insert() for user_role entities.
Chris@0: */
Chris@0: function user_user_role_insert(RoleInterface $role) {
Chris@0: // Ignore the authenticated and anonymous roles or the role is being synced.
Chris@0: if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
Chris@0: return;
Chris@0: }
Chris@0:
Chris@0: $add_id = 'user_add_role_action.' . $role->id();
Chris@0: if (!Action::load($add_id)) {
Chris@0: $action = Action::create([
Chris@0: 'id' => $add_id,
Chris@0: 'type' => 'user',
Chris@0: 'label' => t('Add the @label role to the selected user(s)', ['@label' => $role->label()]),
Chris@0: 'configuration' => [
Chris@0: 'rid' => $role->id(),
Chris@0: ],
Chris@0: 'plugin' => 'user_add_role_action',
Chris@0: ]);
Chris@0: $action->trustData()->save();
Chris@0: }
Chris@0: $remove_id = 'user_remove_role_action.' . $role->id();
Chris@0: if (!Action::load($remove_id)) {
Chris@0: $action = Action::create([
Chris@0: 'id' => $remove_id,
Chris@0: 'type' => 'user',
Chris@0: 'label' => t('Remove the @label role from the selected user(s)', ['@label' => $role->label()]),
Chris@0: 'configuration' => [
Chris@0: 'rid' => $role->id(),
Chris@0: ],
Chris@0: 'plugin' => 'user_remove_role_action',
Chris@0: ]);
Chris@0: $action->trustData()->save();
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_ENTITY_TYPE_delete() for user_role entities.
Chris@0: */
Chris@0: function user_user_role_delete(RoleInterface $role) {
Chris@0: // Delete role references for all users.
Chris@0: $user_storage = \Drupal::entityManager()->getStorage('user');
Chris@0: $user_storage->deleteRoleReferences([$role->id()]);
Chris@0:
Chris@0: // Ignore the authenticated and anonymous roles or the role is being synced.
Chris@0: if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
Chris@0: return;
Chris@0: }
Chris@0:
Chris@0: $actions = Action::loadMultiple([
Chris@0: 'user_add_role_action.' . $role->id(),
Chris@0: 'user_remove_role_action.' . $role->id(),
Chris@0: ]);
Chris@0: foreach ($actions as $action) {
Chris@0: $action->delete();
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Retrieve an array of roles matching specified conditions.
Chris@0: *
Chris@0: * @param bool $membersonly
Chris@0: * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
Chris@0: * FALSE.
Chris@0: * @param string|null $permission
Chris@0: * (optional) A string containing a permission. If set, only roles
Chris@0: * containing that permission are returned. Defaults to NULL, which
Chris@0: * returns all roles.
Chris@0: *
Chris@0: * @return \Drupal\user\RoleInterface[]
Chris@0: * An associative array with the role id as the key and the role object as
Chris@0: * value.
Chris@0: */
Chris@0: function user_roles($membersonly = FALSE, $permission = NULL) {
Chris@0: $roles = Role::loadMultiple();
Chris@0: if ($membersonly) {
Chris@0: unset($roles[RoleInterface::ANONYMOUS_ID]);
Chris@0: }
Chris@0:
Chris@0: if (!empty($permission)) {
Chris@0: $roles = array_filter($roles, function ($role) use ($permission) {
Chris@0: return $role->hasPermission($permission);
Chris@0: });
Chris@0: }
Chris@0:
Chris@0: return $roles;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Fetches a user role by role ID.
Chris@0: *
Chris@0: * @param string $rid
Chris@0: * A string representing the role ID.
Chris@0: *
Chris@0: * @return \Drupal\user\RoleInterface|null
Chris@0: * A fully-loaded role object if a role with the given ID exists, or NULL
Chris@0: * otherwise.
Chris@0: *
Chris@0: * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
Chris@0: * Use \Drupal\user\Entity\Role::load().
Chris@0: */
Chris@0: function user_role_load($rid) {
Chris@0: return Role::load($rid);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Change permissions for a user role.
Chris@0: *
Chris@0: * This function may be used to grant and revoke multiple permissions at once.
Chris@0: * For example, when a form exposes checkboxes to configure permissions for a
Chris@0: * role, the form submit handler may directly pass the submitted values for the
Chris@0: * checkboxes form element to this function.
Chris@0: *
Chris@0: * @param mixed $rid
Chris@0: * The ID of a user role to alter.
Chris@0: * @param array $permissions
Chris@0: * (optional) An associative array, where the key holds the permission name
Chris@0: * and the value determines whether to grant or revoke that permission. Any
Chris@0: * value that evaluates to TRUE will cause the permission to be granted.
Chris@0: * Any value that evaluates to FALSE will cause the permission to be
Chris@0: * revoked.
Chris@0: * @code
Chris@0: * array(
Chris@0: * 'administer nodes' => 0, // Revoke 'administer nodes'
Chris@0: * 'administer blocks' => FALSE, // Revoke 'administer blocks'
Chris@0: * 'access user profiles' => 1, // Grant 'access user profiles'
Chris@0: * 'access content' => TRUE, // Grant 'access content'
Chris@0: * 'access comments' => 'access comments', // Grant 'access comments'
Chris@0: * )
Chris@0: * @endcode
Chris@0: * Existing permissions are not changed, unless specified in $permissions.
Chris@0: *
Chris@0: * @see user_role_grant_permissions()
Chris@0: * @see user_role_revoke_permissions()
Chris@0: */
Chris@0: function user_role_change_permissions($rid, array $permissions = []) {
Chris@0: // Grant new permissions for the role.
Chris@0: $grant = array_filter($permissions);
Chris@0: if (!empty($grant)) {
Chris@0: user_role_grant_permissions($rid, array_keys($grant));
Chris@0: }
Chris@0: // Revoke permissions for the role.
Chris@0: $revoke = array_diff_assoc($permissions, $grant);
Chris@0: if (!empty($revoke)) {
Chris@0: user_role_revoke_permissions($rid, array_keys($revoke));
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Grant permissions to a user role.
Chris@0: *
Chris@0: * @param mixed $rid
Chris@0: * The ID of a user role to alter.
Chris@0: * @param array $permissions
Chris@0: * (optional) A list of permission names to grant.
Chris@0: *
Chris@0: * @see user_role_change_permissions()
Chris@0: * @see user_role_revoke_permissions()
Chris@0: */
Chris@0: function user_role_grant_permissions($rid, array $permissions = []) {
Chris@0: // Grant new permissions for the role.
Chris@0: if ($role = Role::load($rid)) {
Chris@0: foreach ($permissions as $permission) {
Chris@0: $role->grantPermission($permission);
Chris@0: }
Chris@0: $role->trustData()->save();
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Revoke permissions from a user role.
Chris@0: *
Chris@0: * @param mixed $rid
Chris@0: * The ID of a user role to alter.
Chris@0: * @param array $permissions
Chris@0: * (optional) A list of permission names to revoke.
Chris@0: *
Chris@0: * @see user_role_change_permissions()
Chris@0: * @see user_role_grant_permissions()
Chris@0: */
Chris@0: function user_role_revoke_permissions($rid, array $permissions = []) {
Chris@0: // Revoke permissions for the role.
Chris@0: $role = Role::load($rid);
Chris@0: foreach ($permissions as $permission) {
Chris@0: $role->revokePermission($permission);
Chris@0: }
Chris@0: $role->trustData()->save();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Conditionally create and send a notification email when a certain
Chris@0: * operation happens on the given user account.
Chris@0: *
Chris@0: * @param string $op
Chris@0: * The operation being performed on the account. Possible values:
Chris@0: * - 'register_admin_created': Welcome message for user created by the admin.
Chris@0: * - 'register_no_approval_required': Welcome message when user
Chris@0: * self-registers.
Chris@0: * - 'register_pending_approval': Welcome message, user pending admin
Chris@0: * approval.
Chris@0: * - 'password_reset': Password recovery request.
Chris@0: * - 'status_activated': Account activated.
Chris@0: * - 'status_blocked': Account blocked.
Chris@0: * - 'cancel_confirm': Account cancellation request.
Chris@0: * - 'status_canceled': Account canceled.
Chris@0: *
Chris@0: * @param \Drupal\Core\Session\AccountInterface $account
Chris@0: * The user object of the account being notified. Must contain at
Chris@0: * least the fields 'uid', 'name', and 'mail'.
Chris@0: * @param string $langcode
Chris@0: * (optional) Language code to use for the notification, overriding account
Chris@0: * language.
Chris@0: *
Chris@0: * @return array
Chris@0: * An array containing various information about the message.
Chris@0: * See \Drupal\Core\Mail\MailManagerInterface::mail() for details.
Chris@0: *
Chris@0: * @see user_mail_tokens()
Chris@0: */
Chris@0: function _user_mail_notify($op, $account, $langcode = NULL) {
Chris@0: if (\Drupal::config('user.settings')->get('notify.' . $op)) {
Chris@0: $params['account'] = $account;
Chris@0: $langcode = $langcode ? $langcode : $account->getPreferredLangcode();
Chris@0: // Get the custom site notification email to use as the from email address
Chris@0: // if it has been set.
Chris@0: $site_mail = \Drupal::config('system.site')->get('mail_notification');
Chris@0: // If the custom site notification email has not been set, we use the site
Chris@0: // default for this.
Chris@0: if (empty($site_mail)) {
Chris@0: $site_mail = \Drupal::config('system.site')->get('mail');
Chris@0: }
Chris@0: if (empty($site_mail)) {
Chris@0: $site_mail = ini_get('sendmail_from');
Chris@0: }
Chris@0: $mail = \Drupal::service('plugin.manager.mail')->mail('user', $op, $account->getEmail(), $langcode, $params, $site_mail);
Chris@0: if ($op == 'register_pending_approval') {
Chris@0: // If a user registered requiring admin approval, notify the admin, too.
Chris@0: // We use the site default language for this.
Chris@0: \Drupal::service('plugin.manager.mail')->mail('user', 'register_pending_approval_admin', $site_mail, \Drupal::languageManager()->getDefaultLanguage()->getId(), $params);
Chris@0: }
Chris@0: }
Chris@0: return empty($mail) ? NULL : $mail['result'];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_element_info_alter().
Chris@0: */
Chris@0: function user_element_info_alter(array &$types) {
Chris@0: if (isset($types['password_confirm'])) {
Chris@0: $types['password_confirm']['#process'][] = 'user_form_process_password_confirm';
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Form element process handler for client-side password validation.
Chris@0: *
Chris@0: * This #process handler is automatically invoked for 'password_confirm' form
Chris@0: * elements to add the JavaScript and string translations for dynamic password
Chris@0: * validation.
Chris@0: */
Chris@0: function user_form_process_password_confirm($element) {
Chris@0: $password_settings = [
Chris@0: 'confirmTitle' => t('Passwords match:'),
Chris@0: 'confirmSuccess' => t('yes'),
Chris@0: 'confirmFailure' => t('no'),
Chris@0: 'showStrengthIndicator' => FALSE,
Chris@0: ];
Chris@0:
Chris@0: if (\Drupal::config('user.settings')->get('password_strength')) {
Chris@0: $password_settings['showStrengthIndicator'] = TRUE;
Chris@0: $password_settings += [
Chris@0: 'strengthTitle' => t('Password strength:'),
Chris@0: 'hasWeaknesses' => t('Recommendations to make your password stronger:'),
Chris@0: 'tooShort' => t('Make it at least 12 characters'),
Chris@0: 'addLowerCase' => t('Add lowercase letters'),
Chris@0: 'addUpperCase' => t('Add uppercase letters'),
Chris@0: 'addNumbers' => t('Add numbers'),
Chris@0: 'addPunctuation' => t('Add punctuation'),
Chris@0: 'sameAsUsername' => t('Make it different from your username'),
Chris@0: 'weak' => t('Weak'),
Chris@0: 'fair' => t('Fair'),
Chris@0: 'good' => t('Good'),
Chris@0: 'strong' => t('Strong'),
Chris@18: 'username' => \Drupal::currentUser()->getAccountName(),
Chris@0: ];
Chris@0: }
Chris@0:
Chris@0: $element['#attached']['library'][] = 'user/drupal.user';
Chris@0: $element['#attached']['drupalSettings']['password'] = $password_settings;
Chris@0:
Chris@0: return $element;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_modules_uninstalled().
Chris@0: */
Chris@0: function user_modules_uninstalled($modules) {
Chris@0: // Remove any potentially orphan module data stored for users.
Chris@0: \Drupal::service('user.data')->delete($modules);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Saves visitor information as a cookie so it can be reused.
Chris@0: *
Chris@0: * @param array $values
Chris@0: * An array of key/value pairs to be saved into a cookie.
Chris@0: */
Chris@0: function user_cookie_save(array $values) {
Chris@0: foreach ($values as $field => $value) {
Chris@0: // Set cookie for 365 days.
Chris@0: setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Delete a visitor information cookie.
Chris@0: *
Chris@0: * @param string $cookie_name
Chris@0: * A cookie name such as 'homepage'.
Chris@0: */
Chris@0: function user_cookie_delete($cookie_name) {
Chris@0: setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Implements hook_toolbar().
Chris@0: */
Chris@0: function user_toolbar() {
Chris@0: $user = \Drupal::currentUser();
Chris@0:
Chris@0: $items['user'] = [
Chris@0: '#type' => 'toolbar_item',
Chris@0: 'tab' => [
Chris@0: '#type' => 'link',
Chris@0: '#title' => $user->getDisplayName(),
Chris@0: '#url' => Url::fromRoute('user.page'),
Chris@0: '#attributes' => [
Chris@0: 'title' => t('My account'),
Chris@0: 'class' => ['toolbar-icon', 'toolbar-icon-user'],
Chris@0: ],
Chris@0: '#cache' => [
Chris@14: // Vary cache for anonymous and authenticated users.
Chris@14: 'contexts' => ['user.roles:anonymous'],
Chris@0: ],
Chris@0: ],
Chris@0: 'tray' => [
Chris@0: '#heading' => t('User account actions'),
Chris@0: ],
Chris@0: '#weight' => 100,
Chris@0: '#attached' => [
Chris@0: 'library' => [
Chris@0: 'user/drupal.user.icons',
Chris@0: ],
Chris@0: ],
Chris@0: ];
Chris@0:
Chris@14: if ($user->isAnonymous()) {
Chris@14: $links = [
Chris@14: 'login' => [
Chris@14: 'title' => t('Log in'),
Chris@14: 'url' => Url::fromRoute('user.page'),
Chris@14: ],
Chris@14: ];
Chris@14: $items['user']['tray']['user_links'] = [
Chris@14: '#theme' => 'links__toolbar_user',
Chris@14: '#links' => $links,
Chris@14: '#attributes' => [
Chris@14: 'class' => ['toolbar-menu'],
Chris@14: ],
Chris@14: ];
Chris@14: }
Chris@14: else {
Chris@14: $items['user']['tab']['#title'] = [
Chris@14: '#lazy_builder' => ['user.toolbar_link_builder:renderDisplayName', []],
Chris@14: '#create_placeholder' => TRUE,
Chris@14: ];
Chris@14: $items['user']['tray']['user_links'] = [
Chris@14: '#lazy_builder' => ['user.toolbar_link_builder:renderToolbarLinks', []],
Chris@14: '#create_placeholder' => TRUE,
Chris@14: ];
Chris@14: }
Chris@14:
Chris@0: return $items;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Logs the current user out.
Chris@0: */
Chris@0: function user_logout() {
Chris@0: $user = \Drupal::currentUser();
Chris@0:
Chris@0: \Drupal::logger('user')->notice('Session closed for %name.', ['%name' => $user->getAccountName()]);
Chris@0:
Chris@0: \Drupal::moduleHandler()->invokeAll('user_logout', [$user]);
Chris@0:
Chris@0: // Destroy the current session, and reset $user to the anonymous user.
Chris@0: // Note: In Symfony the session is intended to be destroyed with
Chris@0: // Session::invalidate(). Regrettably this method is currently broken and may
Chris@0: // lead to the creation of spurious session records in the database.
Chris@0: // @see https://github.com/symfony/symfony/issues/12375
Chris@0: \Drupal::service('session_manager')->destroy();
Chris@0: $user->setAccount(new AnonymousUserSession());
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Prepares variables for user templates.
Chris@0: *
Chris@0: * Default template: user.html.twig.
Chris@0: *
Chris@0: * @param array $variables
Chris@0: * An associative array containing:
Chris@0: * - elements: An associative array containing the user information and any
Chris@0: * fields attached to the user. Properties used:
Chris@0: * - #user: A \Drupal\user\Entity\User object. The user account of the
Chris@0: * profile being viewed.
Chris@0: * - attributes: HTML attributes for the containing element.
Chris@0: */
Chris@0: function template_preprocess_user(&$variables) {
Chris@0: $variables['user'] = $variables['elements']['#user'];
Chris@0: // Helpful $content variable for templates.
Chris@0: foreach (Element::children($variables['elements']) as $key) {
Chris@0: $variables['content'][$key] = $variables['elements'][$key];
Chris@0: }
Chris@0: }