2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * External course participation api.
21 * This api is mostly read only, the actual enrol and unenrol
22 * support is in each enrol plugin.
26 * @copyright 2010 Jerome Mouneyrac
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') ||
die();
32 require_once("$CFG->libdir/externallib.php");
35 * Enrol external functions
39 * @copyright 2011 Jerome Mouneyrac
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 class core_enrol_external
extends external_api
{
46 * Returns description of method parameters
48 * @return external_function_parameters
51 public static function get_enrolled_users_with_capability_parameters() {
52 return new external_function_parameters(
54 'coursecapabilities' => new external_multiple_structure(
55 new external_single_structure(
57 'courseid' => new external_value(PARAM_INT
, 'Course ID number in the Moodle course table'),
58 'capabilities' => new external_multiple_structure(
59 new external_value(PARAM_CAPABILITY
, 'Capability name, such as mod/forum:viewdiscussion')),
62 , 'course id and associated capability name'),
63 'options' => new external_multiple_structure(
64 new external_single_structure(
66 'name' => new external_value(PARAM_ALPHANUMEXT
, 'option name'),
67 'value' => new external_value(PARAM_RAW
, 'option value')
70 * groupid (integer) return only users in this group id. Requires \'moodle/site:accessallgroups\' .
71 * onlyactive (integer) only users with active enrolments. Requires \'moodle/course:enrolreview\' .
72 * userfields (\'string, string, ...\') return only the values of these user fields.
73 * limitfrom (integer) sql limit from.
74 * limitnumber (integer) max number of users per course and capability.', VALUE_DEFAULT
, array())
80 * Return users that have the capabilities for each course specified. For each course and capability specified,
81 * a list of the users that are enrolled in the course and have that capability are returned.
83 * @param array $coursecapabilities array of course ids and associated capability names {courseid, {capabilities}}
84 * @return array An array of arrays describing users for each associated courseid and capability
87 public static function get_enrolled_users_with_capability($coursecapabilities, $options) {
90 require_once($CFG->dirroot
. '/course/lib.php');
91 require_once($CFG->dirroot
. "/user/lib.php");
93 if (empty($coursecapabilities)) {
94 throw new invalid_parameter_exception('Parameter can not be empty');
96 $params = self
::validate_parameters(self
::get_enrolled_users_with_capability_parameters(),
97 array ('coursecapabilities' => $coursecapabilities, 'options'=>$options));
102 $userfields = array();
105 foreach ($params['options'] as $option) {
106 switch ($option['name']) {
108 $groupid = (int)$option['value'];
111 $onlyactive = !empty($option['value']);
114 $thefields = explode(',', $option['value']);
115 foreach ($thefields as $f) {
116 $userfields[] = clean_param($f, PARAM_ALPHANUMEXT
);
120 $limitfrom = clean_param($option['value'], PARAM_INT
);
123 $limitnumber = clean_param($option['value'], PARAM_INT
);
128 foreach ($params['coursecapabilities'] as $coursecapability) {
129 $courseid = $coursecapability['courseid'];
130 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST
);
131 $coursecontext = context_course
::instance($courseid);
132 if (!$coursecontext) {
133 throw new moodle_exception('cannotfindcourse', 'error', '', null,
134 'The course id ' . $courseid . ' doesn\'t exist.');
136 if ($courseid == SITEID
) {
137 $context = context_system
::instance();
139 $context = $coursecontext;
142 self
::validate_context($context);
143 } catch (Exception
$e) {
144 $exceptionparam = new stdClass();
145 $exceptionparam->message
= $e->getMessage();
146 $exceptionparam->courseid
= $params['courseid'];
147 throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
150 course_require_view_participants($context);
152 // The accessallgroups capability is needed to use this option.
153 if (!empty($groupid) && groups_is_member($groupid)) {
154 require_capability('moodle/site:accessallgroups', $coursecontext);
156 // The course:enrolereview capability is needed to use this option.
158 require_capability('moodle/course:enrolreview', $coursecontext);
161 // To see the permissions of others role:review capability is required.
162 require_capability('moodle/role:review', $coursecontext);
163 foreach ($coursecapability['capabilities'] as $capability) {
164 $courseusers['courseid'] = $courseid;
165 $courseusers['capability'] = $capability;
167 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $capability, $groupid, $onlyactive);
169 $sql = "SELECT u.* FROM {user} u WHERE u.id IN ($enrolledsql) ORDER BY u.id ASC";
171 $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
173 foreach ($enrolledusers as $courseuser) {
174 if ($userdetails = user_get_user_details($courseuser, $course, $userfields)) {
175 $users[] = $userdetails;
178 $enrolledusers->close();
179 $courseusers['users'] = $users;
180 $result[] = $courseusers;
187 * Returns description of method result value
189 * @return external_multiple_structure
192 public static function get_enrolled_users_with_capability_returns() {
193 return new external_multiple_structure( new external_single_structure (
195 'courseid' => new external_value(PARAM_INT
, 'Course ID number in the Moodle course table'),
196 'capability' => new external_value(PARAM_CAPABILITY
, 'Capability name'),
197 'users' => new external_multiple_structure(
198 new external_single_structure(
200 'id' => new external_value(PARAM_INT
, 'ID of the user'),
201 'username' => new external_value(PARAM_RAW
, 'Username', VALUE_OPTIONAL
),
202 'firstname' => new external_value(PARAM_NOTAGS
, 'The first name(s) of the user', VALUE_OPTIONAL
),
203 'lastname' => new external_value(PARAM_NOTAGS
, 'The family name of the user', VALUE_OPTIONAL
),
204 'fullname' => new external_value(PARAM_NOTAGS
, 'The fullname of the user'),
205 'email' => new external_value(PARAM_TEXT
, 'Email address', VALUE_OPTIONAL
),
206 'address' => new external_value(PARAM_MULTILANG
, 'Postal address', VALUE_OPTIONAL
),
207 'phone1' => new external_value(PARAM_NOTAGS
, 'Phone 1', VALUE_OPTIONAL
),
208 'phone2' => new external_value(PARAM_NOTAGS
, 'Phone 2', VALUE_OPTIONAL
),
209 'icq' => new external_value(PARAM_NOTAGS
, 'icq number', VALUE_OPTIONAL
),
210 'skype' => new external_value(PARAM_NOTAGS
, 'skype id', VALUE_OPTIONAL
),
211 'yahoo' => new external_value(PARAM_NOTAGS
, 'yahoo id', VALUE_OPTIONAL
),
212 'aim' => new external_value(PARAM_NOTAGS
, 'aim id', VALUE_OPTIONAL
),
213 'msn' => new external_value(PARAM_NOTAGS
, 'msn number', VALUE_OPTIONAL
),
214 'department' => new external_value(PARAM_TEXT
, 'department', VALUE_OPTIONAL
),
215 'institution' => new external_value(PARAM_TEXT
, 'institution', VALUE_OPTIONAL
),
216 'interests' => new external_value(PARAM_TEXT
, 'user interests (separated by commas)', VALUE_OPTIONAL
),
217 'firstaccess' => new external_value(PARAM_INT
, 'first access to the site (0 if never)', VALUE_OPTIONAL
),
218 'lastaccess' => new external_value(PARAM_INT
, 'last access to the site (0 if never)', VALUE_OPTIONAL
),
219 'description' => new external_value(PARAM_RAW
, 'User profile description', VALUE_OPTIONAL
),
220 'descriptionformat' => new external_value(PARAM_INT
, 'User profile description format', VALUE_OPTIONAL
),
221 'city' => new external_value(PARAM_NOTAGS
, 'Home city of the user', VALUE_OPTIONAL
),
222 'url' => new external_value(PARAM_URL
, 'URL of the user', VALUE_OPTIONAL
),
223 'country' => new external_value(PARAM_ALPHA
, 'Country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
224 'profileimageurlsmall' => new external_value(PARAM_URL
, 'User image profile URL - small', VALUE_OPTIONAL
),
225 'profileimageurl' => new external_value(PARAM_URL
, 'User image profile URL - big', VALUE_OPTIONAL
),
226 'customfields' => new external_multiple_structure(
227 new external_single_structure(
229 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The type of the custom field'),
230 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
231 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
232 'shortname' => new external_value(PARAM_RAW
, 'The shortname of the custom field'),
234 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL
),
235 'groups' => new external_multiple_structure(
236 new external_single_structure(
238 'id' => new external_value(PARAM_INT
, 'group id'),
239 'name' => new external_value(PARAM_RAW
, 'group name'),
240 'description' => new external_value(PARAM_RAW
, 'group description'),
242 ), 'user groups', VALUE_OPTIONAL
),
243 'roles' => new external_multiple_structure(
244 new external_single_structure(
246 'roleid' => new external_value(PARAM_INT
, 'role id'),
247 'name' => new external_value(PARAM_RAW
, 'role name'),
248 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'role shortname'),
249 'sortorder' => new external_value(PARAM_INT
, 'role sortorder')
251 ), 'user roles', VALUE_OPTIONAL
),
252 'preferences' => new external_multiple_structure(
253 new external_single_structure(
255 'name' => new external_value(PARAM_RAW
, 'The name of the preferences'),
256 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
258 ), 'User preferences', VALUE_OPTIONAL
),
259 'enrolledcourses' => new external_multiple_structure(
260 new external_single_structure(
262 'id' => new external_value(PARAM_INT
, 'Id of the course'),
263 'fullname' => new external_value(PARAM_RAW
, 'Fullname of the course'),
264 'shortname' => new external_value(PARAM_RAW
, 'Shortname of the course')
266 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
)
268 ), 'List of users that are enrolled in the course and have the specified capability'),
275 * Returns description of method parameters
277 * @return external_function_parameters
279 public static function get_users_courses_parameters() {
280 return new external_function_parameters(
282 'userid' => new external_value(PARAM_INT
, 'user id'),
288 * Get list of courses user is enrolled in (only active enrolments are returned).
289 * Please note the current user must be able to access the course, otherwise the course is not included.
292 * @return array of courses
294 public static function get_users_courses($userid) {
295 global $CFG, $USER, $DB;
297 require_once($CFG->dirroot
. '/course/lib.php');
298 require_once($CFG->libdir
. '/completionlib.php');
300 // Do basic automatic PARAM checks on incoming data, using params description
301 // If any problems are found then exceptions are thrown with helpful error messages
302 $params = self
::validate_parameters(self
::get_users_courses_parameters(), array('userid'=>$userid));
303 $userid = $params['userid'];
305 $courses = enrol_get_users_courses($userid, true, '*');
308 // Get user data including last access to courses.
309 $user = get_complete_user_data('id', $userid);
310 $sameuser = $USER->id
== $userid;
312 // Retrieve favourited courses (starred).
313 $favouritecourseids = array();
315 $ufservice = \core_favourites\service_factory
::get_service_for_user_context(\context_user
::instance($userid));
316 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
319 $favouritecourseids = array_flip(array_map(
320 function($favourite) {
321 return $favourite->itemid
;
326 foreach ($courses as $course) {
327 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
329 self
::validate_context($context);
330 } catch (Exception
$e) {
331 // current user can not access this course, sorry we can not disclose who is enrolled in this course!
335 if (!$sameuser and !course_can_view_participants($context)) {
336 // we need capability to view participants
340 list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context);
341 $enrolledsql = "SELECT COUNT('x') FROM ($enrolledsqlselect) enrolleduserids";
342 $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams);
344 $displayname = external_format_string(get_course_display_name_for_list($course), $context->id
);
345 list($course->summary
, $course->summaryformat
) =
346 external_format_text($course->summary
, $course->summaryformat
, $context->id
, 'course', 'summary', null);
347 $course->fullname
= external_format_string($course->fullname
, $context->id
);
348 $course->shortname
= external_format_string($course->shortname
, $context->id
);
352 $completionhascriteria = false;
354 // Return only private information if the user should be able to see it.
355 if ($sameuser ||
completion_can_view_data($userid, $course)) {
356 if ($course->enablecompletion
) {
357 $completion = new completion_info($course);
358 $completed = $completion->is_course_complete($userid);
359 $completionhascriteria = $completion->has_criteria();
360 $progress = \core_completion\progress
::get_course_progress_percentage($course, $userid);
365 // Check if last access is a hidden field.
366 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
367 $canviewlastaccess = $sameuser ||
!isset($hiddenfields['lastaccess']);
368 if (!$canviewlastaccess) {
369 $canviewlastaccess = has_capability('moodle/course:viewhiddenuserfields', $context);
372 if ($canviewlastaccess && isset($user->lastcourseaccess
[$course->id
])) {
373 $lastaccess = $user->lastcourseaccess
[$course->id
];
378 $hidden = boolval(get_user_preferences('block_myoverview_hidden_course_' . $course->id
, 0));
381 // Retrieve course overview used files.
382 $courselist = new core_course_list_element($course);
383 $overviewfiles = array();
384 foreach ($courselist->get_course_overviewfiles() as $file) {
385 $fileurl = moodle_url
::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
386 $file->get_filearea(), null, $file->get_filepath(),
387 $file->get_filename())->out(false);
388 $overviewfiles[] = array(
389 'filename' => $file->get_filename(),
390 'fileurl' => $fileurl,
391 'filesize' => $file->get_filesize(),
392 'filepath' => $file->get_filepath(),
393 'mimetype' => $file->get_mimetype(),
394 'timemodified' => $file->get_timemodified(),
400 'shortname' => $course->shortname
,
401 'fullname' => $course->fullname
,
402 'displayname' => $displayname,
403 'idnumber' => $course->idnumber
,
404 'visible' => $course->visible
,
405 'enrolledusercount' => $enrolledusercount,
406 'summary' => $course->summary
,
407 'summaryformat' => $course->summaryformat
,
408 'format' => $course->format
,
409 'showgrades' => $course->showgrades
,
410 'lang' => clean_param($course->lang
, PARAM_LANG
),
411 'enablecompletion' => $course->enablecompletion
,
412 'completionhascriteria' => $completionhascriteria,
413 'category' => $course->category
,
414 'progress' => $progress,
415 'completed' => $completed,
416 'startdate' => $course->startdate
,
417 'enddate' => $course->enddate
,
418 'marker' => $course->marker
,
419 'lastaccess' => $lastaccess,
420 'isfavourite' => isset($favouritecourseids[$course->id
]),
422 'overviewfiles' => $overviewfiles,
430 * Returns description of method result value
432 * @return external_description
434 public static function get_users_courses_returns() {
435 return new external_multiple_structure(
436 new external_single_structure(
438 'id' => new external_value(PARAM_INT
, 'id of course'),
439 'shortname' => new external_value(PARAM_RAW
, 'short name of course'),
440 'fullname' => new external_value(PARAM_RAW
, 'long name of course'),
441 'displayname' => new external_value(PARAM_TEXT
, 'course display name for lists.', VALUE_OPTIONAL
),
442 'enrolledusercount' => new external_value(PARAM_INT
, 'Number of enrolled users in this course'),
443 'idnumber' => new external_value(PARAM_RAW
, 'id number of course'),
444 'visible' => new external_value(PARAM_INT
, '1 means visible, 0 means not yet visible course'),
445 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
446 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL
),
447 'format' => new external_value(PARAM_PLUGIN
, 'course format: weeks, topics, social, site', VALUE_OPTIONAL
),
448 'showgrades' => new external_value(PARAM_BOOL
, 'true if grades are shown, otherwise false', VALUE_OPTIONAL
),
449 'lang' => new external_value(PARAM_LANG
, 'forced course language', VALUE_OPTIONAL
),
450 'enablecompletion' => new external_value(PARAM_BOOL
, 'true if completion is enabled, otherwise false',
452 'completionhascriteria' => new external_value(PARAM_BOOL
, 'If completion criteria is set.', VALUE_OPTIONAL
),
453 'category' => new external_value(PARAM_INT
, 'course category id', VALUE_OPTIONAL
),
454 'progress' => new external_value(PARAM_FLOAT
, 'Progress percentage', VALUE_OPTIONAL
),
455 'completed' => new external_value(PARAM_BOOL
, 'Whether the course is completed.', VALUE_OPTIONAL
),
456 'startdate' => new external_value(PARAM_INT
, 'Timestamp when the course start', VALUE_OPTIONAL
),
457 'enddate' => new external_value(PARAM_INT
, 'Timestamp when the course end', VALUE_OPTIONAL
),
458 'marker' => new external_value(PARAM_INT
, 'Course section marker.', VALUE_OPTIONAL
),
459 'lastaccess' => new external_value(PARAM_INT
, 'Last access to the course (timestamp).', VALUE_OPTIONAL
),
460 'isfavourite' => new external_value(PARAM_BOOL
, 'If the user marked this course a favourite.', VALUE_OPTIONAL
),
461 'hidden' => new external_value(PARAM_BOOL
, 'If the user hide the course from the dashboard.', VALUE_OPTIONAL
),
462 'overviewfiles' => new external_files('Overview files attached to this course.', VALUE_OPTIONAL
),
469 * Returns description of method parameters value
471 * @return external_description
473 public static function get_potential_users_parameters() {
474 return new external_function_parameters(
476 'courseid' => new external_value(PARAM_INT
, 'course id'),
477 'enrolid' => new external_value(PARAM_INT
, 'enrolment id'),
478 'search' => new external_value(PARAM_RAW
, 'query'),
479 'searchanywhere' => new external_value(PARAM_BOOL
, 'find a match anywhere, or only at the beginning'),
480 'page' => new external_value(PARAM_INT
, 'Page number'),
481 'perpage' => new external_value(PARAM_INT
, 'Number per page'),
487 * Get potential users.
489 * @param int $courseid Course id
490 * @param int $enrolid Enrolment id
491 * @param string $search The query
492 * @param boolean $searchanywhere Match anywhere in the string
493 * @param int $page Page number
494 * @param int $perpage Max per page
495 * @return array An array of users
497 public static function get_potential_users($courseid, $enrolid, $search, $searchanywhere, $page, $perpage) {
498 global $PAGE, $DB, $CFG;
500 require_once($CFG->dirroot
.'/enrol/locallib.php');
501 require_once($CFG->dirroot
.'/user/lib.php');
503 $params = self
::validate_parameters(
504 self
::get_potential_users_parameters(),
506 'courseid' => $courseid,
507 'enrolid' => $enrolid,
509 'searchanywhere' => $searchanywhere,
511 'perpage' => $perpage
514 $context = context_course
::instance($params['courseid']);
516 self
::validate_context($context);
517 } catch (Exception
$e) {
518 $exceptionparam = new stdClass();
519 $exceptionparam->message
= $e->getMessage();
520 $exceptionparam->courseid
= $params['courseid'];
521 throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
523 require_capability('moodle/course:enrolreview', $context);
525 $course = $DB->get_record('course', array('id' => $params['courseid']));
526 $manager = new course_enrolment_manager($PAGE, $course);
528 $users = $manager->get_potential_users($params['enrolid'],
530 $params['searchanywhere'],
535 // Add also extra user fields.
536 $requiredfields = array_merge(
537 ['id', 'fullname', 'profileimageurl', 'profileimageurlsmall'],
538 get_extra_user_fields($context)
540 foreach ($users['users'] as $id => $user) {
541 // Note: We pass the course here to validate that the current user can at least view user details in this course.
542 // The user we are looking at is not in this course yet though - but we only fetch the minimal set of
543 // user records, and the user has been validated to have course:enrolreview in this course. Otherwise
544 // there is no way to find users who aren't in the course in order to enrol them.
545 if ($userdetails = user_get_user_details($user, $course, $requiredfields)) {
546 $results[] = $userdetails;
553 * Returns description of method result value
555 * @return external_description
557 public static function get_potential_users_returns() {
559 require_once($CFG->dirroot
. '/user/externallib.php');
560 return new external_multiple_structure(core_user_external
::user_description());
564 * Returns description of method parameters
566 * @return external_function_parameters
568 public static function get_enrolled_users_parameters() {
569 return new external_function_parameters(
571 'courseid' => new external_value(PARAM_INT
, 'course id'),
572 'options' => new external_multiple_structure(
573 new external_single_structure(
575 'name' => new external_value(PARAM_ALPHANUMEXT
, 'option name'),
576 'value' => new external_value(PARAM_RAW
, 'option value')
579 * withcapability (string) return only users with this capability. This option requires \'moodle/role:review\' on the course context.
580 * groupid (integer) return only users in this group id. If the course has groups enabled and this param
581 isn\'t defined, returns all the viewable users.
582 This option requires \'moodle/site:accessallgroups\' on the course context if the
583 user doesn\'t belong to the group.
584 * onlyactive (integer) return only users with active enrolments and matching time restrictions. This option requires \'moodle/course:enrolreview\' on the course context.
585 * userfields (\'string, string, ...\') return only the values of these user fields.
586 * limitfrom (integer) sql limit from.
587 * limitnumber (integer) maximum number of returned users.
588 * sortby (string) sort by id, firstname or lastname. For ordering like the site does, use siteorder.
589 * sortdirection (string) ASC or DESC',
590 VALUE_DEFAULT
, array()),
596 * Get course participants details
598 * @param int $courseid course id
599 * @param array $options options {
600 * 'name' => option name
601 * 'value' => option value
603 * @return array An array of users
605 public static function get_enrolled_users($courseid, $options = array()) {
606 global $CFG, $USER, $DB;
608 require_once($CFG->dirroot
. '/course/lib.php');
609 require_once($CFG->dirroot
. "/user/lib.php");
611 $params = self
::validate_parameters(
612 self
::get_enrolled_users_parameters(),
614 'courseid'=>$courseid,
618 $withcapability = '';
621 $userfields = array();
625 $sortparams = array();
626 $sortdirection = 'ASC';
627 foreach ($options as $option) {
628 switch ($option['name']) {
629 case 'withcapability':
630 $withcapability = $option['value'];
633 $groupid = (int)$option['value'];
636 $onlyactive = !empty($option['value']);
639 $thefields = explode(',', $option['value']);
640 foreach ($thefields as $f) {
641 $userfields[] = clean_param($f, PARAM_ALPHANUMEXT
);
645 $limitfrom = clean_param($option['value'], PARAM_INT
);
648 $limitnumber = clean_param($option['value'], PARAM_INT
);
651 $sortallowedvalues = array('id', 'firstname', 'lastname', 'siteorder');
652 if (!in_array($option['value'], $sortallowedvalues)) {
653 throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $option['value'] . '),' .
654 'allowed values are: ' . implode(',', $sortallowedvalues));
656 if ($option['value'] == 'siteorder') {
657 list($sortby, $sortparams) = users_order_by_sql('us');
659 $sortby = 'us.' . $option['value'];
662 case 'sortdirection':
663 $sortdirection = strtoupper($option['value']);
664 $directionallowedvalues = array('ASC', 'DESC');
665 if (!in_array($sortdirection, $directionallowedvalues)) {
666 throw new invalid_parameter_exception('Invalid value for sortdirection parameter
667 (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues));
673 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST
);
674 $coursecontext = context_course
::instance($courseid, IGNORE_MISSING
);
675 if ($courseid == SITEID
) {
676 $context = context_system
::instance();
678 $context = $coursecontext;
681 self
::validate_context($context);
682 } catch (Exception
$e) {
683 $exceptionparam = new stdClass();
684 $exceptionparam->message
= $e->getMessage();
685 $exceptionparam->courseid
= $params['courseid'];
686 throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
689 course_require_view_participants($context);
691 // to overwrite this parameter, you need role:review capability
692 if ($withcapability) {
693 require_capability('moodle/role:review', $coursecontext);
695 // need accessallgroups capability if you want to overwrite this option
696 if (!empty($groupid) && !groups_is_member($groupid)) {
697 require_capability('moodle/site:accessallgroups', $coursecontext);
699 // to overwrite this option, you need course:enrolereview permission
701 require_capability('moodle/course:enrolreview', $coursecontext);
704 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
705 $ctxselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
706 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
707 $enrolledparams['contextlevel'] = CONTEXT_USER
;
710 if (empty($groupid) && groups_get_course_groupmode($course) == SEPARATEGROUPS
&&
711 !has_capability('moodle/site:accessallgroups', $coursecontext)) {
712 // Filter by groups the user can view.
713 $usergroups = groups_get_user_groups($course->id
);
714 if (!empty($usergroups['0'])) {
715 list($groupsql, $groupparams) = $DB->get_in_or_equal($usergroups['0'], SQL_PARAMS_NAMED
);
716 $groupjoin = "JOIN {groups_members} gm ON (u.id = gm.userid AND gm.groupid $groupsql)";
717 $enrolledparams = array_merge($enrolledparams, $groupparams);
719 // User doesn't belong to any group, so he can't see any user. Return an empty array.
726 SELECT DISTINCT u.id $ctxselect
727 FROM {user} u $ctxjoin $groupjoin
728 WHERE u.id IN ($enrolledsql)
730 ORDER BY $sortby $sortdirection";
731 $enrolledparams = array_merge($enrolledparams, $sortparams);
732 $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
734 foreach ($enrolledusers as $user) {
735 context_helper
::preload_from_record($user);
736 if ($userdetails = user_get_user_details($user, $course, $userfields)) {
737 $users[] = $userdetails;
740 $enrolledusers->close();
746 * Returns description of method result value
748 * @return external_description
750 public static function get_enrolled_users_returns() {
751 return new external_multiple_structure(
752 new external_single_structure(
754 'id' => new external_value(PARAM_INT
, 'ID of the user'),
755 'username' => new external_value(PARAM_RAW
, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL
),
756 'firstname' => new external_value(PARAM_NOTAGS
, 'The first name(s) of the user', VALUE_OPTIONAL
),
757 'lastname' => new external_value(PARAM_NOTAGS
, 'The family name of the user', VALUE_OPTIONAL
),
758 'fullname' => new external_value(PARAM_NOTAGS
, 'The fullname of the user'),
759 'email' => new external_value(PARAM_TEXT
, 'An email address - allow email as root@localhost', VALUE_OPTIONAL
),
760 'address' => new external_value(PARAM_TEXT
, 'Postal address', VALUE_OPTIONAL
),
761 'phone1' => new external_value(PARAM_NOTAGS
, 'Phone 1', VALUE_OPTIONAL
),
762 'phone2' => new external_value(PARAM_NOTAGS
, 'Phone 2', VALUE_OPTIONAL
),
763 'icq' => new external_value(PARAM_NOTAGS
, 'icq number', VALUE_OPTIONAL
),
764 'skype' => new external_value(PARAM_NOTAGS
, 'skype id', VALUE_OPTIONAL
),
765 'yahoo' => new external_value(PARAM_NOTAGS
, 'yahoo id', VALUE_OPTIONAL
),
766 'aim' => new external_value(PARAM_NOTAGS
, 'aim id', VALUE_OPTIONAL
),
767 'msn' => new external_value(PARAM_NOTAGS
, 'msn number', VALUE_OPTIONAL
),
768 'department' => new external_value(PARAM_TEXT
, 'department', VALUE_OPTIONAL
),
769 'institution' => new external_value(PARAM_TEXT
, 'institution', VALUE_OPTIONAL
),
770 'idnumber' => new external_value(PARAM_RAW
, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL
),
771 'interests' => new external_value(PARAM_TEXT
, 'user interests (separated by commas)', VALUE_OPTIONAL
),
772 'firstaccess' => new external_value(PARAM_INT
, 'first access to the site (0 if never)', VALUE_OPTIONAL
),
773 'lastaccess' => new external_value(PARAM_INT
, 'last access to the site (0 if never)', VALUE_OPTIONAL
),
774 'description' => new external_value(PARAM_RAW
, 'User profile description', VALUE_OPTIONAL
),
775 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL
),
776 'city' => new external_value(PARAM_NOTAGS
, 'Home city of the user', VALUE_OPTIONAL
),
777 'url' => new external_value(PARAM_URL
, 'URL of the user', VALUE_OPTIONAL
),
778 'country' => new external_value(PARAM_ALPHA
, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
779 'profileimageurlsmall' => new external_value(PARAM_URL
, 'User image profile URL - small version', VALUE_OPTIONAL
),
780 'profileimageurl' => new external_value(PARAM_URL
, 'User image profile URL - big version', VALUE_OPTIONAL
),
781 'customfields' => new external_multiple_structure(
782 new external_single_structure(
784 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The type of the custom field - text field, checkbox...'),
785 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
786 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
787 'shortname' => new external_value(PARAM_RAW
, 'The shortname of the custom field - to be able to build the field class in the code'),
789 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL
),
790 'groups' => new external_multiple_structure(
791 new external_single_structure(
793 'id' => new external_value(PARAM_INT
, 'group id'),
794 'name' => new external_value(PARAM_RAW
, 'group name'),
795 'description' => new external_value(PARAM_RAW
, 'group description'),
796 'descriptionformat' => new external_format_value('description'),
798 ), 'user groups', VALUE_OPTIONAL
),
799 'roles' => new external_multiple_structure(
800 new external_single_structure(
802 'roleid' => new external_value(PARAM_INT
, 'role id'),
803 'name' => new external_value(PARAM_RAW
, 'role name'),
804 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'role shortname'),
805 'sortorder' => new external_value(PARAM_INT
, 'role sortorder')
807 ), 'user roles', VALUE_OPTIONAL
),
808 'preferences' => new external_multiple_structure(
809 new external_single_structure(
811 'name' => new external_value(PARAM_RAW
, 'The name of the preferences'),
812 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
814 ), 'User preferences', VALUE_OPTIONAL
),
815 'enrolledcourses' => new external_multiple_structure(
816 new external_single_structure(
818 'id' => new external_value(PARAM_INT
, 'Id of the course'),
819 'fullname' => new external_value(PARAM_RAW
, 'Fullname of the course'),
820 'shortname' => new external_value(PARAM_RAW
, 'Shortname of the course')
822 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
)
829 * Returns description of get_course_enrolment_methods() parameters
831 * @return external_function_parameters
833 public static function get_course_enrolment_methods_parameters() {
834 return new external_function_parameters(
836 'courseid' => new external_value(PARAM_INT
, 'Course id')
842 * Get list of active course enrolment methods for current user.
844 * @param int $courseid
845 * @return array of course enrolment methods
846 * @throws moodle_exception
848 public static function get_course_enrolment_methods($courseid) {
851 $params = self
::validate_parameters(self
::get_course_enrolment_methods_parameters(), array('courseid' => $courseid));
852 self
::validate_context(context_system
::instance());
854 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST
);
855 $context = context_course
::instance($course->id
);
856 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $context)) {
857 throw new moodle_exception('coursehidden');
861 $enrolinstances = enrol_get_instances($params['courseid'], true);
862 foreach ($enrolinstances as $enrolinstance) {
863 if ($enrolplugin = enrol_get_plugin($enrolinstance->enrol
)) {
864 if ($instanceinfo = $enrolplugin->get_enrol_info($enrolinstance)) {
865 $result[] = (array) $instanceinfo;
873 * Returns description of get_course_enrolment_methods() result value
875 * @return external_description
877 public static function get_course_enrolment_methods_returns() {
878 return new external_multiple_structure(
879 new external_single_structure(
881 'id' => new external_value(PARAM_INT
, 'id of course enrolment instance'),
882 'courseid' => new external_value(PARAM_INT
, 'id of course'),
883 'type' => new external_value(PARAM_PLUGIN
, 'type of enrolment plugin'),
884 'name' => new external_value(PARAM_RAW
, 'name of enrolment plugin'),
885 'status' => new external_value(PARAM_RAW
, 'status of enrolment plugin'),
886 'wsfunction' => new external_value(PARAM_ALPHANUMEXT
, 'webservice function to get more information', VALUE_OPTIONAL
),
893 * Returns description of edit_user_enrolment() parameters
895 * @return external_function_parameters
897 public static function edit_user_enrolment_parameters() {
898 return new external_function_parameters(
900 'courseid' => new external_value(PARAM_INT
, 'User enrolment ID'),
901 'ueid' => new external_value(PARAM_INT
, 'User enrolment ID'),
902 'status' => new external_value(PARAM_INT
, 'Enrolment status'),
903 'timestart' => new external_value(PARAM_INT
, 'Enrolment start timestamp', VALUE_DEFAULT
, 0),
904 'timeend' => new external_value(PARAM_INT
, 'Enrolment end timestamp', VALUE_DEFAULT
, 0),
910 * External function that updates a given user enrolment.
912 * @param int $courseid The course ID.
913 * @param int $ueid The user enrolment ID.
914 * @param int $status The enrolment status.
915 * @param int $timestart Enrolment start timestamp.
916 * @param int $timeend Enrolment end timestamp.
917 * @return array An array consisting of the processing result, errors and form output, if available.
919 public static function edit_user_enrolment($courseid, $ueid, $status, $timestart = 0, $timeend = 0) {
920 global $CFG, $DB, $PAGE;
922 $params = self
::validate_parameters(self
::edit_user_enrolment_parameters(), [
923 'courseid' => $courseid,
926 'timestart' => $timestart,
927 'timeend' => $timeend,
930 $course = get_course($courseid);
931 $context = context_course
::instance($course->id
);
932 self
::validate_context($context);
934 $userenrolment = $DB->get_record('user_enrolments', ['id' => $params['ueid']], '*', MUST_EXIST
);
936 'status' => $params['status'],
937 'timestart' => $params['timestart'],
938 'timeend' => $params['timeend'],
944 // Validate data against the edit user enrolment form.
945 $instance = $DB->get_record('enrol', ['id' => $userenrolment->enrolid
], '*', MUST_EXIST
);
946 $plugin = enrol_get_plugin($instance->enrol
);
947 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
949 'ue' => $userenrolment,
951 'enrolinstancename' => $plugin->get_instance_name($instance)
953 $mform = new \
enrol_user_enrolment_form(null, $customformdata, 'post', '', null, true, $userenroldata);
954 $mform->set_data($userenroldata);
955 $validationerrors = $mform->validation($userenroldata, null);
956 if (empty($validationerrors)) {
957 require_once($CFG->dirroot
. '/enrol/locallib.php');
958 $manager = new course_enrolment_manager($PAGE, $course);
959 $result = $manager->edit_enrolment($userenrolment, (object)$userenroldata);
961 foreach ($validationerrors as $key => $errormessage) {
962 $errors[] = (object)[
964 'message' => $errormessage
976 * Returns description of edit_user_enrolment() result value
978 * @return external_description
980 public static function edit_user_enrolment_returns() {
981 return new external_single_structure(
983 'result' => new external_value(PARAM_BOOL
, 'True if the user\'s enrolment was successfully updated'),
984 'errors' => new external_multiple_structure(
985 new external_single_structure(
987 'key' => new external_value(PARAM_TEXT
, 'The data that failed the validation'),
988 'message' => new external_value(PARAM_TEXT
, 'The error message'),
990 ), 'List of validation errors'
997 * Returns description of unenrol_user_enrolment() parameters
999 * @return external_function_parameters
1001 public static function unenrol_user_enrolment_parameters() {
1002 return new external_function_parameters(
1004 'ueid' => new external_value(PARAM_INT
, 'User enrolment ID')
1010 * External function that unenrols a given user enrolment.
1012 * @param int $ueid The user enrolment ID.
1013 * @return array An array consisting of the processing result, errors.
1015 public static function unenrol_user_enrolment($ueid) {
1016 global $CFG, $DB, $PAGE;
1018 $params = self
::validate_parameters(self
::unenrol_user_enrolment_parameters(), [
1025 $userenrolment = $DB->get_record('user_enrolments', ['id' => $params['ueid']], '*');
1026 if ($userenrolment) {
1027 $userid = $userenrolment->userid
;
1028 $enrolid = $userenrolment->enrolid
;
1029 $enrol = $DB->get_record('enrol', ['id' => $enrolid], '*', MUST_EXIST
);
1030 $courseid = $enrol->courseid
;
1031 $course = get_course($courseid);
1032 $context = context_course
::instance($course->id
);
1033 self
::validate_context($context);
1035 $validationerrors['invalidrequest'] = get_string('invalidrequest', 'enrol');
1038 // If the userenrolment exists, unenrol the user.
1039 if (!isset($validationerrors)) {
1040 require_once($CFG->dirroot
. '/enrol/locallib.php');
1041 $manager = new course_enrolment_manager($PAGE, $course);
1042 $result = $manager->unenrol_user($userenrolment);
1044 foreach ($validationerrors as $key => $errormessage) {
1045 $errors[] = (object)[
1047 'message' => $errormessage
1053 'result' => $result,
1054 'errors' => $errors,
1059 * Returns description of unenrol_user_enrolment() result value
1061 * @return external_description
1063 public static function unenrol_user_enrolment_returns() {
1064 return new external_single_structure(
1066 'result' => new external_value(PARAM_BOOL
, 'True if the user\'s enrolment was successfully updated'),
1067 'errors' => new external_multiple_structure(
1068 new external_single_structure(
1070 'key' => new external_value(PARAM_TEXT
, 'The data that failed the validation'),
1071 'message' => new external_value(PARAM_TEXT
, 'The error message'),
1073 ), 'List of validation errors'
1081 * Role external functions
1083 * @package core_role
1084 * @category external
1085 * @copyright 2011 Jerome Mouneyrac
1086 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1089 class core_role_external
extends external_api
{
1092 * Returns description of method parameters
1094 * @return external_function_parameters
1096 public static function assign_roles_parameters() {
1097 return new external_function_parameters(
1099 'assignments' => new external_multiple_structure(
1100 new external_single_structure(
1102 'roleid' => new external_value(PARAM_INT
, 'Role to assign to the user'),
1103 'userid' => new external_value(PARAM_INT
, 'The user that is going to be assigned'),
1104 'contextid' => new external_value(PARAM_INT
, 'The context to assign the user role in', VALUE_OPTIONAL
),
1105 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level to assign the user role in
1106 (block, course, coursecat, system, user, module)', VALUE_OPTIONAL
),
1107 'instanceid' => new external_value(PARAM_INT
, 'The Instance id of item where the role needs to be assigned', VALUE_OPTIONAL
),
1116 * Manual role assignments to users
1118 * @param array $assignments An array of manual role assignment
1120 public static function assign_roles($assignments) {
1123 // Do basic automatic PARAM checks on incoming data, using params description
1124 // If any problems are found then exceptions are thrown with helpful error messages
1125 $params = self
::validate_parameters(self
::assign_roles_parameters(), array('assignments'=>$assignments));
1127 $transaction = $DB->start_delegated_transaction();
1129 foreach ($params['assignments'] as $assignment) {
1130 // Ensure correct context level with a instance id or contextid is passed.
1131 $context = self
::get_context_from_params($assignment);
1133 // Ensure the current user is allowed to run this function in the enrolment context.
1134 self
::validate_context($context);
1135 require_capability('moodle/role:assign', $context);
1137 // throw an exception if user is not able to assign the role in this context
1138 $roles = get_assignable_roles($context, ROLENAME_SHORT
);
1140 if (!array_key_exists($assignment['roleid'], $roles)) {
1141 throw new invalid_parameter_exception('Can not assign roleid='.$assignment['roleid'].' in contextid='.$assignment['contextid']);
1144 role_assign($assignment['roleid'], $assignment['userid'], $context->id
);
1147 $transaction->allow_commit();
1151 * Returns description of method result value
1155 public static function assign_roles_returns() {
1161 * Returns description of method parameters
1163 * @return external_function_parameters
1165 public static function unassign_roles_parameters() {
1166 return new external_function_parameters(
1168 'unassignments' => new external_multiple_structure(
1169 new external_single_structure(
1171 'roleid' => new external_value(PARAM_INT
, 'Role to assign to the user'),
1172 'userid' => new external_value(PARAM_INT
, 'The user that is going to be assigned'),
1173 'contextid' => new external_value(PARAM_INT
, 'The context to unassign the user role from', VALUE_OPTIONAL
),
1174 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level to unassign the user role in
1175 + (block, course, coursecat, system, user, module)', VALUE_OPTIONAL
),
1176 'instanceid' => new external_value(PARAM_INT
, 'The Instance id of item where the role needs to be unassigned', VALUE_OPTIONAL
),
1185 * Unassign roles from users
1187 * @param array $unassignments An array of unassignment
1189 public static function unassign_roles($unassignments) {
1192 // Do basic automatic PARAM checks on incoming data, using params description
1193 // If any problems are found then exceptions are thrown with helpful error messages
1194 $params = self
::validate_parameters(self
::unassign_roles_parameters(), array('unassignments'=>$unassignments));
1196 $transaction = $DB->start_delegated_transaction();
1198 foreach ($params['unassignments'] as $unassignment) {
1199 // Ensure the current user is allowed to run this function in the unassignment context
1200 $context = self
::get_context_from_params($unassignment);
1201 self
::validate_context($context);
1202 require_capability('moodle/role:assign', $context);
1204 // throw an exception if user is not able to unassign the role in this context
1205 $roles = get_assignable_roles($context, ROLENAME_SHORT
);
1206 if (!array_key_exists($unassignment['roleid'], $roles)) {
1207 throw new invalid_parameter_exception('Can not unassign roleid='.$unassignment['roleid'].' in contextid='.$unassignment['contextid']);
1210 role_unassign($unassignment['roleid'], $unassignment['userid'], $context->id
);
1213 $transaction->allow_commit();
1217 * Returns description of method result value
1221 public static function unassign_roles_returns() {