MDL-36580 backup: Apply the decrypt() method to lti "secrets"
[moodle.git] / enrol / externallib.php
blobd11bfab194fca91ebba504e53f14cb00dcb9dea8
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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 /**
19 * External course participation api.
21 * This api is mostly read only, the actual enrol and unenrol
22 * support is in each enrol plugin.
24 * @package core_enrol
25 * @category external
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");
34 /**
35 * Enrol external functions
37 * @package core_enrol
38 * @category external
39 * @copyright 2011 Jerome Mouneyrac
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 * @since Moodle 2.2
43 class core_enrol_external extends external_api {
45 /**
46 * Returns description of method parameters
48 * @return external_function_parameters
49 * @since Moodle 2.4
51 public static function get_enrolled_users_with_capability_parameters() {
52 return new external_function_parameters(
53 array (
54 'coursecapabilities' => new external_multiple_structure(
55 new external_single_structure(
56 array (
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(
65 array(
66 'name' => new external_value(PARAM_ALPHANUMEXT, 'option name'),
67 'value' => new external_value(PARAM_RAW, 'option value')
69 ), 'Option names:
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())
79 /**
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
85 * @since Moodle 2.4
87 public static function get_enrolled_users_with_capability($coursecapabilities, $options) {
88 global $CFG, $DB;
90 require_once($CFG->dirroot . '/course/lib.php');
91 require_once($CFG->dirroot . "/user/lib.php");
93 if (empty($coursecapabilities)) {
94 throw new invalid_parameter_exception('Parameter can not be empty');
96 $params = self::validate_parameters(self::get_enrolled_users_with_capability_parameters(),
97 array ('coursecapabilities' => $coursecapabilities, 'options'=>$options));
98 $result = array();
99 $userlist = array();
100 $groupid = 0;
101 $onlyactive = false;
102 $userfields = array();
103 $limitfrom = 0;
104 $limitnumber = 0;
105 foreach ($params['options'] as $option) {
106 switch ($option['name']) {
107 case 'groupid':
108 $groupid = (int)$option['value'];
109 break;
110 case 'onlyactive':
111 $onlyactive = !empty($option['value']);
112 break;
113 case 'userfields':
114 $thefields = explode(',', $option['value']);
115 foreach ($thefields as $f) {
116 $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
118 break;
119 case 'limitfrom' :
120 $limitfrom = clean_param($option['value'], PARAM_INT);
121 break;
122 case 'limitnumber' :
123 $limitnumber = clean_param($option['value'], PARAM_INT);
124 break;
128 foreach ($params['coursecapabilities'] as $coursecapability) {
129 $courseid = $coursecapability['courseid'];
130 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
131 $coursecontext = context_course::instance($courseid);
132 if (!$coursecontext) {
133 throw new moodle_exception('cannotfindcourse', 'error', '', null,
134 'The course id ' . $courseid . ' doesn\'t exist.');
136 if ($courseid == SITEID) {
137 $context = context_system::instance();
138 } else {
139 $context = $coursecontext;
141 try {
142 self::validate_context($context);
143 } catch (Exception $e) {
144 $exceptionparam = new stdClass();
145 $exceptionparam->message = $e->getMessage();
146 $exceptionparam->courseid = $params['courseid'];
147 throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
150 course_require_view_participants($context);
152 // The accessallgroups capability is needed to use this option.
153 if (!empty($groupid) && groups_is_member($groupid)) {
154 require_capability('moodle/site:accessallgroups', $coursecontext);
156 // The course:enrolereview capability is needed to use this option.
157 if ($onlyactive) {
158 require_capability('moodle/course:enrolreview', $coursecontext);
161 // To see the permissions of others role:review capability is required.
162 require_capability('moodle/role:review', $coursecontext);
163 foreach ($coursecapability['capabilities'] as $capability) {
164 $courseusers['courseid'] = $courseid;
165 $courseusers['capability'] = $capability;
167 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $capability, $groupid, $onlyactive);
169 $sql = "SELECT u.* FROM {user} u WHERE u.id IN ($enrolledsql) ORDER BY u.id ASC";
171 $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
172 $users = array();
173 foreach ($enrolledusers as $courseuser) {
174 if ($userdetails = user_get_user_details($courseuser, $course, $userfields)) {
175 $users[] = $userdetails;
178 $enrolledusers->close();
179 $courseusers['users'] = $users;
180 $result[] = $courseusers;
183 return $result;
187 * Returns description of method result value
189 * @return external_multiple_structure
190 * @since Moodle 2.4
192 public static function get_enrolled_users_with_capability_returns() {
193 return new external_multiple_structure( new external_single_structure (
194 array (
195 'courseid' => new external_value(PARAM_INT, 'Course ID number in the Moodle course table'),
196 'capability' => new external_value(PARAM_CAPABILITY, 'Capability name'),
197 'users' => new external_multiple_structure(
198 new external_single_structure(
199 array(
200 'id' => new external_value(PARAM_INT, 'ID of the user'),
201 'username' => new external_value(PARAM_RAW, 'Username', VALUE_OPTIONAL),
202 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
203 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
204 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
205 'email' => new external_value(PARAM_TEXT, 'Email address', VALUE_OPTIONAL),
206 'address' => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
207 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
208 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
209 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
210 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
211 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
212 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
213 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
214 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
215 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
216 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
217 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
218 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
219 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
220 'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
221 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
222 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
223 'country' => new external_value(PARAM_ALPHA, 'Country code of the user, such as AU or CZ', VALUE_OPTIONAL),
224 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small', VALUE_OPTIONAL),
225 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big', VALUE_OPTIONAL),
226 'customfields' => new external_multiple_structure(
227 new external_single_structure(
228 array(
229 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field'),
230 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
231 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
232 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field'),
234 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
235 'groups' => new external_multiple_structure(
236 new external_single_structure(
237 array(
238 'id' => new external_value(PARAM_INT, 'group id'),
239 'name' => new external_value(PARAM_RAW, 'group name'),
240 'description' => new external_value(PARAM_RAW, 'group description'),
242 ), 'user groups', VALUE_OPTIONAL),
243 'roles' => new external_multiple_structure(
244 new external_single_structure(
245 array(
246 'roleid' => new external_value(PARAM_INT, 'role id'),
247 'name' => new external_value(PARAM_RAW, 'role name'),
248 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
249 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
251 ), 'user roles', VALUE_OPTIONAL),
252 'preferences' => new external_multiple_structure(
253 new external_single_structure(
254 array(
255 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
256 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
258 ), 'User preferences', VALUE_OPTIONAL),
259 'enrolledcourses' => new external_multiple_structure(
260 new external_single_structure(
261 array(
262 'id' => new external_value(PARAM_INT, 'Id of the course'),
263 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
264 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
266 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
268 ), 'List of users that are enrolled in the course and have the specified capability'),
275 * Returns description of method parameters
277 * @return external_function_parameters
279 public static function get_users_courses_parameters() {
280 return new external_function_parameters(
281 array(
282 'userid' => new external_value(PARAM_INT, 'user id'),
288 * Get list of courses user is enrolled in (only active enrolments are returned).
289 * Please note the current user must be able to access the course, otherwise the course is not included.
291 * @param int $userid
292 * @return array of courses
294 public static function get_users_courses($userid) {
295 global $CFG, $USER, $DB;
297 require_once($CFG->dirroot . '/course/lib.php');
299 // Do basic automatic PARAM checks on incoming data, using params description
300 // If any problems are found then exceptions are thrown with helpful error messages
301 $params = self::validate_parameters(self::get_users_courses_parameters(), array('userid'=>$userid));
303 $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible,
304 summary, summaryformat, format, showgrades, lang, enablecompletion, category, startdate, enddate');
305 $result = array();
307 foreach ($courses as $course) {
308 $context = context_course::instance($course->id, IGNORE_MISSING);
309 try {
310 self::validate_context($context);
311 } catch (Exception $e) {
312 // current user can not access this course, sorry we can not disclose who is enrolled in this course!
313 continue;
316 if ($userid != $USER->id and !course_can_view_participants($context)) {
317 // we need capability to view participants
318 continue;
321 list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context);
322 $enrolledsql = "SELECT COUNT('x') FROM ($enrolledsqlselect) enrolleduserids";
323 $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams);
325 list($course->summary, $course->summaryformat) =
326 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', null);
327 $course->fullname = external_format_string($course->fullname, $context->id);
328 $course->shortname = external_format_string($course->shortname, $context->id);
330 $progress = null;
331 if ($course->enablecompletion) {
332 $progress = \core_completion\progress::get_course_progress_percentage($course);
335 $result[] = array(
336 'id' => $course->id,
337 'shortname' => $course->shortname,
338 'fullname' => $course->fullname,
339 'idnumber' => $course->idnumber,
340 'visible' => $course->visible,
341 'enrolledusercount' => $enrolledusercount,
342 'summary' => $course->summary,
343 'summaryformat' => $course->summaryformat,
344 'format' => $course->format,
345 'showgrades' => $course->showgrades,
346 'lang' => $course->lang,
347 'enablecompletion' => $course->enablecompletion,
348 'category' => $course->category,
349 'progress' => $progress,
350 'startdate' => $course->startdate,
351 'enddate' => $course->enddate,
355 return $result;
359 * Returns description of method result value
361 * @return external_description
363 public static function get_users_courses_returns() {
364 return new external_multiple_structure(
365 new external_single_structure(
366 array(
367 'id' => new external_value(PARAM_INT, 'id of course'),
368 'shortname' => new external_value(PARAM_RAW, 'short name of course'),
369 'fullname' => new external_value(PARAM_RAW, 'long name of course'),
370 'enrolledusercount' => new external_value(PARAM_INT, 'Number of enrolled users in this course'),
371 'idnumber' => new external_value(PARAM_RAW, 'id number of course'),
372 'visible' => new external_value(PARAM_INT, '1 means visible, 0 means hidden course'),
373 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
374 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
375 'format' => new external_value(PARAM_PLUGIN, 'course format: weeks, topics, social, site', VALUE_OPTIONAL),
376 'showgrades' => new external_value(PARAM_BOOL, 'true if grades are shown, otherwise false', VALUE_OPTIONAL),
377 'lang' => new external_value(PARAM_LANG, 'forced course language', VALUE_OPTIONAL),
378 'enablecompletion' => new external_value(PARAM_BOOL, 'true if completion is enabled, otherwise false',
379 VALUE_OPTIONAL),
380 'category' => new external_value(PARAM_INT, 'course category id', VALUE_OPTIONAL),
381 'progress' => new external_value(PARAM_FLOAT, 'Progress percentage', VALUE_OPTIONAL),
382 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
383 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
390 * Returns description of method parameters value
392 * @return external_description
394 public static function get_potential_users_parameters() {
395 return new external_function_parameters(
396 array(
397 'courseid' => new external_value(PARAM_INT, 'course id'),
398 'enrolid' => new external_value(PARAM_INT, 'enrolment id'),
399 'search' => new external_value(PARAM_RAW, 'query'),
400 'searchanywhere' => new external_value(PARAM_BOOL, 'find a match anywhere, or only at the beginning'),
401 'page' => new external_value(PARAM_INT, 'Page number'),
402 'perpage' => new external_value(PARAM_INT, 'Number per page'),
408 * Get potential users.
410 * @param int $courseid Course id
411 * @param int $enrolid Enrolment id
412 * @param string $search The query
413 * @param boolean $searchanywhere Match anywhere in the string
414 * @param int $page Page number
415 * @param int $perpage Max per page
416 * @return array An array of users
418 public static function get_potential_users($courseid, $enrolid, $search, $searchanywhere, $page, $perpage) {
419 global $PAGE, $DB, $CFG;
421 require_once($CFG->dirroot.'/enrol/locallib.php');
422 require_once($CFG->dirroot.'/user/lib.php');
424 $params = self::validate_parameters(
425 self::get_potential_users_parameters(),
426 array(
427 'courseid' => $courseid,
428 'enrolid' => $enrolid,
429 'search' => $search,
430 'searchanywhere' => $searchanywhere,
431 'page' => $page,
432 'perpage' => $perpage
435 $context = context_course::instance($params['courseid']);
436 try {
437 self::validate_context($context);
438 } catch (Exception $e) {
439 $exceptionparam = new stdClass();
440 $exceptionparam->message = $e->getMessage();
441 $exceptionparam->courseid = $params['courseid'];
442 throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
444 require_capability('moodle/course:enrolreview', $context);
446 $course = $DB->get_record('course', array('id' => $params['courseid']));
447 $manager = new course_enrolment_manager($PAGE, $course);
449 $users = $manager->get_potential_users($params['enrolid'],
450 $params['search'],
451 $params['searchanywhere'],
452 $params['page'],
453 $params['perpage']);
455 $results = array();
456 $requiredfields = ['id', 'fullname', 'profileimageurl', 'profileimageurlsmall'];
457 foreach ($users['users'] as $id => $user) {
458 // Note: We pass the course here to validate that the current user can at least view user details in this course.
459 // The user we are looking at is not in this course yet though - but we only fetch the minimal set of
460 // user records, and the user has been validated to have course:enrolreview in this course. Otherwise
461 // there is no way to find users who aren't in the course in order to enrol them.
462 if ($userdetails = user_get_user_details($user, $course, $requiredfields)) {
463 $results[] = $userdetails;
466 return $results;
470 * Returns description of method result value
472 * @return external_description
474 public static function get_potential_users_returns() {
475 global $CFG;
476 require_once($CFG->dirroot . '/user/externallib.php');
477 return new external_multiple_structure(core_user_external::user_description());
481 * Returns description of method parameters
483 * @return external_function_parameters
485 public static function get_enrolled_users_parameters() {
486 return new external_function_parameters(
487 array(
488 'courseid' => new external_value(PARAM_INT, 'course id'),
489 'options' => new external_multiple_structure(
490 new external_single_structure(
491 array(
492 'name' => new external_value(PARAM_ALPHANUMEXT, 'option name'),
493 'value' => new external_value(PARAM_RAW, 'option value')
495 ), 'Option names:
496 * withcapability (string) return only users with this capability. This option requires \'moodle/role:review\' on the course context.
497 * groupid (integer) return only users in this group id. If the course has groups enabled and this param
498 isn\'t defined, returns all the viewable users.
499 This option requires \'moodle/site:accessallgroups\' on the course context if the
500 user doesn\'t belong to the group.
501 * onlyactive (integer) return only users with active enrolments and matching time restrictions. This option requires \'moodle/course:enrolreview\' on the course context.
502 * userfields (\'string, string, ...\') return only the values of these user fields.
503 * limitfrom (integer) sql limit from.
504 * limitnumber (integer) maximum number of returned users.
505 * sortby (string) sort by id, firstname or lastname. For ordering like the site does, use siteorder.
506 * sortdirection (string) ASC or DESC',
507 VALUE_DEFAULT, array()),
513 * Get course participants details
515 * @param int $courseid course id
516 * @param array $options options {
517 * 'name' => option name
518 * 'value' => option value
520 * @return array An array of users
522 public static function get_enrolled_users($courseid, $options = array()) {
523 global $CFG, $USER, $DB;
525 require_once($CFG->dirroot . '/course/lib.php');
526 require_once($CFG->dirroot . "/user/lib.php");
528 $params = self::validate_parameters(
529 self::get_enrolled_users_parameters(),
530 array(
531 'courseid'=>$courseid,
532 'options'=>$options
535 $withcapability = '';
536 $groupid = 0;
537 $onlyactive = false;
538 $userfields = array();
539 $limitfrom = 0;
540 $limitnumber = 0;
541 $sortby = 'us.id';
542 $sortparams = array();
543 $sortdirection = 'ASC';
544 foreach ($options as $option) {
545 switch ($option['name']) {
546 case 'withcapability':
547 $withcapability = $option['value'];
548 break;
549 case 'groupid':
550 $groupid = (int)$option['value'];
551 break;
552 case 'onlyactive':
553 $onlyactive = !empty($option['value']);
554 break;
555 case 'userfields':
556 $thefields = explode(',', $option['value']);
557 foreach ($thefields as $f) {
558 $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
560 break;
561 case 'limitfrom' :
562 $limitfrom = clean_param($option['value'], PARAM_INT);
563 break;
564 case 'limitnumber' :
565 $limitnumber = clean_param($option['value'], PARAM_INT);
566 break;
567 case 'sortby':
568 $sortallowedvalues = array('id', 'firstname', 'lastname', 'siteorder');
569 if (!in_array($option['value'], $sortallowedvalues)) {
570 throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $option['value'] . '),' .
571 'allowed values are: ' . implode(',', $sortallowedvalues));
573 if ($option['value'] == 'siteorder') {
574 list($sortby, $sortparams) = users_order_by_sql('us');
575 } else {
576 $sortby = 'us.' . $option['value'];
578 break;
579 case 'sortdirection':
580 $sortdirection = strtoupper($option['value']);
581 $directionallowedvalues = array('ASC', 'DESC');
582 if (!in_array($sortdirection, $directionallowedvalues)) {
583 throw new invalid_parameter_exception('Invalid value for sortdirection parameter
584 (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues));
586 break;
590 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
591 $coursecontext = context_course::instance($courseid, IGNORE_MISSING);
592 if ($courseid == SITEID) {
593 $context = context_system::instance();
594 } else {
595 $context = $coursecontext;
597 try {
598 self::validate_context($context);
599 } catch (Exception $e) {
600 $exceptionparam = new stdClass();
601 $exceptionparam->message = $e->getMessage();
602 $exceptionparam->courseid = $params['courseid'];
603 throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
606 course_require_view_participants($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
617 if ($onlyactive) {
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;
626 $groupjoin = '';
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);
635 } else {
636 // User doesn't belong to any group, so he can't see any user. Return an empty array.
637 return array();
640 $sql = "SELECT us.*
641 FROM {user} us
642 JOIN (
643 SELECT DISTINCT u.id $ctxselect
644 FROM {user} u $ctxjoin $groupjoin
645 WHERE u.id IN ($enrolledsql)
646 ) q ON q.id = us.id
647 ORDER BY $sortby $sortdirection";
648 $enrolledparams = array_merge($enrolledparams, $sortparams);
649 $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
650 $users = array();
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();
659 return $users;
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(
670 array(
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(
700 array(
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(
709 array(
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(
718 array(
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(
727 array(
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(
734 array(
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(
752 array(
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) {
766 global $DB;
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');
777 $result = array();
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;
786 return $result;
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(
797 array(
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),
810 * Returns description of edit_user_enrolment() parameters
812 * @return external_function_parameters
814 public static function edit_user_enrolment_parameters() {
815 return new external_function_parameters(
816 array(
817 'courseid' => new external_value(PARAM_INT, 'User enrolment ID'),
818 'ueid' => new external_value(PARAM_INT, 'User enrolment ID'),
819 'status' => new external_value(PARAM_INT, 'Enrolment status'),
820 'timestart' => new external_value(PARAM_INT, 'Enrolment start timestamp', VALUE_DEFAULT, 0),
821 'timeend' => new external_value(PARAM_INT, 'Enrolment end timestamp', VALUE_DEFAULT, 0),
827 * External function that updates a given user enrolment.
829 * @param int $courseid The course ID.
830 * @param int $ueid The user enrolment ID.
831 * @param int $status The enrolment status.
832 * @param int $timestart Enrolment start timestamp.
833 * @param int $timeend Enrolment end timestamp.
834 * @return array An array consisting of the processing result, errors and form output, if available.
836 public static function edit_user_enrolment($courseid, $ueid, $status, $timestart = 0, $timeend = 0) {
837 global $CFG, $DB, $PAGE;
839 $params = self::validate_parameters(self::edit_user_enrolment_parameters(), [
840 'courseid' => $courseid,
841 'ueid' => $ueid,
842 'status' => $status,
843 'timestart' => $timestart,
844 'timeend' => $timeend,
847 $course = get_course($courseid);
848 $context = context_course::instance($course->id);
849 self::validate_context($context);
851 $userenrolment = $DB->get_record('user_enrolments', ['id' => $params['ueid']], '*', MUST_EXIST);
852 $userenroldata = [
853 'status' => $params['status'],
854 'timestart' => $params['timestart'],
855 'timeend' => $params['timeend'],
858 $result = false;
859 $errors = [];
861 // Validate data against the edit user enrolment form.
862 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
863 $customformdata = [
864 'ue' => $userenrolment,
865 'modal' => true,
867 $mform = new \enrol_user_enrolment_form(null, $customformdata, 'post', '', null, true, $userenroldata);
868 $mform->set_data($userenroldata);
869 $validationerrors = $mform->validation($userenroldata, null);
870 if (empty($validationerrors)) {
871 require_once($CFG->dirroot . '/enrol/locallib.php');
872 $manager = new course_enrolment_manager($PAGE, $course);
873 $result = $manager->edit_enrolment($userenrolment, (object)$userenroldata);
874 } else {
875 foreach ($validationerrors as $key => $errormessage) {
876 $errors[] = (object)[
877 'key' => $key,
878 'message' => $errormessage
883 return [
884 'result' => $result,
885 'errors' => $errors,
890 * Returns description of edit_user_enrolment() result value
892 * @return external_description
894 public static function edit_user_enrolment_returns() {
895 return new external_single_structure(
896 array(
897 'result' => new external_value(PARAM_BOOL, 'True if the user\'s enrolment was successfully updated'),
898 'errors' => new external_multiple_structure(
899 new external_single_structure(
900 array(
901 'key' => new external_value(PARAM_TEXT, 'The data that failed the validation'),
902 'message' => new external_value(PARAM_TEXT, 'The error message'),
904 ), 'List of validation errors'
912 * Role external functions
914 * @package core_role
915 * @category external
916 * @copyright 2011 Jerome Mouneyrac
917 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
918 * @since Moodle 2.2
920 class core_role_external extends external_api {
923 * Returns description of method parameters
925 * @return external_function_parameters
927 public static function assign_roles_parameters() {
928 return new external_function_parameters(
929 array(
930 'assignments' => new external_multiple_structure(
931 new external_single_structure(
932 array(
933 'roleid' => new external_value(PARAM_INT, 'Role to assign to the user'),
934 'userid' => new external_value(PARAM_INT, 'The user that is going to be assigned'),
935 'contextid' => new external_value(PARAM_INT, 'The context to assign the user role in', VALUE_OPTIONAL),
936 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level to assign the user role in
937 (block, course, coursecat, system, user, module)', VALUE_OPTIONAL),
938 'instanceid' => new external_value(PARAM_INT, 'The Instance id of item where the role needs to be assigned', VALUE_OPTIONAL),
947 * Manual role assignments to users
949 * @param array $assignments An array of manual role assignment
951 public static function assign_roles($assignments) {
952 global $DB;
954 // Do basic automatic PARAM checks on incoming data, using params description
955 // If any problems are found then exceptions are thrown with helpful error messages
956 $params = self::validate_parameters(self::assign_roles_parameters(), array('assignments'=>$assignments));
958 $transaction = $DB->start_delegated_transaction();
960 foreach ($params['assignments'] as $assignment) {
961 // Ensure correct context level with a instance id or contextid is passed.
962 $context = self::get_context_from_params($assignment);
964 // Ensure the current user is allowed to run this function in the enrolment context.
965 self::validate_context($context);
966 require_capability('moodle/role:assign', $context);
968 // throw an exception if user is not able to assign the role in this context
969 $roles = get_assignable_roles($context, ROLENAME_SHORT);
971 if (!array_key_exists($assignment['roleid'], $roles)) {
972 throw new invalid_parameter_exception('Can not assign roleid='.$assignment['roleid'].' in contextid='.$assignment['contextid']);
975 role_assign($assignment['roleid'], $assignment['userid'], $context->id);
978 $transaction->allow_commit();
982 * Returns description of method result value
984 * @return null
986 public static function assign_roles_returns() {
987 return null;
992 * Returns description of method parameters
994 * @return external_function_parameters
996 public static function unassign_roles_parameters() {
997 return new external_function_parameters(
998 array(
999 'unassignments' => new external_multiple_structure(
1000 new external_single_structure(
1001 array(
1002 'roleid' => new external_value(PARAM_INT, 'Role to assign to the user'),
1003 'userid' => new external_value(PARAM_INT, 'The user that is going to be assigned'),
1004 'contextid' => new external_value(PARAM_INT, 'The context to unassign the user role from', VALUE_OPTIONAL),
1005 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level to unassign the user role in
1006 + (block, course, coursecat, system, user, module)', VALUE_OPTIONAL),
1007 'instanceid' => new external_value(PARAM_INT, 'The Instance id of item where the role needs to be unassigned', VALUE_OPTIONAL),
1016 * Unassign roles from users
1018 * @param array $unassignments An array of unassignment
1020 public static function unassign_roles($unassignments) {
1021 global $DB;
1023 // Do basic automatic PARAM checks on incoming data, using params description
1024 // If any problems are found then exceptions are thrown with helpful error messages
1025 $params = self::validate_parameters(self::unassign_roles_parameters(), array('unassignments'=>$unassignments));
1027 $transaction = $DB->start_delegated_transaction();
1029 foreach ($params['unassignments'] as $unassignment) {
1030 // Ensure the current user is allowed to run this function in the unassignment context
1031 $context = self::get_context_from_params($unassignment);
1032 self::validate_context($context);
1033 require_capability('moodle/role:assign', $context);
1035 // throw an exception if user is not able to unassign the role in this context
1036 $roles = get_assignable_roles($context, ROLENAME_SHORT);
1037 if (!array_key_exists($unassignment['roleid'], $roles)) {
1038 throw new invalid_parameter_exception('Can not unassign roleid='.$unassignment['roleid'].' in contextid='.$unassignment['contextid']);
1041 role_unassign($unassignment['roleid'], $unassignment['userid'], $context->id);
1044 $transaction->allow_commit();
1048 * Returns description of method result value
1050 * @return null
1052 public static function unassign_roles_returns() {
1053 return null;