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) {
89 require_once($CFG->dirroot . "/user/lib.php");
91 if (empty($coursecapabilities)) {
92 throw new invalid_parameter_exception('Parameter can not be empty');
94 $params = self::validate_parameters(self::get_enrolled_users_with_capability_parameters(),
95 array ('coursecapabilities' => $coursecapabilities, 'options'=>$options));
100 $userfields = array();
103 foreach ($params['options'] as $option) {
104 switch ($option['name']) {
106 $groupid = (int)$option['value'];
109 $onlyactive = !empty($option['value']);
112 $thefields = explode(',', $option['value']);
113 foreach ($thefields as $f) {
114 $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
118 $limitfrom = clean_param($option['value'], PARAM_INT);
121 $limitnumber = clean_param($option['value'], PARAM_INT);
126 foreach ($params['coursecapabilities'] as $coursecapability) {
127 $courseid = $coursecapability['courseid'];
128 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
129 $coursecontext = context_course::instance($courseid);
130 if (!$coursecontext) {
131 throw new moodle_exception('cannotfindcourse', 'error', '', null,
132 'The course id ' . $courseid . ' doesn\'t exist.');
134 if ($courseid == SITEID) {
135 $context = context_system::instance();
137 $context = $coursecontext;
140 self::validate_context($context);
141 } catch (Exception $e) {
142 $exceptionparam = new stdClass();
143 $exceptionparam->message = $e->getMessage();
144 $exceptionparam->courseid = $params['courseid'];
145 throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
148 if ($courseid == SITEID) {
149 require_capability('moodle/site:viewparticipants', $context);
151 require_capability('moodle/course:viewparticipants', $context);
153 // The accessallgroups capability is needed to use this option.
154 if (!empty($groupid) && groups_is_member($groupid)) {
155 require_capability('moodle/site:accessallgroups', $coursecontext);
157 // The course:enrolereview capability is needed to use this option.
159 require_capability('moodle/course:enrolreview', $coursecontext);
162 // To see the permissions of others role:review capability is required.
163 require_capability('moodle/role:review', $coursecontext);
164 foreach ($coursecapability['capabilities'] as $capability) {
165 $courseusers['courseid'] = $courseid;
166 $courseusers['capability'] = $capability;
168 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $capability, $groupid, $onlyactive);
170 $sql = "SELECT u.* FROM {user} u WHERE u.id IN ($enrolledsql) ORDER BY u.id ASC";
172 $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
174 foreach ($enrolledusers as $courseuser) {
175 if ($userdetails = user_get_user_details($courseuser, $course, $userfields)) {
176 $users[] = $userdetails;
179 $enrolledusers->close();
180 $courseusers['users'] = $users;
181 $result[] = $courseusers;
188 * Returns description of method result value
190 * @return external_multiple_structure
193 public static function get_enrolled_users_with_capability_returns() {
194 return new external_multiple_structure( new external_single_structure (
196 'courseid' => new external_value(PARAM_INT, 'Course ID number in the Moodle course table'),
197 'capability' => new external_value(PARAM_CAPABILITY, 'Capability name'),
198 'users' => new external_multiple_structure(
199 new external_single_structure(
201 'id' => new external_value(PARAM_INT, 'ID of the user'),
202 'username' => new external_value(PARAM_RAW, 'Username', VALUE_OPTIONAL),
203 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
204 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
205 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
206 'email' => new external_value(PARAM_TEXT, 'Email address', VALUE_OPTIONAL),
207 'address' => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
208 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
209 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
210 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
211 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
212 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
213 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
214 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
215 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
216 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
217 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
218 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
219 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
220 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
221 'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
222 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
223 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
224 'country' => new external_value(PARAM_ALPHA, 'Country code of the user, such as AU or CZ', VALUE_OPTIONAL),
225 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small', VALUE_OPTIONAL),
226 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big', VALUE_OPTIONAL),
227 'customfields' => new external_multiple_structure(
228 new external_single_structure(
230 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field'),
231 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
232 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
233 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field'),
235 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
236 'groups' => new external_multiple_structure(
237 new external_single_structure(
239 'id' => new external_value(PARAM_INT, 'group id'),
240 'name' => new external_value(PARAM_RAW, 'group name'),
241 'description' => new external_value(PARAM_RAW, 'group description'),
243 ), 'user groups', VALUE_OPTIONAL),
244 'roles' => new external_multiple_structure(
245 new external_single_structure(
247 'roleid' => new external_value(PARAM_INT, 'role id'),
248 'name' => new external_value(PARAM_RAW, 'role name'),
249 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
250 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
252 ), 'user roles', VALUE_OPTIONAL),
253 'preferences' => new external_multiple_structure(
254 new external_single_structure(
256 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
257 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
259 ), 'User preferences', VALUE_OPTIONAL),
260 'enrolledcourses' => new external_multiple_structure(
261 new external_single_structure(
263 'id' => new external_value(PARAM_INT, 'Id of the course'),
264 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
265 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
267 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
269 ), 'List of users that are enrolled in the course and have the specified capability'),
276 * Returns description of method parameters
278 * @return external_function_parameters
280 public static function get_users_courses_parameters() {
281 return new external_function_parameters(
283 'userid' => new external_value(PARAM_INT, 'user id'),
289 * Get list of courses user is enrolled in (only active enrolments are returned).
290 * Please note the current user must be able to access the course, otherwise the course is not included.
293 * @return array of courses
295 public static function get_users_courses($userid) {
298 // Do basic automatic PARAM checks on incoming data, using params description
299 // If any problems are found then exceptions are thrown with helpful error messages
300 $params = self::validate_parameters(self::get_users_courses_parameters(), array('userid'=>$userid));
302 $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible,
303 summary, summaryformat, format, showgrades, lang, enablecompletion, category, startdate, enddate');
306 foreach ($courses as $course) {
307 $context = context_course::instance($course->id, IGNORE_MISSING);
309 self::validate_context($context);
310 } catch (Exception $e) {
311 // current user can not access this course, sorry we can not disclose who is enrolled in this course!
315 if ($userid != $USER->id and !has_capability('moodle/course:viewparticipants', $context)) {
316 // we need capability to view participants
320 list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context);
321 $enrolledsql = "SELECT COUNT('x') FROM ($enrolledsqlselect) enrolleduserids";
322 $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams);
324 list($course->summary, $course->summaryformat) =
325 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', null);
326 $course->fullname = external_format_string($course->fullname, $context->id);
327 $course->shortname = external_format_string($course->shortname, $context->id);
330 if ($course->enablecompletion) {
331 $progress = \core_completion\progress::get_course_progress_percentage($course);
336 'shortname' => $course->shortname,
337 'fullname' => $course->fullname,
338 'idnumber' => $course->idnumber,
339 'visible' => $course->visible,
340 'enrolledusercount' => $enrolledusercount,
341 'summary' => $course->summary,
342 'summaryformat' => $course->summaryformat,
343 'format' => $course->format,
344 'showgrades' => $course->showgrades,
345 'lang' => $course->lang,
346 'enablecompletion' => $course->enablecompletion,
347 'category' => $course->category,
348 'progress' => $progress,
349 'startdate' => $course->startdate,
350 'enddate' => $course->enddate,
358 * Returns description of method result value
360 * @return external_description
362 public static function get_users_courses_returns() {
363 return new external_multiple_structure(
364 new external_single_structure(
366 'id' => new external_value(PARAM_INT, 'id of course'),
367 'shortname' => new external_value(PARAM_RAW, 'short name of course'),
368 'fullname' => new external_value(PARAM_RAW, 'long name of course'),
369 'enrolledusercount' => new external_value(PARAM_INT, 'Number of enrolled users in this course'),
370 'idnumber' => new external_value(PARAM_RAW, 'id number of course'),
371 'visible' => new external_value(PARAM_INT, '1 means visible, 0 means hidden course'),
372 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
373 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
374 'format' => new external_value(PARAM_PLUGIN, 'course format: weeks, topics, social, site', VALUE_OPTIONAL),
375 'showgrades' => new external_value(PARAM_BOOL, 'true if grades are shown, otherwise false', VALUE_OPTIONAL),
376 'lang' => new external_value(PARAM_LANG, 'forced course language', VALUE_OPTIONAL),
377 'enablecompletion' => new external_value(PARAM_BOOL, 'true if completion is enabled, otherwise false',
379 'category' => new external_value(PARAM_INT, 'course category id', VALUE_OPTIONAL),
380 'progress' => new external_value(PARAM_FLOAT, 'Progress percentage', VALUE_OPTIONAL),
381 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
382 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
389 * Returns description of method parameters value
391 * @return external_description
393 public static function get_potential_users_parameters() {
394 return new external_function_parameters(
396 'courseid' => new external_value(PARAM_INT, 'course id'),
397 'enrolid' => new external_value(PARAM_INT, 'enrolment id'),
398 'search' => new external_value(PARAM_RAW, 'query'),
399 'searchanywhere' => new external_value(PARAM_BOOL, 'find a match anywhere, or only at the beginning'),
400 'page' => new external_value(PARAM_INT, 'Page number'),
401 'perpage' => new external_value(PARAM_INT, 'Number per page'),
407 * Get potential users.
409 * @param int $courseid Course id
410 * @param int $enrolid Enrolment id
411 * @param string $search The query
412 * @param boolean $searchanywhere Match anywhere in the string
413 * @param int $page Page number
414 * @param int $perpage Max per page
415 * @return array An array of users
417 public static function get_potential_users($courseid, $enrolid, $search, $searchanywhere, $page, $perpage) {
418 global $PAGE, $DB, $CFG;
420 require_once($CFG->dirroot.'/enrol/locallib.php');
421 require_once($CFG->dirroot.'/user/lib.php');
423 $params = self::validate_parameters(
424 self::get_potential_users_parameters(),
426 'courseid' => $courseid,
427 'enrolid' => $enrolid,
429 'searchanywhere' => $searchanywhere,
431 'perpage' => $perpage
434 $context = context_course::instance($params['courseid']);
436 self::validate_context($context);
437 } catch (Exception $e) {
438 $exceptionparam = new stdClass();
439 $exceptionparam->message = $e->getMessage();
440 $exceptionparam->courseid = $params['courseid'];
441 throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
443 require_capability('moodle/course:enrolreview', $context);
445 $course = $DB->get_record('course', array('id' => $params['courseid']));
446 $manager = new course_enrolment_manager($PAGE, $course);
448 $users = $manager->get_potential_users($params['enrolid'],
450 $params['searchanywhere'],
455 $requiredfields = ['id', 'fullname', 'profileimageurl', 'profileimageurlsmall'];
456 foreach ($users['users'] as $id => $user) {
457 // Note: We pass the course here to validate that the current user can at least view user details in this course.
458 // The user we are looking at is not in this course yet though - but we only fetch the minimal set of
459 // user records, and the user has been validated to have course:enrolreview in this course. Otherwise
460 // there is no way to find users who aren't in the course in order to enrol them.
461 if ($userdetails = user_get_user_details($user, $course, $requiredfields)) {
462 $results[] = $userdetails;
469 * Returns description of method result value
471 * @return external_description
473 public static function get_potential_users_returns() {
475 require_once($CFG->dirroot . '/user/externallib.php');
476 return new external_multiple_structure(core_user_external::user_description());
480 * Returns description of method parameters
482 * @return external_function_parameters
484 public static function get_enrolled_users_parameters() {
485 return new external_function_parameters(
487 'courseid' => new external_value(PARAM_INT, 'course id'),
488 'options' => new external_multiple_structure(
489 new external_single_structure(
491 'name' => new external_value(PARAM_ALPHANUMEXT, 'option name'),
492 'value' => new external_value(PARAM_RAW, 'option value')
495 * withcapability (string) return only users with this capability. This option requires \'moodle/role:review\' on the course context.
496 * groupid (integer) return only users in this group id. If the course has groups enabled and this param
497 isn\'t defined, returns all the viewable users.
498 This option requires \'moodle/site:accessallgroups\' on the course context if the
499 user doesn\'t belong to the group.
500 * onlyactive (integer) return only users with active enrolments and matching time restrictions. This option requires \'moodle/course:enrolreview\' on the course context.
501 * userfields (\'string, string, ...\') return only the values of these user fields.
502 * limitfrom (integer) sql limit from.
503 * limitnumber (integer) maximum number of returned users.
504 * sortby (string) sort by id, firstname or lastname. For ordering like the site does, use siteorder.
505 * sortdirection (string) ASC or DESC',
506 VALUE_DEFAULT, array()),
512 * Get course participants details
514 * @param int $courseid course id
515 * @param array $options options {
516 * 'name' => option name
517 * 'value' => option value
519 * @return array An array of users
521 public static function get_enrolled_users($courseid, $options = array()) {
522 global $CFG, $USER, $DB;
523 require_once($CFG->dirroot . "/user/lib.php");
525 $params = self::validate_parameters(
526 self::get_enrolled_users_parameters(),
528 'courseid'=>$courseid,
532 $withcapability = '';
535 $userfields = array();
539 $sortparams = array();
540 $sortdirection = 'ASC';
541 foreach ($options as $option) {
542 switch ($option['name']) {
543 case 'withcapability':
544 $withcapability = $option['value'];
547 $groupid = (int)$option['value'];
550 $onlyactive = !empty($option['value']);
553 $thefields = explode(',', $option['value']);
554 foreach ($thefields as $f) {
555 $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
559 $limitfrom = clean_param($option['value'], PARAM_INT);
562 $limitnumber = clean_param($option['value'], PARAM_INT);
565 $sortallowedvalues = array('id', 'firstname', 'lastname', 'siteorder');
566 if (!in_array($option['value'], $sortallowedvalues)) {
567 throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $option['value'] . '),' .
568 'allowed values are: ' . implode(',', $sortallowedvalues));
570 if ($option['value'] == 'siteorder') {
571 list($sortby, $sortparams) = users_order_by_sql('us');
573 $sortby = 'us.' . $option['value'];
576 case 'sortdirection':
577 $sortdirection = strtoupper($option['value']);
578 $directionallowedvalues = array('ASC', 'DESC');
579 if (!in_array($sortdirection, $directionallowedvalues)) {
580 throw new invalid_parameter_exception('Invalid value for sortdirection parameter
581 (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues));
587 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
588 $coursecontext = context_course::instance($courseid, IGNORE_MISSING);
589 if ($courseid == SITEID) {
590 $context = context_system::instance();
592 $context = $coursecontext;
595 self::validate_context($context);
596 } catch (Exception $e) {
597 $exceptionparam = new stdClass();
598 $exceptionparam->message = $e->getMessage();
599 $exceptionparam->courseid = $params['courseid'];
600 throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
603 if ($courseid == SITEID) {
604 require_capability('moodle/site:viewparticipants', $context);
606 require_capability('moodle/course:viewparticipants', $context);
608 // to overwrite this parameter, you need role:review capability
609 if ($withcapability) {
610 require_capability('moodle/role:review', $coursecontext);
612 // need accessallgroups capability if you want to overwrite this option
613 if (!empty($groupid) && !groups_is_member($groupid)) {
614 require_capability('moodle/site:accessallgroups', $coursecontext);
616 // to overwrite this option, you need course:enrolereview permission
618 require_capability('moodle/course:enrolreview', $coursecontext);
621 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
622 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
623 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
624 $enrolledparams['contextlevel'] = CONTEXT_USER;
627 if (empty($groupid) && groups_get_course_groupmode($course) == SEPARATEGROUPS &&
628 !has_capability('moodle/site:accessallgroups', $coursecontext)) {
629 // Filter by groups the user can view.
630 $usergroups = groups_get_user_groups($course->id);
631 if (!empty($usergroups['0'])) {
632 list($groupsql, $groupparams) = $DB->get_in_or_equal($usergroups['0'], SQL_PARAMS_NAMED);
633 $groupjoin = "JOIN {groups_members} gm ON (u.id = gm.userid AND gm.groupid $groupsql)";
634 $enrolledparams = array_merge($enrolledparams, $groupparams);
636 // User doesn't belong to any group, so he can't see any user. Return an empty array.
643 SELECT DISTINCT u.id $ctxselect
644 FROM {user} u $ctxjoin $groupjoin
645 WHERE u.id IN ($enrolledsql)
647 ORDER BY $sortby $sortdirection";
648 $enrolledparams = array_merge($enrolledparams, $sortparams);
649 $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
651 foreach ($enrolledusers as $user) {
652 context_helper::preload_from_record($user);
653 if ($userdetails = user_get_user_details($user, $course, $userfields)) {
654 $users[] = $userdetails;
657 $enrolledusers->close();
663 * Returns description of method result value
665 * @return external_description
667 public static function get_enrolled_users_returns() {
668 return new external_multiple_structure(
669 new external_single_structure(
671 'id' => new external_value(PARAM_INT, 'ID of the user'),
672 'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL),
673 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
674 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
675 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
676 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
677 'address' => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL),
678 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
679 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
680 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
681 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
682 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
683 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
684 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
685 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
686 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
687 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
688 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
689 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
690 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
691 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
692 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
693 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
694 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
695 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
696 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version', VALUE_OPTIONAL),
697 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version', VALUE_OPTIONAL),
698 'customfields' => new external_multiple_structure(
699 new external_single_structure(
701 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
702 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
703 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
704 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
706 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
707 'groups' => new external_multiple_structure(
708 new external_single_structure(
710 'id' => new external_value(PARAM_INT, 'group id'),
711 'name' => new external_value(PARAM_RAW, 'group name'),
712 'description' => new external_value(PARAM_RAW, 'group description'),
713 'descriptionformat' => new external_format_value('description'),
715 ), 'user groups', VALUE_OPTIONAL),
716 'roles' => new external_multiple_structure(
717 new external_single_structure(
719 'roleid' => new external_value(PARAM_INT, 'role id'),
720 'name' => new external_value(PARAM_RAW, 'role name'),
721 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
722 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
724 ), 'user roles', VALUE_OPTIONAL),
725 'preferences' => new external_multiple_structure(
726 new external_single_structure(
728 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
729 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
731 ), 'User preferences', VALUE_OPTIONAL),
732 'enrolledcourses' => new external_multiple_structure(
733 new external_single_structure(
735 'id' => new external_value(PARAM_INT, 'Id of the course'),
736 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
737 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
739 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
746 * Returns description of get_course_enrolment_methods() parameters
748 * @return external_function_parameters
750 public static function get_course_enrolment_methods_parameters() {
751 return new external_function_parameters(
753 'courseid' => new external_value(PARAM_INT, 'Course id')
759 * Get list of active course enrolment methods for current user.
761 * @param int $courseid
762 * @return array of course enrolment methods
763 * @throws moodle_exception
765 public static function get_course_enrolment_methods($courseid) {
768 $params = self::validate_parameters(self::get_course_enrolment_methods_parameters(), array('courseid' => $courseid));
769 self::validate_context(context_system::instance());
771 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
772 $context = context_course::instance($course->id);
773 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) {
774 throw new moodle_exception('coursehidden');
778 $enrolinstances = enrol_get_instances($params['courseid'], true);
779 foreach ($enrolinstances as $enrolinstance) {
780 if ($enrolplugin = enrol_get_plugin($enrolinstance->enrol)) {
781 if ($instanceinfo = $enrolplugin->get_enrol_info($enrolinstance)) {
782 $result[] = (array) $instanceinfo;
790 * Returns description of get_course_enrolment_methods() result value
792 * @return external_description
794 public static function get_course_enrolment_methods_returns() {
795 return new external_multiple_structure(
796 new external_single_structure(
798 'id' => new external_value(PARAM_INT, 'id of course enrolment instance'),
799 'courseid' => new external_value(PARAM_INT, 'id of course'),
800 'type' => new external_value(PARAM_PLUGIN, 'type of enrolment plugin'),
801 'name' => new external_value(PARAM_RAW, 'name of enrolment plugin'),
802 'status' => new external_value(PARAM_RAW, 'status of enrolment plugin'),
803 'wsfunction' => new external_value(PARAM_ALPHANUMEXT, 'webservice function to get more information', VALUE_OPTIONAL),
811 * Role external functions
815 * @copyright 2011 Jerome Mouneyrac
816 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
819 class core_role_external extends external_api {
822 * Returns description of method parameters
824 * @return external_function_parameters
826 public static function assign_roles_parameters() {
827 return new external_function_parameters(
829 'assignments' => new external_multiple_structure(
830 new external_single_structure(
832 'roleid' => new external_value(PARAM_INT, 'Role to assign to the user'),
833 'userid' => new external_value(PARAM_INT, 'The user that is going to be assigned'),
834 'contextid' => new external_value(PARAM_INT, 'The context to assign the user role in', VALUE_OPTIONAL),
835 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level to assign the user role in
836 (block, course, coursecat, system, user, module)', VALUE_OPTIONAL),
837 'instanceid' => new external_value(PARAM_INT, 'The Instance id of item where the role needs to be assigned', VALUE_OPTIONAL),
846 * Manual role assignments to users
848 * @param array $assignments An array of manual role assignment
850 public static function assign_roles($assignments) {
853 // Do basic automatic PARAM checks on incoming data, using params description
854 // If any problems are found then exceptions are thrown with helpful error messages
855 $params = self::validate_parameters(self::assign_roles_parameters(), array('assignments'=>$assignments));
857 $transaction = $DB->start_delegated_transaction();
859 foreach ($params['assignments'] as $assignment) {
860 // Ensure correct context level with a instance id or contextid is passed.
861 $context = self::get_context_from_params($assignment);
863 // Ensure the current user is allowed to run this function in the enrolment context.
864 self::validate_context($context);
865 require_capability('moodle/role:assign', $context);
867 // throw an exception if user is not able to assign the role in this context
868 $roles = get_assignable_roles($context, ROLENAME_SHORT);
870 if (!array_key_exists($assignment['roleid'], $roles)) {
871 throw new invalid_parameter_exception('Can not assign roleid='.$assignment['roleid'].' in contextid='.$assignment['contextid']);
874 role_assign($assignment['roleid'], $assignment['userid'], $context->id);
877 $transaction->allow_commit();
881 * Returns description of method result value
885 public static function assign_roles_returns() {
891 * Returns description of method parameters
893 * @return external_function_parameters
895 public static function unassign_roles_parameters() {
896 return new external_function_parameters(
898 'unassignments' => new external_multiple_structure(
899 new external_single_structure(
901 'roleid' => new external_value(PARAM_INT, 'Role to assign to the user'),
902 'userid' => new external_value(PARAM_INT, 'The user that is going to be assigned'),
903 'contextid' => new external_value(PARAM_INT, 'The context to unassign the user role from', VALUE_OPTIONAL),
904 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level to unassign the user role in
905 + (block, course, coursecat, system, user, module)', VALUE_OPTIONAL),
906 'instanceid' => new external_value(PARAM_INT, 'The Instance id of item where the role needs to be unassigned', VALUE_OPTIONAL),
915 * Unassign roles from users
917 * @param array $unassignments An array of unassignment
919 public static function unassign_roles($unassignments) {
922 // Do basic automatic PARAM checks on incoming data, using params description
923 // If any problems are found then exceptions are thrown with helpful error messages
924 $params = self::validate_parameters(self::unassign_roles_parameters(), array('unassignments'=>$unassignments));
926 $transaction = $DB->start_delegated_transaction();
928 foreach ($params['unassignments'] as $unassignment) {
929 // Ensure the current user is allowed to run this function in the unassignment context
930 $context = self::get_context_from_params($unassignment);
931 self::validate_context($context);
932 require_capability('moodle/role:assign', $context);
934 // throw an exception if user is not able to unassign the role in this context
935 $roles = get_assignable_roles($context, ROLENAME_SHORT);
936 if (!array_key_exists($unassignment['roleid'], $roles)) {
937 throw new invalid_parameter_exception('Can not unassign roleid='.$unassignment['roleid'].' in contextid='.$unassignment['contextid']);
940 role_unassign($unassignment['roleid'], $unassignment['userid'], $context->id);
943 $transaction->allow_commit();
947 * Returns description of method result value
951 public static function unassign_roles_returns() {