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/>.
18 * Course participations External functions.
22 * @copyright 2010 Jerome Mouneyrac
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 use core_external\external_api
;
27 use core_external\external_files
;
28 use core_external\external_format_value
;
29 use core_external\external_function_parameters
;
30 use core_external\external_multiple_structure
;
31 use core_external\external_single_structure
;
32 use core_external\external_value
;
35 * Enrol external functions
37 * This api is mostly read only, the actual enrol and unenrol
38 * support is in each enrol plugin.
42 * @copyright 2010 Jerome Mouneyrac
43 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46 class core_enrol_external
extends external_api
{
49 * Returns description of method parameters
51 * @return external_function_parameters
54 public static function get_enrolled_users_with_capability_parameters() {
55 return new external_function_parameters(
57 'coursecapabilities' => new external_multiple_structure(
58 new external_single_structure(
60 'courseid' => new external_value(PARAM_INT
, 'Course ID number in the Moodle course table'),
61 'capabilities' => new external_multiple_structure(
62 new external_value(PARAM_CAPABILITY
, 'Capability name, such as mod/forum:viewdiscussion')),
65 , 'course id and associated capability name'),
66 'options' => new external_multiple_structure(
67 new external_single_structure(
69 'name' => new external_value(PARAM_ALPHANUMEXT
, 'option name'),
70 'value' => new external_value(PARAM_RAW
, 'option value')
73 * groupid (integer) return only users in this group id. Requires \'moodle/site:accessallgroups\' .
74 * onlyactive (integer) only users with active enrolments. Requires \'moodle/course:enrolreview\' .
75 * userfields (\'string, string, ...\') return only the values of these user fields.
76 * limitfrom (integer) sql limit from.
77 * limitnumber (integer) max number of users per course and capability.', VALUE_DEFAULT
, array())
83 * Return users that have the capabilities for each course specified. For each course and capability specified,
84 * a list of the users that are enrolled in the course and have that capability are returned.
86 * @param array $coursecapabilities array of course ids and associated capability names {courseid, {capabilities}}
87 * @return array An array of arrays describing users for each associated courseid and capability
90 public static function get_enrolled_users_with_capability($coursecapabilities, $options) {
93 require_once($CFG->dirroot
. '/course/lib.php');
94 require_once($CFG->dirroot
. "/user/lib.php");
96 if (empty($coursecapabilities)) {
97 throw new invalid_parameter_exception('Parameter can not be empty');
99 $params = self
::validate_parameters(self
::get_enrolled_users_with_capability_parameters(),
100 array ('coursecapabilities' => $coursecapabilities, 'options'=>$options));
105 $userfields = array();
108 foreach ($params['options'] as $option) {
109 switch ($option['name']) {
111 $groupid = (int)$option['value'];
114 $onlyactive = !empty($option['value']);
117 $thefields = explode(',', $option['value']);
118 foreach ($thefields as $f) {
119 $userfields[] = clean_param($f, PARAM_ALPHANUMEXT
);
123 $limitfrom = clean_param($option['value'], PARAM_INT
);
126 $limitnumber = clean_param($option['value'], PARAM_INT
);
131 foreach ($params['coursecapabilities'] as $coursecapability) {
132 $courseid = $coursecapability['courseid'];
133 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST
);
134 $coursecontext = context_course
::instance($courseid);
135 if (!$coursecontext) {
136 throw new moodle_exception('cannotfindcourse', 'error', '', null,
137 'The course id ' . $courseid . ' doesn\'t exist.');
139 if ($courseid == SITEID
) {
140 $context = context_system
::instance();
142 $context = $coursecontext;
145 self
::validate_context($context);
146 } catch (Exception
$e) {
147 $exceptionparam = new stdClass();
148 $exceptionparam->message
= $e->getMessage();
149 $exceptionparam->courseid
= $params['courseid'];
150 throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
153 course_require_view_participants($context);
155 // The accessallgroups capability is needed to use this option.
156 if (!empty($groupid) && groups_is_member($groupid)) {
157 require_capability('moodle/site:accessallgroups', $coursecontext);
159 // The course:enrolereview capability is needed to use this option.
161 require_capability('moodle/course:enrolreview', $coursecontext);
164 // To see the permissions of others role:review capability is required.
165 require_capability('moodle/role:review', $coursecontext);
166 foreach ($coursecapability['capabilities'] as $capability) {
167 $courseusers['courseid'] = $courseid;
168 $courseusers['capability'] = $capability;
170 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $capability, $groupid, $onlyactive);
171 $enrolledparams['courseid'] = $courseid;
173 $sql = "SELECT u.*, COALESCE(ul.timeaccess, 0) AS lastcourseaccess
175 LEFT JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = :courseid)
176 WHERE u.id IN ($enrolledsql)
179 $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
181 foreach ($enrolledusers as $courseuser) {
182 if ($userdetails = user_get_user_details($courseuser, $course, $userfields)) {
183 $users[] = $userdetails;
186 $enrolledusers->close();
187 $courseusers['users'] = $users;
188 $result[] = $courseusers;
195 * Returns description of method result value
197 * @return external_multiple_structure
200 public static function get_enrolled_users_with_capability_returns() {
201 return new external_multiple_structure( new external_single_structure (
203 'courseid' => new external_value(PARAM_INT
, 'Course ID number in the Moodle course table'),
204 'capability' => new external_value(PARAM_CAPABILITY
, 'Capability name'),
205 'users' => new external_multiple_structure(
206 new external_single_structure(
208 'id' => new external_value(PARAM_INT
, 'ID of the user'),
209 'username' => new external_value(PARAM_RAW
, 'Username', VALUE_OPTIONAL
),
210 'firstname' => new external_value(PARAM_NOTAGS
, 'The first name(s) of the user', VALUE_OPTIONAL
),
211 'lastname' => new external_value(PARAM_NOTAGS
, 'The family name of the user', VALUE_OPTIONAL
),
212 'fullname' => new external_value(PARAM_NOTAGS
, 'The fullname of the user'),
213 'email' => new external_value(PARAM_TEXT
, 'Email address', VALUE_OPTIONAL
),
214 'address' => new external_value(PARAM_MULTILANG
, 'Postal address', VALUE_OPTIONAL
),
215 'phone1' => new external_value(PARAM_NOTAGS
, 'Phone 1', VALUE_OPTIONAL
),
216 'phone2' => new external_value(PARAM_NOTAGS
, 'Phone 2', VALUE_OPTIONAL
),
217 'department' => new external_value(PARAM_TEXT
, 'department', VALUE_OPTIONAL
),
218 'institution' => new external_value(PARAM_TEXT
, 'institution', VALUE_OPTIONAL
),
219 'interests' => new external_value(PARAM_TEXT
, 'user interests (separated by commas)', VALUE_OPTIONAL
),
220 'firstaccess' => new external_value(PARAM_INT
, 'first access to the site (0 if never)', VALUE_OPTIONAL
),
221 'lastaccess' => new external_value(PARAM_INT
, 'last access to the site (0 if never)', VALUE_OPTIONAL
),
222 'lastcourseaccess' => new external_value(PARAM_INT
, 'last access to the course (0 if never)', VALUE_OPTIONAL
),
223 'description' => new external_value(PARAM_RAW
, 'User profile description', VALUE_OPTIONAL
),
224 'descriptionformat' => new external_value(PARAM_INT
, 'User profile description format', VALUE_OPTIONAL
),
225 'city' => new external_value(PARAM_NOTAGS
, 'Home city of the user', VALUE_OPTIONAL
),
226 'country' => new external_value(PARAM_ALPHA
, 'Country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
227 'profileimageurlsmall' => new external_value(PARAM_URL
, 'User image profile URL - small', VALUE_OPTIONAL
),
228 'profileimageurl' => new external_value(PARAM_URL
, 'User image profile URL - big', VALUE_OPTIONAL
),
229 'customfields' => new external_multiple_structure(
230 new external_single_structure(
232 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The type of the custom field'),
233 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
234 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
235 'shortname' => new external_value(PARAM_RAW
, 'The shortname of the custom field'),
237 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL
),
238 'groups' => new external_multiple_structure(
239 new external_single_structure(
241 'id' => new external_value(PARAM_INT
, 'group id'),
242 'name' => new external_value(PARAM_RAW
, 'group name'),
243 'description' => new external_value(PARAM_RAW
, 'group description'),
245 ), 'user groups', VALUE_OPTIONAL
),
246 'roles' => new external_multiple_structure(
247 new external_single_structure(
249 'roleid' => new external_value(PARAM_INT
, 'role id'),
250 'name' => new external_value(PARAM_RAW
, 'role name'),
251 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'role shortname'),
252 'sortorder' => new external_value(PARAM_INT
, 'role sortorder')
254 ), 'user roles', VALUE_OPTIONAL
),
255 'preferences' => new external_multiple_structure(
256 new external_single_structure(
258 'name' => new external_value(PARAM_RAW
, 'The name of the preferences'),
259 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
261 ), 'User preferences', VALUE_OPTIONAL
),
262 'enrolledcourses' => new external_multiple_structure(
263 new external_single_structure(
265 'id' => new external_value(PARAM_INT
, 'Id of the course'),
266 'fullname' => new external_value(PARAM_RAW
, 'Fullname of the course'),
267 'shortname' => new external_value(PARAM_RAW
, 'Shortname of the course')
269 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
)
271 ), 'List of users that are enrolled in the course and have the specified capability'),
278 * Returns description of method parameters
280 * @return external_function_parameters
282 public static function get_users_courses_parameters() {
283 return new external_function_parameters(
285 'userid' => new external_value(PARAM_INT
, 'user id'),
286 'returnusercount' => new external_value(PARAM_BOOL
,
287 'Include count of enrolled users for each course? This can add several seconds to the response time'
288 . ' if a user is on several large courses, so set this to false if the value will not be used to'
289 . ' improve performance.',
290 VALUE_DEFAULT
, true),
296 * Get list of courses user is enrolled in (only active enrolments are returned).
297 * Please note the current user must be able to access the course, otherwise the course is not included.
300 * @param bool $returnusercount
301 * @return array of courses
303 public static function get_users_courses($userid, $returnusercount = true) {
304 global $CFG, $USER, $DB;
306 require_once($CFG->dirroot
. '/course/lib.php');
307 require_once($CFG->dirroot
. '/user/lib.php');
308 require_once($CFG->libdir
. '/completionlib.php');
310 // Do basic automatic PARAM checks on incoming data, using params description
311 // If any problems are found then exceptions are thrown with helpful error messages
312 $params = self
::validate_parameters(self
::get_users_courses_parameters(),
313 ['userid' => $userid, 'returnusercount' => $returnusercount]);
314 $userid = $params['userid'];
315 $returnusercount = $params['returnusercount'];
317 $courses = enrol_get_users_courses($userid, true, '*');
320 // Get user data including last access to courses.
321 $user = get_complete_user_data('id', $userid);
322 $sameuser = $USER->id
== $userid;
324 // Retrieve favourited courses (starred).
325 $favouritecourseids = array();
327 $ufservice = \core_favourites\service_factory
::get_service_for_user_context(\context_user
::instance($userid));
328 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
331 $favouritecourseids = array_flip(array_map(
332 function($favourite) {
333 return $favourite->itemid
;
338 foreach ($courses as $course) {
339 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
341 self
::validate_context($context);
342 } catch (Exception
$e) {
343 // current user can not access this course, sorry we can not disclose who is enrolled in this course!
347 // If viewing details of another user, then we must be able to view participants as well as profile of that user.
348 if (!$sameuser && (!course_can_view_participants($context) ||
!user_can_view_profile($user, $course))) {
352 if ($returnusercount) {
353 list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context);
354 $enrolledsql = "SELECT COUNT('x') FROM ($enrolledsqlselect) enrolleduserids";
355 $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams);
358 $displayname = \core_external\util
::format_string(get_course_display_name_for_list($course), $context);
359 list($course->summary
, $course->summaryformat
) =
360 \core_external\util
::format_text($course->summary
, $course->summaryformat
, $context, 'course', 'summary', null);
361 $course->fullname
= \core_external\util
::format_string($course->fullname
, $context);
362 $course->shortname
= \core_external\util
::format_string($course->shortname
, $context);
366 $completionhascriteria = false;
367 $completionusertracked = false;
369 // Return only private information if the user should be able to see it.
370 if ($sameuser ||
completion_can_view_data($userid, $course)) {
371 if ($course->enablecompletion
) {
372 $completion = new completion_info($course);
373 $completed = $completion->is_course_complete($userid);
374 $completionhascriteria = $completion->has_criteria();
375 $completionusertracked = $completion->is_tracked_user($userid);
376 $progress = \core_completion\progress
::get_course_progress_percentage($course, $userid);
381 // Check if last access is a hidden field.
382 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
383 $canviewlastaccess = $sameuser ||
!isset($hiddenfields['lastaccess']);
384 if (!$canviewlastaccess) {
385 $canviewlastaccess = has_capability('moodle/course:viewhiddenuserfields', $context);
388 if ($canviewlastaccess && isset($user->lastcourseaccess
[$course->id
])) {
389 $lastaccess = $user->lastcourseaccess
[$course->id
];
394 $hidden = boolval(get_user_preferences('block_myoverview_hidden_course_' . $course->id
, 0));
397 // Retrieve course overview used files.
398 $courselist = new core_course_list_element($course);
399 $overviewfiles = array();
400 foreach ($courselist->get_course_overviewfiles() as $file) {
401 $fileurl = moodle_url
::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
402 $file->get_filearea(), null, $file->get_filepath(),
403 $file->get_filename())->out(false);
404 $overviewfiles[] = array(
405 'filename' => $file->get_filename(),
406 'fileurl' => $fileurl,
407 'filesize' => $file->get_filesize(),
408 'filepath' => $file->get_filepath(),
409 'mimetype' => $file->get_mimetype(),
410 'timemodified' => $file->get_timemodified(),
416 'shortname' => $course->shortname
,
417 'fullname' => $course->fullname
,
418 'displayname' => $displayname,
419 'idnumber' => $course->idnumber
,
420 'visible' => $course->visible
,
421 'summary' => $course->summary
,
422 'summaryformat' => $course->summaryformat
,
423 'format' => $course->format
,
424 'showgrades' => $course->showgrades
,
425 'lang' => clean_param($course->lang
, PARAM_LANG
),
426 'enablecompletion' => $course->enablecompletion
,
427 'completionhascriteria' => $completionhascriteria,
428 'completionusertracked' => $completionusertracked,
429 'category' => $course->category
,
430 'progress' => $progress,
431 'completed' => $completed,
432 'startdate' => $course->startdate
,
433 'enddate' => $course->enddate
,
434 'marker' => $course->marker
,
435 'lastaccess' => $lastaccess,
436 'isfavourite' => isset($favouritecourseids[$course->id
]),
438 'overviewfiles' => $overviewfiles,
439 'showactivitydates' => $course->showactivitydates
,
440 'showcompletionconditions' => $course->showcompletionconditions
,
441 'timemodified' => $course->timemodified
,
443 if ($returnusercount) {
444 $courseresult['enrolledusercount'] = $enrolledusercount;
446 $result[] = $courseresult;
453 * Returns description of method result value
455 * @return \core_external\external_description
457 public static function get_users_courses_returns() {
458 return new external_multiple_structure(
459 new external_single_structure(
461 'id' => new external_value(PARAM_INT
, 'id of course'),
462 'shortname' => new external_value(PARAM_RAW
, 'short name of course'),
463 'fullname' => new external_value(PARAM_RAW
, 'long name of course'),
464 'displayname' => new external_value(PARAM_RAW
, 'course display name for lists.', VALUE_OPTIONAL
),
465 'enrolledusercount' => new external_value(PARAM_INT
, 'Number of enrolled users in this course',
467 'idnumber' => new external_value(PARAM_RAW
, 'id number of course'),
468 'visible' => new external_value(PARAM_INT
, '1 means visible, 0 means not yet visible course'),
469 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
470 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL
),
471 'format' => new external_value(PARAM_PLUGIN
, 'course format: weeks, topics, social, site', VALUE_OPTIONAL
),
472 'showgrades' => new external_value(PARAM_BOOL
, 'true if grades are shown, otherwise false', VALUE_OPTIONAL
),
473 'lang' => new external_value(PARAM_LANG
, 'forced course language', VALUE_OPTIONAL
),
474 'enablecompletion' => new external_value(PARAM_BOOL
, 'true if completion is enabled, otherwise false',
476 'completionhascriteria' => new external_value(PARAM_BOOL
, 'If completion criteria is set.', VALUE_OPTIONAL
),
477 'completionusertracked' => new external_value(PARAM_BOOL
, 'If the user is completion tracked.', VALUE_OPTIONAL
),
478 'category' => new external_value(PARAM_INT
, 'course category id', VALUE_OPTIONAL
),
479 'progress' => new external_value(PARAM_FLOAT
, 'Progress percentage', VALUE_OPTIONAL
),
480 'completed' => new external_value(PARAM_BOOL
, 'Whether the course is completed.', VALUE_OPTIONAL
),
481 'startdate' => new external_value(PARAM_INT
, 'Timestamp when the course start', VALUE_OPTIONAL
),
482 'enddate' => new external_value(PARAM_INT
, 'Timestamp when the course end', VALUE_OPTIONAL
),
483 'marker' => new external_value(PARAM_INT
, 'Course section marker.', VALUE_OPTIONAL
),
484 'lastaccess' => new external_value(PARAM_INT
, 'Last access to the course (timestamp).', VALUE_OPTIONAL
),
485 'isfavourite' => new external_value(PARAM_BOOL
, 'If the user marked this course a favourite.', VALUE_OPTIONAL
),
486 'hidden' => new external_value(PARAM_BOOL
, 'If the user hide the course from the dashboard.', VALUE_OPTIONAL
),
487 'overviewfiles' => new external_files('Overview files attached to this course.', VALUE_OPTIONAL
),
488 'showactivitydates' => new external_value(PARAM_BOOL
, 'Whether the activity dates are shown or not'),
489 'showcompletionconditions' => new external_value(PARAM_BOOL
, 'Whether the activity completion conditions are shown or not'),
490 'timemodified' => new external_value(PARAM_INT
, 'Last time course settings were updated (timestamp).',
498 * Returns description of method parameters value
500 * @return \core_external\external_description
502 public static function get_potential_users_parameters() {
503 return new external_function_parameters(
505 'courseid' => new external_value(PARAM_INT
, 'course id'),
506 'enrolid' => new external_value(PARAM_INT
, 'enrolment id'),
507 'search' => new external_value(PARAM_RAW
, 'query'),
508 'searchanywhere' => new external_value(PARAM_BOOL
, 'find a match anywhere, or only at the beginning'),
509 'page' => new external_value(PARAM_INT
, 'Page number'),
510 'perpage' => new external_value(PARAM_INT
, 'Number per page'),
516 * Get potential users.
518 * @param int $courseid Course id
519 * @param int $enrolid Enrolment id
520 * @param string $search The query
521 * @param boolean $searchanywhere Match anywhere in the string
522 * @param int $page Page number
523 * @param int $perpage Max per page
524 * @return array An array of users
526 public static function get_potential_users($courseid, $enrolid, $search, $searchanywhere, $page, $perpage) {
527 global $PAGE, $DB, $CFG;
529 require_once($CFG->dirroot
.'/enrol/locallib.php');
530 require_once($CFG->dirroot
.'/user/lib.php');
532 $params = self
::validate_parameters(
533 self
::get_potential_users_parameters(),
535 'courseid' => $courseid,
536 'enrolid' => $enrolid,
538 'searchanywhere' => $searchanywhere,
540 'perpage' => $perpage
543 $context = context_course
::instance($params['courseid']);
545 self
::validate_context($context);
546 } catch (Exception
$e) {
547 $exceptionparam = new stdClass();
548 $exceptionparam->message
= $e->getMessage();
549 $exceptionparam->courseid
= $params['courseid'];
550 throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
552 require_capability('moodle/course:enrolreview', $context);
554 $course = $DB->get_record('course', array('id' => $params['courseid']));
555 $manager = new course_enrolment_manager($PAGE, $course);
557 $users = $manager->get_potential_users($params['enrolid'],
559 $params['searchanywhere'],
564 // Add also extra user fields.
565 $identityfields = \core_user\fields
::get_identity_fields($context, true);
566 $customprofilefields = [];
567 foreach ($identityfields as $key => $value) {
568 if ($fieldname = \core_user\fields
::match_custom_field($value)) {
569 unset($identityfields[$key]);
570 $customprofilefields[$fieldname] = true;
573 if ($customprofilefields) {
574 $identityfields[] = 'customfields';
576 $requiredfields = array_merge(
577 ['id', 'fullname', 'profileimageurl', 'profileimageurlsmall'],
580 foreach ($users['users'] as $id => $user) {
581 // Note: We pass the course here to validate that the current user can at least view user details in this course.
582 // The user we are looking at is not in this course yet though - but we only fetch the minimal set of
583 // user records, and the user has been validated to have course:enrolreview in this course. Otherwise
584 // there is no way to find users who aren't in the course in order to enrol them.
585 if ($userdetails = user_get_user_details($user, $course, $requiredfields)) {
586 // For custom fields, only return the ones we actually need.
587 if ($customprofilefields && array_key_exists('customfields', $userdetails)) {
588 foreach ($userdetails['customfields'] as $key => $data) {
589 if (!array_key_exists($data['shortname'], $customprofilefields)) {
590 unset($userdetails['customfields'][$key]);
593 $userdetails['customfields'] = array_values($userdetails['customfields']);
595 $results[] = $userdetails;
602 * Returns description of method result value
604 * @return \core_external\external_description
606 public static function get_potential_users_returns() {
608 require_once($CFG->dirroot
. '/user/externallib.php');
609 return new external_multiple_structure(core_user_external
::user_description());
613 * Returns description of method parameters
615 * @return external_function_parameters
617 public static function search_users_parameters(): external_function_parameters
{
618 return new external_function_parameters(
620 'courseid' => new external_value(PARAM_INT
, 'course id'),
621 'search' => new external_value(PARAM_RAW
, 'query'),
622 'searchanywhere' => new external_value(PARAM_BOOL
, 'find a match anywhere, or only at the beginning'),
623 'page' => new external_value(PARAM_INT
, 'Page number'),
624 'perpage' => new external_value(PARAM_INT
, 'Number per page'),
630 * Search course participants.
632 * @param int $courseid Course id
633 * @param string $search The query
634 * @param bool $searchanywhere Match anywhere in the string
635 * @param int $page Page number
636 * @param int $perpage Max per page
637 * @return array An array of users
638 * @throws moodle_exception
640 public static function search_users(int $courseid, string $search, bool $searchanywhere, int $page, int $perpage): array {
641 global $PAGE, $DB, $CFG;
643 require_once($CFG->dirroot
.'/enrol/locallib.php');
644 require_once($CFG->dirroot
.'/user/lib.php');
646 $params = self
::validate_parameters(
647 self
::search_users_parameters(),
649 'courseid' => $courseid,
651 'searchanywhere' => $searchanywhere,
653 'perpage' => $perpage
656 $context = context_course
::instance($params['courseid']);
658 self
::validate_context($context);
659 } catch (Exception
$e) {
660 $exceptionparam = new stdClass();
661 $exceptionparam->message
= $e->getMessage();
662 $exceptionparam->courseid
= $params['courseid'];
663 throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
665 course_require_view_participants($context);
667 $course = get_course($params['courseid']);
668 $manager = new course_enrolment_manager($PAGE, $course);
670 $users = $manager->search_users($params['search'],
671 $params['searchanywhere'],
676 // Add also extra user fields.
677 $requiredfields = array_merge(
678 ['id', 'fullname', 'profileimageurl', 'profileimageurlsmall'],
679 // TODO Does not support custom user profile fields (MDL-70456).
680 \core_user\fields
::get_identity_fields($context, false)
682 foreach ($users['users'] as $user) {
683 if ($userdetails = user_get_user_details($user, $course, $requiredfields)) {
684 $results[] = $userdetails;
691 * Returns description of method result value
693 * @return external_multiple_structure
695 public static function search_users_returns(): external_multiple_structure
{
697 require_once($CFG->dirroot
. '/user/externallib.php');
698 return new external_multiple_structure(core_user_external
::user_description());
702 * Returns description of method parameters
704 * @return external_function_parameters
706 public static function get_enrolled_users_parameters() {
707 return new external_function_parameters(
709 'courseid' => new external_value(PARAM_INT
, 'course id'),
710 'options' => new external_multiple_structure(
711 new external_single_structure(
713 'name' => new external_value(PARAM_ALPHANUMEXT
, 'option name'),
714 'value' => new external_value(PARAM_RAW
, 'option value')
717 * withcapability (string) return only users with this capability. This option requires \'moodle/role:review\' on the course context.
718 * groupid (integer) return only users in this group id. If the course has groups enabled and this param
719 isn\'t defined, returns all the viewable users.
720 This option requires \'moodle/site:accessallgroups\' on the course context if the
721 user doesn\'t belong to the group.
722 * onlyactive (integer) return only users with active enrolments and matching time restrictions.
723 This option requires \'moodle/course:enrolreview\' on the course context.
724 Please note that this option can\'t
725 be used together with onlysuspended (only one can be active).
726 * onlysuspended (integer) return only suspended users. This option requires
727 \'moodle/course:enrolreview\' on the course context. Please note that this option can\'t
728 be used together with onlyactive (only one can be active).
729 * userfields (\'string, string, ...\') return only the values of these user fields.
730 * limitfrom (integer) sql limit from.
731 * limitnumber (integer) maximum number of returned users.
732 * sortby (string) sort by id, firstname or lastname. For ordering like the site does, use siteorder.
733 * sortdirection (string) ASC or DESC',
740 * Get course participants details
742 * @param int $courseid course id
743 * @param array $options options {
744 * 'name' => option name
745 * 'value' => option value
747 * @return array An array of users
749 public static function get_enrolled_users($courseid, $options = []) {
750 global $CFG, $USER, $DB;
752 require_once($CFG->dirroot
. '/course/lib.php');
753 require_once($CFG->dirroot
. "/user/lib.php");
755 $params = self
::validate_parameters(
756 self
::get_enrolled_users_parameters(),
758 'courseid'=>$courseid,
762 $withcapability = '';
765 $onlysuspended = false;
771 $sortdirection = 'ASC';
772 foreach ($options as $option) {
773 switch ($option['name']) {
774 case 'withcapability':
775 $withcapability = $option['value'];
778 $groupid = (int)$option['value'];
781 $onlyactive = !empty($option['value']);
783 case 'onlysuspended':
784 $onlysuspended = !empty($option['value']);
787 $thefields = explode(',', $option['value']);
788 foreach ($thefields as $f) {
789 $userfields[] = clean_param($f, PARAM_ALPHANUMEXT
);
793 $limitfrom = clean_param($option['value'], PARAM_INT
);
796 $limitnumber = clean_param($option['value'], PARAM_INT
);
799 $sortallowedvalues = ['id', 'firstname', 'lastname', 'siteorder'];
800 if (!in_array($option['value'], $sortallowedvalues)) {
801 throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' .
802 $option['value'] . '), allowed values are: ' . implode(',', $sortallowedvalues));
804 if ($option['value'] == 'siteorder') {
805 list($sortby, $sortparams) = users_order_by_sql('us');
807 $sortby = 'us.' . $option['value'];
810 case 'sortdirection':
811 $sortdirection = strtoupper($option['value']);
812 $directionallowedvalues = ['ASC', 'DESC'];
813 if (!in_array($sortdirection, $directionallowedvalues)) {
814 throw new invalid_parameter_exception('Invalid value for sortdirection parameter
815 (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues));
821 $course = $DB->get_record('course', ['id' => $courseid], '*', MUST_EXIST
);
822 $coursecontext = context_course
::instance($courseid, IGNORE_MISSING
);
823 if ($courseid == SITEID
) {
824 $context = context_system
::instance();
826 $context = $coursecontext;
829 self
::validate_context($context);
830 } catch (Exception
$e) {
831 $exceptionparam = new stdClass();
832 $exceptionparam->message
= $e->getMessage();
833 $exceptionparam->courseid
= $params['courseid'];
834 throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
837 course_require_view_participants($context);
839 // to overwrite this parameter, you need role:review capability
840 if ($withcapability) {
841 require_capability('moodle/role:review', $coursecontext);
843 // need accessallgroups capability if you want to overwrite this option
844 if (!empty($groupid) && !groups_is_member($groupid)) {
845 require_capability('moodle/site:accessallgroups', $coursecontext);
847 // to overwrite this option, you need course:enrolereview permission
848 if ($onlyactive ||
$onlysuspended) {
849 require_capability('moodle/course:enrolreview', $coursecontext);
852 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive,
854 $ctxselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
855 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
856 $enrolledparams['contextlevel'] = CONTEXT_USER
;
859 if (empty($groupid) && groups_get_course_groupmode($course) == SEPARATEGROUPS
&&
860 !has_capability('moodle/site:accessallgroups', $coursecontext)) {
861 // Filter by groups the user can view.
862 $usergroups = groups_get_user_groups($course->id
);
863 if (!empty($usergroups['0'])) {
864 list($groupsql, $groupparams) = $DB->get_in_or_equal($usergroups['0'], SQL_PARAMS_NAMED
);
865 $groupjoin = "JOIN {groups_members} gm ON (u.id = gm.userid AND gm.groupid $groupsql)";
866 $enrolledparams = array_merge($enrolledparams, $groupparams);
868 // User doesn't belong to any group, so he can't see any user. Return an empty array.
872 $sql = "SELECT us.*, COALESCE(ul.timeaccess, 0) AS lastcourseaccess
875 SELECT DISTINCT u.id $ctxselect
876 FROM {user} u $ctxjoin $groupjoin
877 WHERE u.id IN ($enrolledsql)
879 LEFT JOIN {user_lastaccess} ul ON (ul.userid = us.id AND ul.courseid = :courseid)
880 ORDER BY $sortby $sortdirection";
881 $enrolledparams = array_merge($enrolledparams, $sortparams);
882 $enrolledparams['courseid'] = $courseid;
884 $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
886 foreach ($enrolledusers as $user) {
887 context_helper
::preload_from_record($user);
888 if ($userdetails = user_get_user_details($user, $course, $userfields)) {
889 $users[] = $userdetails;
892 $enrolledusers->close();
898 * Returns description of method result value
900 * @return \core_external\external_description
902 public static function get_enrolled_users_returns() {
903 return new external_multiple_structure(
904 new external_single_structure(
906 'id' => new external_value(PARAM_INT
, 'ID of the user'),
907 'username' => new external_value(PARAM_RAW
, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL
),
908 'firstname' => new external_value(PARAM_NOTAGS
, 'The first name(s) of the user', VALUE_OPTIONAL
),
909 'lastname' => new external_value(PARAM_NOTAGS
, 'The family name of the user', VALUE_OPTIONAL
),
910 'fullname' => new external_value(PARAM_NOTAGS
, 'The fullname of the user'),
911 'email' => new external_value(PARAM_TEXT
, 'An email address - allow email as root@localhost', VALUE_OPTIONAL
),
912 'address' => new external_value(PARAM_TEXT
, 'Postal address', VALUE_OPTIONAL
),
913 'phone1' => new external_value(PARAM_NOTAGS
, 'Phone 1', VALUE_OPTIONAL
),
914 'phone2' => new external_value(PARAM_NOTAGS
, 'Phone 2', VALUE_OPTIONAL
),
915 'department' => new external_value(PARAM_TEXT
, 'department', VALUE_OPTIONAL
),
916 'institution' => new external_value(PARAM_TEXT
, 'institution', VALUE_OPTIONAL
),
917 'idnumber' => new external_value(PARAM_RAW
, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL
),
918 'interests' => new external_value(PARAM_TEXT
, 'user interests (separated by commas)', VALUE_OPTIONAL
),
919 'firstaccess' => new external_value(PARAM_INT
, 'first access to the site (0 if never)', VALUE_OPTIONAL
),
920 'lastaccess' => new external_value(PARAM_INT
, 'last access to the site (0 if never)', VALUE_OPTIONAL
),
921 'lastcourseaccess' => new external_value(PARAM_INT
, 'last access to the course (0 if never)', VALUE_OPTIONAL
),
922 'description' => new external_value(PARAM_RAW
, 'User profile description', VALUE_OPTIONAL
),
923 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL
),
924 'city' => new external_value(PARAM_NOTAGS
, 'Home city of the user', VALUE_OPTIONAL
),
925 'country' => new external_value(PARAM_ALPHA
, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
926 'profileimageurlsmall' => new external_value(PARAM_URL
, 'User image profile URL - small version', VALUE_OPTIONAL
),
927 'profileimageurl' => new external_value(PARAM_URL
, 'User image profile URL - big version', VALUE_OPTIONAL
),
928 'customfields' => new external_multiple_structure(
929 new external_single_structure(
931 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The type of the custom field - text field, checkbox...'),
932 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
933 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
934 'shortname' => new external_value(PARAM_RAW
, 'The shortname of the custom field - to be able to build the field class in the code'),
936 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL
),
937 'groups' => new external_multiple_structure(
938 new external_single_structure(
940 'id' => new external_value(PARAM_INT
, 'group id'),
941 'name' => new external_value(PARAM_RAW
, 'group name'),
942 'description' => new external_value(PARAM_RAW
, 'group description'),
943 'descriptionformat' => new external_format_value('description'),
945 ), 'user groups', VALUE_OPTIONAL
),
946 'roles' => new external_multiple_structure(
947 new external_single_structure(
949 'roleid' => new external_value(PARAM_INT
, 'role id'),
950 'name' => new external_value(PARAM_RAW
, 'role name'),
951 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'role shortname'),
952 'sortorder' => new external_value(PARAM_INT
, 'role sortorder')
954 ), 'user roles', VALUE_OPTIONAL
),
955 'preferences' => new external_multiple_structure(
956 new external_single_structure(
958 'name' => new external_value(PARAM_RAW
, 'The name of the preferences'),
959 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
961 ), 'User preferences', VALUE_OPTIONAL
),
962 'enrolledcourses' => new external_multiple_structure(
963 new external_single_structure(
965 'id' => new external_value(PARAM_INT
, 'Id of the course'),
966 'fullname' => new external_value(PARAM_RAW
, 'Fullname of the course'),
967 'shortname' => new external_value(PARAM_RAW
, 'Shortname of the course')
969 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
)
976 * Returns description of get_course_enrolment_methods() parameters
978 * @return external_function_parameters
980 public static function get_course_enrolment_methods_parameters() {
981 return new external_function_parameters(
983 'courseid' => new external_value(PARAM_INT
, 'Course id')
989 * Get list of active course enrolment methods for current user.
991 * @param int $courseid
992 * @return array of course enrolment methods
993 * @throws moodle_exception
995 public static function get_course_enrolment_methods($courseid) {
998 $params = self
::validate_parameters(self
::get_course_enrolment_methods_parameters(), array('courseid' => $courseid));
999 self
::validate_context(context_system
::instance());
1001 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST
);
1002 if (!core_course_category
::can_view_course_info($course) && !can_access_course($course)) {
1003 throw new moodle_exception('coursehidden');
1007 $enrolinstances = enrol_get_instances($params['courseid'], true);
1008 foreach ($enrolinstances as $enrolinstance) {
1009 if ($enrolplugin = enrol_get_plugin($enrolinstance->enrol
)) {
1010 if ($instanceinfo = $enrolplugin->get_enrol_info($enrolinstance)) {
1011 $result[] = (array) $instanceinfo;
1019 * Returns description of get_course_enrolment_methods() result value
1021 * @return \core_external\external_description
1023 public static function get_course_enrolment_methods_returns() {
1024 return new external_multiple_structure(
1025 new external_single_structure(
1027 'id' => new external_value(PARAM_INT
, 'id of course enrolment instance'),
1028 'courseid' => new external_value(PARAM_INT
, 'id of course'),
1029 'type' => new external_value(PARAM_PLUGIN
, 'type of enrolment plugin'),
1030 'name' => new external_value(PARAM_RAW
, 'name of enrolment plugin'),
1031 'status' => new external_value(PARAM_RAW
, 'status of enrolment plugin'),
1032 'wsfunction' => new external_value(PARAM_ALPHANUMEXT
, 'webservice function to get more information', VALUE_OPTIONAL
),
1039 * Returns description of submit_user_enrolment_form parameters.
1041 * @return external_function_parameters.
1043 public static function submit_user_enrolment_form_parameters() {
1044 return new external_function_parameters([
1045 'formdata' => new external_value(PARAM_RAW
, 'The data from the event form'),
1050 * External function that handles the user enrolment form submission.
1052 * @param string $formdata The user enrolment form data in s URI encoded param string
1053 * @return array An array consisting of the processing result and error flag, if available
1055 public static function submit_user_enrolment_form($formdata) {
1056 global $CFG, $DB, $PAGE;
1058 // Parameter validation.
1059 $params = self
::validate_parameters(self
::submit_user_enrolment_form_parameters(), ['formdata' => $formdata]);
1062 parse_str($params['formdata'], $data);
1064 $userenrolment = $DB->get_record('user_enrolments', ['id' => $data['ue']], '*', MUST_EXIST
);
1065 $instance = $DB->get_record('enrol', ['id' => $userenrolment->enrolid
], '*', MUST_EXIST
);
1066 $plugin = enrol_get_plugin($instance->enrol
);
1067 $course = get_course($instance->courseid
);
1068 $context = context_course
::instance($course->id
);
1069 self
::validate_context($context);
1071 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
1073 'ue' => $userenrolment,
1075 'enrolinstancename' => $plugin->get_instance_name($instance)
1077 $mform = new enrol_user_enrolment_form(null, $customformdata, 'post', '', null, true, $data);
1079 if ($validateddata = $mform->get_data()) {
1080 if (!empty($validateddata->duration
) && $validateddata->timeend
== 0) {
1081 $validateddata->timeend
= $validateddata->timestart +
$validateddata->duration
;
1083 require_once($CFG->dirroot
. '/enrol/locallib.php');
1084 $manager = new course_enrolment_manager($PAGE, $course);
1085 $result = $manager->edit_enrolment($userenrolment, $validateddata);
1087 return ['result' => $result];
1089 return ['result' => false, 'validationerror' => true];
1094 * Returns description of submit_user_enrolment_form() result value
1096 * @return \core_external\external_description
1098 public static function submit_user_enrolment_form_returns() {
1099 return new external_single_structure([
1100 'result' => new external_value(PARAM_BOOL
, 'True if the user\'s enrolment was successfully updated'),
1101 'validationerror' => new external_value(PARAM_BOOL
, 'Indicates invalid form data', VALUE_DEFAULT
, false),
1106 * Returns description of unenrol_user_enrolment() parameters
1108 * @return external_function_parameters
1110 public static function unenrol_user_enrolment_parameters() {
1111 return new external_function_parameters(
1113 'ueid' => new external_value(PARAM_INT
, 'User enrolment ID')
1119 * External function that unenrols a given user enrolment.
1121 * @param int $ueid The user enrolment ID.
1122 * @return array An array consisting of the processing result, errors.
1124 public static function unenrol_user_enrolment($ueid) {
1125 global $CFG, $DB, $PAGE;
1127 $params = self
::validate_parameters(self
::unenrol_user_enrolment_parameters(), [
1134 $userenrolment = $DB->get_record('user_enrolments', ['id' => $params['ueid']], '*');
1135 if ($userenrolment) {
1136 $userid = $userenrolment->userid
;
1137 $enrolid = $userenrolment->enrolid
;
1138 $enrol = $DB->get_record('enrol', ['id' => $enrolid], '*', MUST_EXIST
);
1139 $courseid = $enrol->courseid
;
1140 $course = get_course($courseid);
1141 $context = context_course
::instance($course->id
);
1142 self
::validate_context($context);
1144 $validationerrors['invalidrequest'] = get_string('invalidrequest', 'enrol');
1147 // If the userenrolment exists, unenrol the user.
1148 if (!isset($validationerrors)) {
1149 require_once($CFG->dirroot
. '/enrol/locallib.php');
1150 $manager = new course_enrolment_manager($PAGE, $course);
1151 $result = $manager->unenrol_user($userenrolment);
1153 foreach ($validationerrors as $key => $errormessage) {
1154 $errors[] = (object)[
1156 'message' => $errormessage
1162 'result' => $result,
1163 'errors' => $errors,
1168 * Returns description of unenrol_user_enrolment() result value
1170 * @return \core_external\external_description
1172 public static function unenrol_user_enrolment_returns() {
1173 return new external_single_structure(
1175 'result' => new external_value(PARAM_BOOL
, 'True if the user\'s enrolment was successfully updated'),
1176 'errors' => new external_multiple_structure(
1177 new external_single_structure(
1179 'key' => new external_value(PARAM_TEXT
, 'The data that failed the validation'),
1180 'message' => new external_value(PARAM_TEXT
, 'The error message'),
1182 ), 'List of validation errors'
1190 * Role external functions
1192 * @package core_role
1193 * @category external
1194 * @copyright 2011 Jerome Mouneyrac
1195 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1198 class core_role_external
extends external_api
{
1201 * Returns description of method parameters
1203 * @return external_function_parameters
1205 public static function assign_roles_parameters() {
1206 return new external_function_parameters(
1208 'assignments' => new external_multiple_structure(
1209 new external_single_structure(
1211 'roleid' => new external_value(PARAM_INT
, 'Role to assign to the user'),
1212 'userid' => new external_value(PARAM_INT
, 'The user that is going to be assigned'),
1213 'contextid' => new external_value(PARAM_INT
, 'The context to assign the user role in', VALUE_OPTIONAL
),
1214 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level to assign the user role in
1215 (block, course, coursecat, system, user, module)', VALUE_OPTIONAL
),
1216 'instanceid' => new external_value(PARAM_INT
, 'The Instance id of item where the role needs to be assigned', VALUE_OPTIONAL
),
1225 * Manual role assignments to users
1227 * @param array $assignments An array of manual role assignment
1229 public static function assign_roles($assignments) {
1232 // Do basic automatic PARAM checks on incoming data, using params description
1233 // If any problems are found then exceptions are thrown with helpful error messages
1234 $params = self
::validate_parameters(self
::assign_roles_parameters(), array('assignments'=>$assignments));
1236 $transaction = $DB->start_delegated_transaction();
1238 foreach ($params['assignments'] as $assignment) {
1239 // Ensure correct context level with a instance id or contextid is passed.
1240 $context = self
::get_context_from_params($assignment);
1242 // Ensure the current user is allowed to run this function in the enrolment context.
1243 self
::validate_context($context);
1244 require_capability('moodle/role:assign', $context);
1246 // throw an exception if user is not able to assign the role in this context
1247 $roles = get_assignable_roles($context, ROLENAME_SHORT
);
1249 if (!array_key_exists($assignment['roleid'], $roles)) {
1250 throw new invalid_parameter_exception('Can not assign roleid='.$assignment['roleid'].' in contextid='.$assignment['contextid']);
1253 role_assign($assignment['roleid'], $assignment['userid'], $context->id
);
1256 $transaction->allow_commit();
1260 * Returns description of method result value
1264 public static function assign_roles_returns() {
1270 * Returns description of method parameters
1272 * @return external_function_parameters
1274 public static function unassign_roles_parameters() {
1275 return new external_function_parameters(
1277 'unassignments' => new external_multiple_structure(
1278 new external_single_structure(
1280 'roleid' => new external_value(PARAM_INT
, 'Role to assign to the user'),
1281 'userid' => new external_value(PARAM_INT
, 'The user that is going to be assigned'),
1282 'contextid' => new external_value(PARAM_INT
, 'The context to unassign the user role from', VALUE_OPTIONAL
),
1283 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level to unassign the user role in
1284 + (block, course, coursecat, system, user, module)', VALUE_OPTIONAL
),
1285 'instanceid' => new external_value(PARAM_INT
, 'The Instance id of item where the role needs to be unassigned', VALUE_OPTIONAL
),
1294 * Unassign roles from users
1296 * @param array $unassignments An array of unassignment
1298 public static function unassign_roles($unassignments) {
1301 // Do basic automatic PARAM checks on incoming data, using params description
1302 // If any problems are found then exceptions are thrown with helpful error messages
1303 $params = self
::validate_parameters(self
::unassign_roles_parameters(), array('unassignments'=>$unassignments));
1305 $transaction = $DB->start_delegated_transaction();
1307 foreach ($params['unassignments'] as $unassignment) {
1308 // Ensure the current user is allowed to run this function in the unassignment context
1309 $context = self
::get_context_from_params($unassignment);
1310 self
::validate_context($context);
1311 require_capability('moodle/role:assign', $context);
1313 // throw an exception if user is not able to unassign the role in this context
1314 $roles = get_assignable_roles($context, ROLENAME_SHORT
);
1315 if (!array_key_exists($unassignment['roleid'], $roles)) {
1316 throw new invalid_parameter_exception('Can not unassign roleid='.$unassignment['roleid'].' in contextid='.$unassignment['contextid']);
1319 role_unassign($unassignment['roleid'], $unassignment['userid'], $context->id
);
1322 $transaction->allow_commit();
1326 * Returns description of method result value
1330 public static function unassign_roles_returns() {