You are here

function cf_user_has_role in Common Functionality 7.2

Same name and namespace in other branches
  1. 7 modules/cf_user/cf_user.module \cf_user_has_role()

Confirm whether a user is in a given role by the role id.

Justification: The roles stored in the global $user variable are role names and not ids. This provides a way to get user role ids without having to load the user data, process each role, and produce an array of role ids.

Parameters

int $rid: a rid of the role to check to see if a user has the given permission.

int $uid: (optional) a uid of the user to get the role ids of if the current user is not to be used.

Return value

bool FALSE on error, FALSE if not in role, and TRUE if in role.

Related topics

File

modules/cf_user/cf_user.module, line 115
Common Functionality - User module.

Code

function cf_user_has_role($rid, $uid = NULL) {
  if (!is_numeric($rid)) {
    if (class_exists('cf_error')) {
      cf_error::invalid_numeric('rid');
    }
    return FALSE;
  }
  if ($uid == NULL) {
    $current_user = cf_current_user(FALSE);
    $uid = $current_user->uid;
  }
  elseif (!is_numeric($uid)) {
    if (class_exists('cf_error')) {
      cf_error::invalid_numeric('uid');
    }
    return FALSE;
  }

  // Roles 0, 1, and 2 don't actually get assigned and can be guessed based on uid.
  if ($rid == 0) {
    return $uid == 0;
  }
  elseif ($rid == 1) {
    return $uid == 1;
  }
  elseif ($rid == 2) {
    return $uid != 0;
  }
  $query = cf_user_get_rids($uid);
  if (is_object($query)) {
    $and = db_and();
    $and
      ->condition('r.rid', $rid, '=');
    $query
      ->condition($and);
    try {
      $query_execute = $query
        ->execute();
      if ($query_execute
        ->rowCount() == 1) {
        return TRUE;
      }
    } catch (Exception $e) {
      if (class_exists('cf_error')) {
        cf_error::on_query_execution($e);
      }
    }
  }
  return FALSE;
}