get_enrolled_users() vs get_users_by_capability()

get_enrolled_users() vs get_users_by_capability()

by Matthew Davidson -
Number of replies: 2
Picture of Core developers Picture of Plugin developers

I have run into multiple instances where plugins were using get_users_by_capability() when generating a list of users to contact.  I have argued that the correct function to use would be get_enrolled_users() instead because this eliminates the inclusion of users with system roles.  For instance, questionnaire currently generates a list of users that are "non responders".  It does this by getting a list of everyone who has the capability to take the questionnaire and removes the users that already have.  However, in this list are all the site admins and managers.  Although they have the capability of taking any questionnaire, they aren't the intended audience.  This becomes a real issue when the list is anonymous and system users can't be deselected manually from the list.  

Another case is a plugin that has student submission emails going to people with the capability to grade.  Again, admins and managers receive emails.  

I'm pretty sure I'm correct on this, but could I get some validation on when is the appropriate time to use get_users_by_capability() and when is the correct time to use get_enrolled_users()

Thanks!!

Average of ratings: -
In reply to Matthew Davidson

Re: get_enrolled_users() vs get_users_by_capability()

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Well, in the instance of an assignment - you want the users on a course who have the capability of submitting assignment, not the users who are enrolled on the course.

If you look at the capability definitions (https://github.com/moodle/moodle/blob/master/mod/assign/db/access.php), only people with the student role (usually only assigned at the course level) will be found by get_users_by_capability(). Conversely, get_enrolled_users() would get every teacher, course creator, etc. enrolled on the course.

So, if pretty much always the correct answer is to a) use get_users_by_capability() and b) make sure that the capability in question is not allocated to roles that are assigned above the course level (something you can do by default, but you can't stop system admins doing anything silly).


In reply to Davo Smith

Re: get_enrolled_users() vs get_users_by_capability()

by Matthew Davidson -
Picture of Core developers Picture of Plugin developers

I guess I should have been more clear that I was comparing using

get_enrolled_users($context, $capability, 0, 'u.id');

vs

get_users_by_capability($context,$capability, 'u.id');

Where both versions are given a certain capability to narrow it down with.  

Does that change anything?