UserSelection.php 7.35 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\user\Plugin\EntityReferenceSelection\UserSelection.
6 7
 */

8
namespace Drupal\user\Plugin\EntityReferenceSelection;
9

10
use Drupal\Core\Database\Connection;
11
use Drupal\Core\Database\Query\SelectInterface;
12
use Drupal\Core\Entity\EntityManagerInterface;
13
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
14 15 16
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
17
use Drupal\user\RoleInterface;
18
use Symfony\Component\DependencyInjection\ContainerInterface;
19 20 21 22

/**
 * Provides specific access control for the user entity type.
 *
23
 * @EntityReferenceSelection(
24
 *   id = "default:user",
25 26 27 28 29 30
 *   label = @Translation("User selection"),
 *   entity_types = {"user"},
 *   group = "default",
 *   weight = 1
 * )
 */
31
class UserSelection extends DefaultSelection {
32

33 34 35 36 37 38 39
  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

40 41 42 43 44 45 46
  /**
   * The user storage.
   *
   * @var \Drupal\user\UserStorageInterface
   */
  protected $userStorage;

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  /**
   * Constructs a new UserSelection object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, Connection $connection) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_manager, $module_handler, $current_user);

    $this->connection = $connection;
69
    $this->userStorage = $entity_manager->getStorage('user');
70 71
  }

72
  /**
73
   * {@inheritdoc}
74
   */
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity.manager'),
      $container->get('module_handler'),
      $container->get('current_user'),
      $container->get('database')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $selection_handler_settings = $this->configuration['handler_settings'];
92

93
    // Merge in default values.
94
    $selection_handler_settings += array(
95 96 97
      'filter' => array(
        'type' => '_none',
      ),
98 99 100 101 102 103 104
      'include_anonymous' => TRUE,
    );

    $form['include_anonymous'] = array(
      '#type' => 'checkbox',
      '#title' => $this->t('Include the anonymous user.'),
      '#default_value' => $selection_handler_settings['include_anonymous'],
105 106 107 108 109
    );

    // Add user specific filter options.
    $form['filter']['type'] = array(
      '#type' => 'select',
110
      '#title' => $this->t('Filter by'),
111
      '#options' => array(
112 113
        '_none' => $this->t('- None -'),
        'role' => $this->t('User role'),
114 115 116
      ),
      '#ajax' => TRUE,
      '#limit_validation_errors' => array(),
117
      '#default_value' => $selection_handler_settings['filter']['type'],
118 119 120 121 122 123 124 125
    );

    $form['filter']['settings'] = array(
      '#type' => 'container',
      '#attributes' => array('class' => array('entity_reference-settings')),
      '#process' => array('_entity_reference_form_process_merge_parent'),
    );

126
    if ($selection_handler_settings['filter']['type'] == 'role') {
127
      // Merge in default values.
128
      $selection_handler_settings['filter'] += array(
129 130 131 132 133
        'role' => NULL,
      );

      $form['filter']['settings']['role'] = array(
        '#type' => 'checkboxes',
134
        '#title' => $this->t('Restrict to the selected roles'),
135
        '#required' => TRUE,
136
        '#options' => array_diff_key(user_role_names(TRUE), array(RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID)),
137
        '#default_value' => $selection_handler_settings['filter']['role'],
138 139 140
      );
    }

141
    $form += parent::buildConfigurationForm($form, $form_state);
142

143 144 145 146
    return $form;
  }

  /**
147
   * {@inheritdoc}
148
   */
149
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
150 151 152 153 154 155 156
    $query = parent::buildEntityQuery($match, $match_operator);

    // The user entity doesn't have a label column.
    if (isset($match)) {
      $query->condition('name', $match, $match_operator);
    }

157
    // Filter by role.
158
    $handler_settings = $this->configuration['handler_settings'];
159 160 161 162
    if (!empty($handler_settings['filter']['role'])) {
      $query->condition('roles', $handler_settings['filter']['role'], 'IN');
    }

163
    // Adding the permission check is sadly insufficient for users: core
164
    // requires us to also know about the concept of 'blocked' and 'active'.
165
    if (!$this->currentUser->hasPermission('administer users')) {
166 167 168 169 170 171
      $query->condition('status', 1);
    }
    return $query;
  }

  /**
172
   * {@inheritdoc}
173 174
   */
  public function entityQueryAlter(SelectInterface $query) {
175 176 177 178 179 180
    // Bail out early if we do not need to match the Anonymous user.
    $handler_settings = $this->configuration['handler_settings'];
    if (isset($handler_settings['include_anonymous']) && !$handler_settings['include_anonymous']) {
      return;
    }

181
    if ($this->currentUser->hasPermission('administer users')) {
182 183 184 185 186
      // In addition, if the user is administrator, we need to make sure to
      // match the anonymous user, that doesn't actually have a name in the
      // database.
      $conditions = &$query->conditions();
      foreach ($conditions as $key => $condition) {
187
        if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users_field_data.name') {
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
          // Remove the condition.
          unset($conditions[$key]);

          // Re-add the condition and a condition on uid = 0 so that we end up
          // with a query in the form:
          // WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
          $or = db_or();
          $or->condition($condition['field'], $condition['value'], $condition['operator']);
          // Sadly, the Database layer doesn't allow us to build a condition
          // in the form ':placeholder = :placeholder2', because the 'field'
          // part of a condition is always escaped.
          // As a (cheap) workaround, we separately build a condition with no
          // field, and concatenate the field and the condition separately.
          $value_part = db_and();
          $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
203
          $value_part->compile($this->connection, $query);
204
          $or->condition(db_and()
205
            ->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => \Drupal::config('user.settings')->get('anonymous')))
206
            ->condition('base_table.uid', 0)
207 208 209 210 211 212
          );
          $query->condition($or);
        }
      }
    }
  }
213

214
}