Retrieve an array of roles matching specified conditions.
$membersonly: Set this to TRUE to exclude the 'anonymous' role.
$permission: A string containing a permission. If set, only roles containing that permission are returned.
An associative array with the role id as the key and the role name as value.
function user_roles($membersonly = FALSE, $permission = NULL) {
$user_roles =& drupal_static(__FUNCTION__);
// Do not cache roles for specific permissions. This data is not requested
// frequently enough to justify the additional memory use.
if (empty($permission)) {
$cid = $membersonly ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
if (isset($user_roles[$cid])) {
return $user_roles[$cid];
}
}
$query = db_select('role', 'r');
$query
->addTag('translatable');
$query
->fields('r', array(
'rid',
'name',
));
$query
->orderBy('weight');
$query
->orderBy('name');
if (!empty($permission)) {
$query
->innerJoin('role_permission', 'p', 'r.rid = p.rid');
$query
->condition('p.permission', $permission);
}
if ($membersonly) {
$query
->condition('r.rid', DRUPAL_ANONYMOUS_RID, '!=');
}
$roles = $query
->execute()
->fetchAllKeyed();
if (empty($permission)) {
$user_roles[$cid] = $roles;
return $user_roles[$cid];
}
return $roles;
}