You are here

function User::validate_argument in Views (for Drupal 7) 8.3

Overrides ArgumentValidatorPluginBase::validate_argument

File

lib/Views/user/Plugin/views/argument_validator/User.php, line 75
Definition of Views\user\Plugin\views\argument_validator\User.

Class

User
Validate whether an argument is a valid user.

Namespace

Views\user\Plugin\views\argument_validator

Code

function validate_argument($argument) {
  $type = $this->options['type'];

  // is_numeric() can return false positives, so we ensure it's an integer.
  // However, is_integer() will always fail, since $argument is a string.
  if (is_numeric($argument) && $argument == (int) $argument) {
    if ($type == 'uid' || $type == 'either') {
      if ($argument == $GLOBALS['user']->uid) {

        // If you assign an object to a variable in PHP, the variable
        // automatically acts as a reference, not a copy, so we use
        // clone to ensure that we don't actually mess with the
        // real global $user object.
        $account = clone $GLOBALS['user'];
      }
      $condition = 'uid';
    }
  }
  else {
    if ($type == 'name' || $type == 'either') {
      $name = !empty($GLOBALS['user']->name) ? $GLOBALS['user']->name : config('user.settings')
        ->get('anonymous');
      if ($argument == $name) {
        $account = clone $GLOBALS['user'];
      }
      $condition = 'name';
    }
  }

  // If we don't have a WHERE clause, the argument is invalid.
  if (empty($condition)) {
    return FALSE;
  }
  if (!isset($account)) {
    $account = db_select('users', 'u')
      ->fields('u', array(
      'uid',
      'name',
    ))
      ->condition($condition, $argument)
      ->execute()
      ->fetchObject();
  }
  if (empty($account)) {

    // User not found.
    return FALSE;
  }

  // See if we're filtering users based on roles.
  if (!empty($this->options['restrict_roles']) && !empty($this->options['roles'])) {
    $roles = $this->options['roles'];
    $account->roles = array();
    $account->roles[] = $account->uid ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
    $query = db_select('users_roles', 'u');
    $query
      ->addField('u', 'rid');
    $query
      ->condition('u.uid', $account->uid);
    $result = $query
      ->execute();
    foreach ($result as $role) {
      $account->roles[] = $role->rid;
    }
    if (!(bool) array_intersect($account->roles, $roles)) {
      return FALSE;
    }
  }
  $this->argument->argument = $account->uid;
  $this->argument->validated_title = check_plain(user_format_name($account));
  return TRUE;
}