1 user.module user_roles($members_only = FALSE, $permission = NULL, $full_objects = FALSE)

Retrieve an array of roles matching specified conditions.

Parameters

$members_only: Set this to TRUE to exclude the 'anonymous' role.

$permission: A string containing a permission. If set, only roles containing that permission are returned.

$full_objects: TRUE to return complete role objects; FALSE to return role labels.

Return value

An associative array of role objects (or role labels, depending on: $full_objects) indexed by role names.

File

core/modules/user/user.module, line 2250
Enables the user registration and login system.

Code

function user_roles($members_only = FALSE, $permission = NULL, $full_objects = FALSE) {
  $user_roles = &backdrop_static(__FUNCTION__);

  if (!isset($user_roles)) {
    $user_roles = array();

    // @todo: Consider a cache get here instead of reading from disk.
    $names = config_get_names_with_prefix('user.role.');
    foreach ($names as $config_name) {
      $config = config($config_name);
      $role_name = str_replace('user.role.', '', $config_name);
      $role_data = $config->get();
      $role_data += array(
        'weight' => 0,
        'permissions' => array(),
      );
      $user_roles[$role_name] = $role_data;
    }
    backdrop_sort($user_roles, array('weight' => SORT_NUMERIC, 'name' => SORT_STRING));

    // Convert user roles into objects.
    // @todo: Consider using classes and a constructor here.
    foreach ($user_roles as $role_name => $role_data) {
      $user_roles[$role_name] = (object) $user_roles[$role_name];
      $user_roles[$role_name]->label = t($role_data['label']);
    }
  }

  $return_roles = $user_roles;
  if ($members_only) {
    unset($return_roles['anonymous']);
  }

  if ($permission) {
    foreach ($return_roles as $role_name => $role) {
      if (array_search($permission, $role->permissions) === FALSE) {
        unset($return_roles[$role_name]);
      }
    }
  }

  if (!$full_objects) {
    foreach ($return_roles as $role_name => $role) {
      $return_roles[$role_name] = $role->label;
    }
  }

  return $return_roles;
}