'Return a sorted list of legitimate roles that can be associated with a permission on
item where item is a Library or a Dataset.  The cntrller param is the controller from
which the request is sent.  We cannot use trans.user_is_admin() because the controller is
what is important since admin users do not necessarily have permission to do things
on items outside of the admin view.
If cntrller is from the admin side ( e.g., library_admin ):
- if item is public, all roles, including private roles, are legitimate.
- if item is restricted, legitimate roles are derived from the users and groups associated
with each role that is associated with the access permission ( i.e., DATASET_MANAGE_PERMISSIONS or
LIBRARY_MANAGE ) on item.  Legitimate roles will include private roles.
If cntrller is not from the admin side ( e.g., root, library ):
- if item is public, all non-private roles, except for the current user\'s private role,
are legitimate.
- if item is restricted, legitimate roles are derived from the users and groups associated
with each role that is associated with the access permission on item.  Private roles, except
for the current user\'s private role, will be excluded.'

def get_legitimate_roles(self, trans, item, cntrller):

    admin_controller = (cntrller in ['library_admin'])
    roles = set()
    if ((isinstance(item, self.model.Library) and self.library_is_public(item)) or (isinstance(item, self.model.Dataset) and self.dataset_is_public(item))):
        return self.get_all_roles(trans, cntrller)
    access_roles = item.get_access_roles(trans)
    for role in access_roles:
        if (admin_controller or self.ok_to_display(trans.user, role)):
            roles.add(role)
            for ura in role.users:
                user = ura.user
                for ura2 in user.roles:
                    if (admin_controller or self.ok_to_display(trans.user, ura2.role)):
                        roles.add(ura2.role)
            for gra in role.groups:
                group = gra.group
                for uga in group.users:
                    user = uga.user
                    for ura in user.roles:
                        if (admin_controller or self.ok_to_display(trans.user, ura.role)):
                            roles.add(ura.role)
    return self.sort_by_attr([role for role in roles], 'name')
