From b6b6c7acb62ed17b9e36e784dd8042f2f95232ab Mon Sep 17 00:00:00 2001
From: Paul Charsley
Date: Wed, 19 Sep 2012 13:01:26 +1200
Subject: [PATCH] MDL-31859 added get_enrolled_users_with_capability web
service function
---
enrol/externallib.php | 229 +++++++++++++++++++++++++++++++
enrol/tests/externallib_test.php | 61 ++++++--
lib/db/services.php | 9 ++
3 files changed, 289 insertions(+), 10 deletions(-)
diff --git a/enrol/externallib.php b/enrol/externallib.php
index 757362aa694..a316f577e73 100644
--- a/enrol/externallib.php
+++ b/enrol/externallib.php
@@ -42,6 +42,235 @@ require_once("$CFG->libdir/externallib.php");
*/
class core_enrol_external extends external_api {
+ /**
+ * Returns description of method parameters
+ *
+ * @return external_function_parameters
+ * @since Moodle 2.4
+ */
+ public static function get_enrolled_users_with_capability_parameters() {
+ return new external_function_parameters(
+ array (
+ 'coursecapabilities' => new external_multiple_structure(
+ new external_single_structure(
+ array (
+ 'courseid' => new external_value(PARAM_INT, 'Course ID number in the Moodle course table'),
+ 'capabilities' => new external_multiple_structure(
+ new external_value(PARAM_CAPABILITY, 'Capability name, such as mod/forum:viewdiscussion')),
+ )
+ )
+ , 'course id and associated capability name'),
+ 'options' => new external_multiple_structure(
+ new external_single_structure(
+ array(
+ 'name' => new external_value(PARAM_ALPHANUMEXT, 'option name'),
+ 'value' => new external_value(PARAM_RAW, 'option value')
+ )
+ ), 'Option names:
+ * groupid (integer) return only users in this group id. Requires \'moodle/site:accessallgroups\' .
+ * onlyactive (integer) only users with active enrolments. Requires \'moodle/course:enrolreview\' .
+ * userfields (\'string, string, ...\') return only the values of these user fields.
+ * limitfrom (integer) sql limit from.
+ * limitnumber (integer) max number of users per course and capability.', VALUE_DEFAULT, array())
+ )
+ );
+ }
+
+ /**
+ * Return users that have the capabilities for each course specified. For each course and capability specified,
+ * a list of the users that are enrolled in the course and have that capability are returned.
+ *
+ * @param array $coursecapabilities array of course ids and associated capability names {courseid, {capabilities}}
+ * @return array An array of arrays describing users for each associated courseid and capability
+ * @since Moodle 2.4
+ */
+ public static function get_enrolled_users_with_capability($coursecapabilities, $options) {
+ global $CFG, $DB;
+ require_once($CFG->dirroot . "/user/lib.php");
+
+ if (empty($coursecapabilities)) {
+ throw new invalid_parameter_exception('Parameter can not be empty');
+ }
+ $params = self::validate_parameters(self::get_enrolled_users_with_capability_parameters(),
+ array ('coursecapabilities' => $coursecapabilities, 'options'=>$options));
+ $result = array();
+ $userlist = array();
+ $groupid = 0;
+ $onlyactive = false;
+ $userfields = array();
+ $limitfrom = 0;
+ $limitnumber = 0;
+ foreach ($params['options'] as $option) {
+ switch ($option['name']) {
+ case 'groupid':
+ $groupid = (int)$option['value'];
+ break;
+ case 'onlyactive':
+ $onlyactive = !empty($option['value']);
+ break;
+ case 'userfields':
+ $thefields = explode(',', $option['value']);
+ foreach ($thefields as $f) {
+ $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
+ }
+ case 'limitfrom' :
+ $limitfrom = clean_param($option['value'], PARAM_INT);
+ break;
+ case 'limitnumber' :
+ $limitnumber = clean_param($option['value'], PARAM_INT);
+ break;
+ }
+ }
+
+ foreach ($params['coursecapabilities'] as $coursecapability) {
+ $courseid = $coursecapability['courseid'];
+ $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
+ $coursecontext = context_course::instance($courseid);
+ if (!$coursecontext) {
+ throw new moodle_exception('cannotfindcourse', 'error', '', null,
+ 'The course id ' . $courseid . ' doesn\'t exist.');
+ }
+ if ($courseid == SITEID) {
+ $context = context_system::instance();
+ } else {
+ $context = $coursecontext;
+ }
+ try {
+ self::validate_context($context);
+ } catch (Exception $e) {
+ $exceptionparam = new stdClass();
+ $exceptionparam->message = $e->getMessage();
+ $exceptionparam->courseid = $params['courseid'];
+ throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
+ }
+
+ if ($courseid == SITEID) {
+ require_capability('moodle/site:viewparticipants', $context);
+ } else {
+ require_capability('moodle/course:viewparticipants', $context);
+ }
+ // The accessallgroups capability is needed to use this option.
+ if (!empty($groupid) && groups_is_member($groupid)) {
+ require_capability('moodle/site:accessallgroups', $coursecontext);
+ }
+ // The course:enrolereview capability is needed to use this option.
+ if ($onlyactive) {
+ require_capability('moodle/course:enrolreview', $coursecontext);
+ }
+
+ // To see the permissions of others role:review capability is required.
+ require_capability('moodle/role:review', $coursecontext);
+ foreach ($coursecapability['capabilities'] as $capability) {
+ $courseusers['courseid'] = $courseid;
+ $courseusers['capability'] = $capability;
+
+ list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $capability, $groupid, $onlyactive);
+
+ $sql = "SELECT u.* FROM {user} u WHERE u.id IN ($enrolledsql) ORDER BY u.id ASC";
+
+ $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
+ $users = array();
+ foreach ($enrolledusers as $courseuser) {
+ if ($userdetails = user_get_user_details($courseuser, $course, $userfields)) {
+ $users[] = $userdetails;
+ }
+ }
+ $enrolledusers->close();
+ $courseusers['users'] = $users;
+ $result[] = $courseusers;
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * Returns description of method result value
+ *
+ * @return external_multiple_structure
+ * @since Moodle 2.4
+ */
+ public static function get_enrolled_users_with_capability_returns() {
+ return new external_multiple_structure( new external_single_structure (
+ array (
+ 'courseid' => new external_value(PARAM_INT, 'Course ID number in the Moodle course table'),
+ 'capability' => new external_value(PARAM_CAPABILITY, 'Capability name'),
+ 'users' => new external_multiple_structure(
+ new external_single_structure(
+ array(
+ 'id' => new external_value(PARAM_NUMBER, 'ID of the user'),
+ 'username' => new external_value(PARAM_RAW, 'Username', VALUE_OPTIONAL),
+ 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
+ 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
+ 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
+ 'email' => new external_value(PARAM_TEXT, 'Email address', VALUE_OPTIONAL),
+ 'address' => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
+ 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
+ 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
+ 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
+ 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
+ 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
+ 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
+ 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
+ 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
+ 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
+ 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
+ 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
+ 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
+ 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
+ 'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
+ 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
+ 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
+ 'country' => new external_value(PARAM_ALPHA, 'Country code of the user, such as AU or CZ', VALUE_OPTIONAL),
+ 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small', VALUE_OPTIONAL),
+ 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big', VALUE_OPTIONAL),
+ 'customfields' => new external_multiple_structure(
+ new external_single_structure(
+ array(
+ 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field'),
+ 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
+ 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
+ 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field'),
+ )
+ ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
+ 'groups' => new external_multiple_structure(
+ new external_single_structure(
+ array(
+ 'id' => new external_value(PARAM_INT, 'group id'),
+ 'name' => new external_value(PARAM_RAW, 'group name'),
+ 'description' => new external_value(PARAM_RAW, 'group description'),
+ )
+ ), 'user groups', VALUE_OPTIONAL),
+ 'roles' => new external_multiple_structure(
+ new external_single_structure(
+ array(
+ 'roleid' => new external_value(PARAM_INT, 'role id'),
+ 'name' => new external_value(PARAM_RAW, 'role name'),
+ 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
+ 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
+ )
+ ), 'user roles', VALUE_OPTIONAL),
+ 'preferences' => new external_multiple_structure(
+ new external_single_structure(
+ array(
+ 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
+ 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
+ )
+ ), 'User preferences', VALUE_OPTIONAL),
+ 'enrolledcourses' => new external_multiple_structure(
+ new external_single_structure(
+ array(
+ 'id' => new external_value(PARAM_INT, 'Id of the course'),
+ 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
+ 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
+ )
+ ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
+ )
+ ), 'List of users that are enrolled in the course and have the specified capability'),
+ )
+ )
+ );
+ }
+
/**
* Returns description of method parameters
*
diff --git a/enrol/tests/externallib_test.php b/enrol/tests/externallib_test.php
index 7fb95006796..4fd30e68e1f 100644
--- a/enrol/tests/externallib_test.php
+++ b/enrol/tests/externallib_test.php
@@ -14,16 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Enrol/Role external PHPunit tests
- *
- * @package core_enrol
- * @category external
- * @copyright 2012 Jerome Mouneyrac
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- * @since Moodle 2.4
- */
-
defined('MOODLE_INTERNAL') || die();
global $CFG;
@@ -122,6 +112,57 @@ class core_enrol_external_testcase extends externallib_advanced_testcase {
// Check we retrieve the good total number of enrolled users.
$this->assertEquals(2, count($enrolledincourses));
}
+
+ /**
+ * Test get_enrolled_users_with_capability
+ */
+ public function test_get_enrolled_users_with_capability () {
+ global $DB, $USER;
+
+ $this->resetAfterTest(true);
+
+ $coursedata['idnumber'] = 'idnumbercourse1';
+ $coursedata['fullname'] = 'Lightwork Course 1';
+ $coursedata['summary'] = 'Lightwork Course 1 description';
+ $coursedata['summaryformat'] = FORMAT_MOODLE;
+ $course1 = self::getDataGenerator()->create_course($coursedata);
+
+ // Create a manual enrolment record.
+ $manual_enrol_data['enrol'] = 'manual';
+ $manual_enrol_data['status'] = 0;
+ $manual_enrol_data['courseid'] = $course1->id;
+ $enrolid = $DB->insert_record('enrol', $manual_enrol_data);
+
+ // Create the user and give them capabilities in the course context.
+ $context = context_course::instance($course1->id);
+ $roleid = $this->assignUserCapability('moodle/course:viewparticipants', $context->id, 3);
+
+ // Create a student.
+ $student1 = self::getDataGenerator()->create_user();
+
+ // Enrol both the user and the student in the course.
+ $user_enrolment_data['status'] = 0;
+ $user_enrolment_data['enrolid'] = $enrolid;
+ $user_enrolment_data['userid'] = $USER->id;
+ $DB->insert_record('user_enrolments', $user_enrolment_data);
+
+ $user_enrolment_data['status'] = 0;
+ $user_enrolment_data['enrolid'] = $enrolid;
+ $user_enrolment_data['userid'] = $student1->id;
+ $DB->insert_record('user_enrolments', $user_enrolment_data);
+
+ $params = array("coursecapabilities" =>array
+ ('courseid' => $course1->id, 'capabilities' => array('moodle/course:viewparticipants')));
+ $options = array();
+ $result = core_enrol_external::get_enrolled_users_with_capability($params, $options);
+
+ // Check an array containing the expected user for the course capability is returned.
+ $expecteduserlist = $result[0];
+ $this->assertEquals($course1->id, $expecteduserlist['courseid']);
+ $this->assertEquals('moodle/course:viewparticipants', $expecteduserlist['capability']);
+ $this->assertEquals(1, count($expecteduserlist['users']));
+
+ }
}
/**
diff --git a/lib/db/services.php b/lib/db/services.php
index cf9acb04fe6..638ec727440 100644
--- a/lib/db/services.php
+++ b/lib/db/services.php
@@ -355,6 +355,15 @@ $functions = array(
),
// === enrol related functions ===
+
+ 'core_enrol_get_enrolled_users_with_capability' => array(
+ 'classname' => 'core_enrol_external',
+ 'methodname' => 'get_enrolled_users_with_capability',
+ 'classpath' => 'enrol/externallib.php',
+ 'description' => 'For each course and capability specified, return a list of the users that are enrolled in the course
+ and have that capability',
+ 'type' => 'read',
+ ),
'moodle_enrol_get_enrolled_users' => array(
'classname' => 'moodle_enrol_external',