3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // 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 2009 Moodle Pty Ltd (http://moodle.com)
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");
37 class core_enrol_external extends external_api {
40 * Returns description of method parameters
41 * @return external_function_parameters
43 public static function get_users_courses_parameters() {
44 return new external_function_parameters(
46 'userid' => new external_value(PARAM_INT, 'user id'),
52 * Get list of courses user is enrolled in (only active enrolments are returned).
54 * Please note the current user must be able to access the course, otherwise the course is not included.
57 * @return array of courses
59 public static function get_users_courses($userid) {
62 // Do basic automatic PARAM checks on incoming data, using params description
63 // If any problems are found then exceptions are thrown with helpful error messages
64 $params = self::validate_parameters(self::get_users_courses_parameters(), array('userid'=>$userid));
66 $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible');
69 foreach ($courses as $course) {
70 $context = get_context_instance(CONTEXT_COURSE, $course->id);
72 self::validate_context($context);
73 } catch (Exception $e) {
74 // current user can not access this course, sorry we can not disclose who is enrolled in this course!
78 if ($userid != $USER->id and !has_capability('moodle/course:viewparticipants', $context)) {
79 // we need capability to view participants
83 list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context);
84 $enrolledsql = "SELECT COUNT(*) FROM ($enrolledsqlselect) AS enrolleduserids";
85 $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams);
87 $result[] = array('id'=>$course->id, 'shortname'=>$course->shortname, 'fullname'=>$course->fullname, 'idnumber'=>$course->idnumber,'visible'=>$course->visible, 'enrolledusercount'=>$enrolledusercount);
94 * Returns description of method result value
95 * @return external_description
97 public static function get_users_courses_returns() {
98 return new external_multiple_structure(
99 new external_single_structure(
101 'id' => new external_value(PARAM_INT, 'id of course'),
102 'shortname' => new external_value(PARAM_RAW, 'short name of course'),
103 'fullname' => new external_value(PARAM_RAW, 'long name of course'),
104 'enrolledusercount' => new external_value(PARAM_INT, 'Number of enrolled users in this course'),
105 'idnumber' => new external_value(PARAM_RAW, 'id number of course'),
106 'visible' => new external_value(PARAM_INT, '1 means visible, 0 means hidden course'),
113 * Returns description of method parameters
114 * @return external_function_parameters
116 public static function get_enrolled_users_parameters() {
117 return new external_function_parameters(
119 'courseid' => new external_value(PARAM_INT, 'course id'),
120 'options' => new external_multiple_structure(
121 new external_single_structure(
123 'name' => new external_value(PARAM_ALPHANUMEXT, 'option name'),
124 'value' => new external_value(PARAM_RAW, 'option value')
126 ), 'method options', VALUE_DEFAULT, array()),
132 * Get course participants details
133 * @param int $courseid course id
134 * @param array $options options {
135 * 'name' => option name
136 * 'value' => option value
138 * @return array An array of users
140 public static function get_enrolled_users($courseid, $options) {
141 global $CFG, $USER, $DB;
142 require_once($CFG->dirroot . "/user/lib.php");
144 $params = self::validate_parameters(
145 self::get_enrolled_users_parameters(),
147 'courseid'=>$courseid,
151 $withcapability = '';
154 $userfields = array();
155 foreach ($options as $option) {
156 switch ($option['name']) {
157 case 'withcapability':
158 $withcapability = $option['value'];
161 $groupid = (int)$option['value'];
164 $onlyactive = !empty($option['value']);
167 $thefields = explode(',', $option['value']);
168 foreach ($thefields as $f) {
169 $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
175 // to overwrite this parameter, you need role:review capability
176 if ($withcapability) {
177 require_capability('moodle/role:review', $coursecontext);
179 // need accessallgroups capability if you want to overwrite this option
180 if (!empty($groupid) && groups_is_member($groupid)) {
181 require_capability('moodle/site:accessallgroups', $context);
183 // to overwrite this option, you need course:enrolereview permission
185 require_capability('moodle/course:enrolreview', $coursecontext);
188 list($coursectxselect, $coursectxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
189 $coursesql = "SELECT c.* $coursectxselect
190 FROM {course} c $coursectxjoin
191 WHERE c.id = $courseid";
192 $course = $DB->get_record_sql($coursesql);
193 context_instance_preload($course);
194 $coursecontext = get_context_instance(CONTEXT_COURSE, $params['courseid']);
195 if ($courseid == SITEID) {
196 $context = get_system_context();
198 $context = $coursecontext;
201 self::validate_context($context);
202 } catch (Exception $e) {
203 $exceptionparam = new stdClass();
204 $exceptionparam->message = $e->getMessage();
205 $exceptionparam->courseid = $params['courseid'];
206 throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
209 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
210 list($ctxselect, $ctxjoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
211 $records = $DB->get_records_sql($enrolledsql, $enrolledparams);
212 $sqlparams['courseid'] = $courseid;
213 $sql = "SELECT u.* $ctxselect
214 FROM {user} u $ctxjoin
215 WHERE u.id IN ($enrolledsql)
217 $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams);
219 foreach ($enrolledusers as $user) {
220 if (!empty($user->deleted)) {
223 context_instance_preload($user);
224 if ($userdetails = user_get_user_details($user, $course, $userfields)) {
225 $users[] = $userdetails;
228 $enrolledusers->close();
234 * Returns description of method result value
235 * @return external_description
237 public static function get_enrolled_users_returns() {
238 return new external_multiple_structure(
239 new external_single_structure(
241 'id' => new external_value(PARAM_NUMBER, 'ID of the user'),
242 'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL),
243 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
244 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
245 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
246 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
247 'address' => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
248 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
249 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
250 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
251 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
252 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
253 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
254 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
255 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
256 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
257 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
258 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
259 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
260 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
261 'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
262 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
263 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
264 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
265 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version', VALUE_OPTIONAL),
266 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version', VALUE_OPTIONAL),
267 'customfields' => new external_multiple_structure(
268 new external_single_structure(
270 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
271 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
272 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
273 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
275 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
276 'groups' => new external_multiple_structure(
277 new external_single_structure(
279 'id' => new external_value(PARAM_INT, 'group id'),
280 'name' => new external_value(PARAM_RAW, 'group name'),
281 'description' => new external_value(PARAM_RAW, 'group description'),
283 ), 'user groups', VALUE_OPTIONAL),
284 'roles' => new external_multiple_structure(
285 new external_single_structure(
287 'roleid' => new external_value(PARAM_INT, 'role id'),
288 'name' => new external_value(PARAM_RAW, 'role name'),
289 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
290 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
292 ), 'user roles', VALUE_OPTIONAL),
293 'preferences' => new external_multiple_structure(
294 new external_single_structure(
296 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
297 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
299 ), 'User preferences', VALUE_OPTIONAL),
300 'enrolledcourses' => new external_multiple_structure(
301 new external_single_structure(
303 'id' => new external_value(PARAM_INT, 'Id of the course'),
304 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
305 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
307 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
318 class core_role_external extends external_api {
321 * Returns description of method parameters
322 * @return external_function_parameters
324 public static function assign_roles_parameters() {
325 return new external_function_parameters(
327 'assignments' => new external_multiple_structure(
328 new external_single_structure(
330 'roleid' => new external_value(PARAM_INT, 'Role to assign to the user'),
331 'userid' => new external_value(PARAM_INT, 'The user that is going to be assigned'),
332 'contextid' => new external_value(PARAM_INT, 'The context to assign the user role in'),
341 * Manual role assignments to users
343 * @param array $assignment An array of manual role assignment
346 public static function assign_roles($assignments) {
349 // Do basic automatic PARAM checks on incoming data, using params description
350 // If any problems are found then exceptions are thrown with helpful error messages
351 $params = self::validate_parameters(self::assign_roles_parameters(), array('assignments'=>$assignments));
353 $transaction = $DB->start_delegated_transaction();
355 foreach ($params['assignments'] as $assignment) {
356 // Ensure the current user is allowed to run this function in the enrolment context
357 $context = get_context_instance_by_id($assignment['contextid']);
358 self::validate_context($context);
359 require_capability('moodle/role:assign', $context);
361 // throw an exception if user is not able to assign the role in this context
362 $roles = get_assignable_roles($context, ROLENAME_SHORT);
364 if (!key_exists($assignment['roleid'], $roles)) {
365 throw new invalid_parameter_exception('Can not assign roleid='.$assignment['roleid'].' in contextid='.$assignment['contextid']);
368 role_assign($assignment['roleid'], $assignment['userid'], $assignment['contextid']);
371 $transaction->allow_commit();
375 * Returns description of method result value
376 * @return external_description
378 public static function assign_roles_returns() {
384 * Returns description of method parameters
385 * @return external_function_parameters
387 public static function unassign_roles_parameters() {
388 return new external_function_parameters(
390 'unassignments' => new external_multiple_structure(
391 new external_single_structure(
393 'roleid' => new external_value(PARAM_INT, 'Role to assign to the user'),
394 'userid' => new external_value(PARAM_INT, 'The user that is going to be assigned'),
395 'contextid' => new external_value(PARAM_INT, 'The context to unassign the user role from'),
404 * Unassign roles from users
406 * @param array $unassignment An array of unassignment
409 public static function unassign_roles($unassignments) {
412 // Do basic automatic PARAM checks on incoming data, using params description
413 // If any problems are found then exceptions are thrown with helpful error messages
414 $params = self::validate_parameters(self::unassign_roles_parameters(), array('unassignments'=>$unassignments));
416 $transaction = $DB->start_delegated_transaction();
418 foreach ($params['unassignments'] as $unassignment) {
419 // Ensure the current user is allowed to run this function in the unassignment context
420 $context = get_context_instance_by_id($unassignment['contextid']);
421 self::validate_context($context);
422 require_capability('moodle/role:assign', $context);
424 // throw an exception if user is not able to unassign the role in this context
425 $roles = get_assignable_roles($context, ROLENAME_SHORT);
426 if (!key_exists($unassignment['roleid'], $roles)) {
427 throw new invalid_parameter_exception('Can not unassign roleid='.$unassignment['roleid'].' in contextid='.$unassignment['contextid']);
430 role_unassign($unassignment['roleid'], $unassignment['userid'], $unassignment['contextid']);
433 $transaction->allow_commit();
437 * Returns description of method result value
440 public static function unassign_roles_returns() {
447 * Deprecated enroll and role functions
448 * @deprecated since Moodle 2.2 please use core_enrol_external or core_role_external instead
450 class moodle_enrol_external extends external_api {
454 * Returns description of method parameters
455 * @deprecated since Moodle 2.2 please use core_enrol_external::get_enrolled_users_parameters() instead
456 * @return external_function_parameters
458 public static function get_enrolled_users_parameters() {
459 return new external_function_parameters(
461 'courseid' => new external_value(PARAM_INT, 'Course id'),
462 'withcapability' => new external_value(PARAM_CAPABILITY, 'User should have this capability', VALUE_DEFAULT, null),
463 'groupid' => new external_value(PARAM_INT, 'Group id, null means all groups', VALUE_DEFAULT, null),
464 'onlyactive' => new external_value(PARAM_INT, 'True means only active, false means all participants', VALUE_DEFAULT, 0),
470 * Get list of course participants.
471 * @deprecated since Moodle 2.2 please use core_enrol_external::get_enrolled_users() instead
472 * @param int $courseid
473 * @param text $withcapability
474 * @param int $groupid
475 * @param bool $onlyactive
476 * @return array of course participants
478 public static function get_enrolled_users($courseid, $withcapability = null, $groupid = null, $onlyactive = false) {
479 global $DB, $CFG, $USER;
481 // Do basic automatic PARAM checks on incoming data, using params description
482 // If any problems are found then exceptions are thrown with helpful error messages
483 $params = self::validate_parameters(self::get_enrolled_users_parameters(), array(
484 'courseid'=>$courseid,
485 'withcapability'=>$withcapability,
487 'onlyactive'=>$onlyactive)
490 $coursecontext = get_context_instance(CONTEXT_COURSE, $params['courseid']);
491 if ($courseid == SITEID) {
492 $context = get_context_instance(CONTEXT_SYSTEM);
494 $context = $coursecontext;
498 self::validate_context($context);
499 } catch (Exception $e) {
500 $exceptionparam = new stdClass();
501 $exceptionparam->message = $e->getMessage();
502 $exceptionparam->courseid = $params['courseid'];
503 throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
506 if ($courseid == SITEID) {
507 require_capability('moodle/site:viewparticipants', $context);
509 require_capability('moodle/course:viewparticipants', $context);
512 if ($withcapability) {
513 require_capability('moodle/role:review', $coursecontext);
515 if ($groupid && groups_is_member($groupid)) {
516 require_capability('moodle/site:accessallgroups', $coursecontext);
519 require_capability('moodle/course:enrolreview', $coursecontext);
522 list($sqlparams, $params) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
523 $sql = "SELECT ue.userid, e.courseid, u.firstname, u.lastname, u.username, c.id as usercontextid
524 FROM {user_enrolments} ue
525 JOIN {enrol} e ON (e.id = ue.enrolid)
526 JOIN {user} u ON (ue.userid = u.id)
527 JOIN {context} c ON (u.id = c.instanceid AND contextlevel = " . CONTEXT_USER . ")
528 WHERE e.courseid = :courseid AND ue.userid IN ($sqlparams)
529 GROUP BY ue.userid, e.courseid, u.firstname, u.lastname, u.username, c.id";
530 $params['courseid'] = $courseid;
531 $enrolledusers = $DB->get_records_sql($sql, $params);
533 $isadmin = is_siteadmin($USER);
534 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
535 foreach ($enrolledusers as $enrolleduser) {
536 $profilimgurl = moodle_url::make_pluginfile_url($enrolleduser->usercontextid, 'user', 'icon', NULL, '/', 'f1');
537 $profilimgurlsmall = moodle_url::make_pluginfile_url($enrolleduser->usercontextid, 'user', 'icon', NULL, '/', 'f2');
539 'courseid' => $enrolleduser->courseid,
540 'userid' => $enrolleduser->userid,
541 'fullname' => fullname($enrolleduser),
542 'profileimgurl' => $profilimgurl->out(false),
543 'profileimgurlsmall' => $profilimgurlsmall->out(false)
545 // check if we can return username
547 $resultuser['username'] = $enrolleduser->username;
549 // check if we can return first and last name
550 if ($isadmin or $canviewfullnames) {
551 $resultuser['firstname'] = $enrolleduser->firstname;
552 $resultuser['lastname'] = $enrolleduser->lastname;
554 $result[] = $resultuser;
561 * Returns description of method result value
562 * @deprecated since Moodle 2.2 please use core_enrol_external::get_enrolled_users_returns() instead
563 * @return external_description
565 public static function get_enrolled_users_returns() {
566 return new external_multiple_structure(
567 new external_single_structure(
569 'courseid' => new external_value(PARAM_INT, 'id of course'),
570 'userid' => new external_value(PARAM_INT, 'id of user'),
571 'firstname' => new external_value(PARAM_RAW, 'first name of user', VALUE_OPTIONAL),
572 'lastname' => new external_value(PARAM_RAW, 'last name of user', VALUE_OPTIONAL),
573 'fullname' => new external_value(PARAM_RAW, 'fullname of user'),
574 'username' => new external_value(PARAM_RAW, 'username of user', VALUE_OPTIONAL),
575 'profileimgurl' => new external_value(PARAM_URL, 'url of the profile image'),
576 'profileimgurlsmall' => new external_value(PARAM_URL, 'url of the profile image (small version)')
583 * Returns description of method parameters
584 * @deprecated since Moodle 2.2 please use core_enrol_external::get_users_courses_parameters() instead
585 * @return external_function_parameters
587 public static function get_users_courses_parameters() {
588 return core_enrol_external::get_users_courses_parameters();
592 * Get list of courses user is enrolled in (only active enrolments are returned).
594 * Please note the current user must be able to access the course, otherwise the course is not included.
595 * @deprecated since Moodle 2.2 please use core_enrol_external::get_users_courses() instead
597 * @return array of courses
599 public static function get_users_courses($userid) {
600 return core_enrol_external::get_users_courses($userid);
604 * Returns description of method result value
605 * @deprecated since Moodle 2.2 please use core_enrol_external::get_users_courses_returns() instead
606 * @return external_description
608 public static function get_users_courses_returns() {
609 return core_enrol_external::get_users_courses_returns();
614 * Returns description of method parameters
615 * @deprecated since Moodle 2.2 please use core_role_external::assign_roles_parameters() instead
616 * @return external_function_parameters
618 public static function role_assign_parameters() {
619 return core_role_external::assign_roles_parameters();
623 * Manual role assignments to users
624 * @deprecated since Moodle 2.2 please use core_role_external::assign_roles() instead
625 * @param array $assignment An array of manual role assignment
628 public static function role_assign($assignments) {
629 return core_role_external::assign_roles($assignments);
633 * Returns description of method result value
634 * @deprecated since Moodle 2.2 please use core_role_external::assign_roles_returns() instead
635 * @return external_description
637 public static function role_assign_returns() {
638 return core_role_external::assign_roles_returns();
643 * Returns description of method parameters
644 * @deprecated since Moodle 2.2 please use core_role_external::unassign_roles_parameters() instead
645 * @return external_function_parameters
647 public static function role_unassign_parameters() {
648 return core_role_external::unassign_roles_parameters();
652 * Unassign roles from users
653 * @deprecated since Moodle 2.2 please use core_role_external::unassign_roles() instead
654 * @param array $unassignment An array of unassignment
657 public static function role_unassign($unassignments) {
658 return core_role_external::unassign_roles($unassignments);
662 * Returns description of method result value
663 * @deprecated since Moodle 2.2 please use core_role_external::unassign_roles_returns() instead
664 * @return external_description
666 public static function role_unassign_returns() {
667 return core_role_external::unassign_roles_returns();