externallib.php 52.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

17

18
/**
19
 * External course participation api.
20
 *
21
22
23
 * This api is mostly read only, the actual enrol and unenrol
 * support is in each enrol plugin.
 *
24
25
26
 * @package    core_enrol
 * @category   external
 * @copyright  2010 Jerome Mouneyrac
27
28
29
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

Petr Skoda's avatar
Petr Skoda committed
30
defined('MOODLE_INTERNAL') || die();
31

32
33
require_once("$CFG->libdir/externallib.php");

34
/**
35
36
37
38
39
40
41
 * Enrol external functions
 *
 * @package    core_enrol
 * @category   external
 * @copyright  2011 Jerome Mouneyrac
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.2
42
43
44
 */
class core_enrol_external extends external_api {

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    /**
     * Returns description of method parameters
     *
     * @return external_function_parameters
     * @since Moodle 2.4
     */
    public static function get_enrolled_users_with_capability_parameters() {
        return new external_function_parameters(
            array (
                'coursecapabilities' => new external_multiple_structure(
                    new external_single_structure(
                        array (
                            'courseid' => new external_value(PARAM_INT, 'Course ID number in the Moodle course table'),
                            'capabilities' => new external_multiple_structure(
                                new external_value(PARAM_CAPABILITY, 'Capability name, such as mod/forum:viewdiscussion')),
                        )
                    )
                , 'course id and associated capability name'),
                 'options'  => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'name'  => new external_value(PARAM_ALPHANUMEXT, 'option name'),
                            'value' => new external_value(PARAM_RAW, 'option value')
                        )
                    ), 'Option names:
                            * groupid (integer) return only users in this group id. Requires \'moodle/site:accessallgroups\' .
                            * onlyactive (integer) only users with active enrolments. Requires \'moodle/course:enrolreview\' .
                            * userfields (\'string, string, ...\') return only the values of these user fields.
                            * limitfrom (integer) sql limit from.
                            * limitnumber (integer) max number of users per course and capability.', VALUE_DEFAULT, array())
            )
        );
    }

    /**
     * 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.
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
     *
     * @param array $coursecapabilities array of course ids and associated capability names {courseid, {capabilities}}
     * @return array An array of arrays describing users for each associated courseid and capability
     * @since  Moodle 2.4
     */
    public static function get_enrolled_users_with_capability($coursecapabilities, $options) {
        global $CFG, $DB;
        require_once($CFG->dirroot . "/user/lib.php");

        if (empty($coursecapabilities)) {
            throw new invalid_parameter_exception('Parameter can not be empty');
        }
        $params = self::validate_parameters(self::get_enrolled_users_with_capability_parameters(),
            array ('coursecapabilities' => $coursecapabilities,  'options'=>$options));
        $result = array();
        $userlist = array();
        $groupid        = 0;
        $onlyactive     = false;
        $userfields     = array();
        $limitfrom = 0;
        $limitnumber = 0;
        foreach ($params['options'] as $option) {
            switch ($option['name']) {
                case 'groupid':
                    $groupid = (int)$option['value'];
                    break;
                case 'onlyactive':
                    $onlyactive = !empty($option['value']);
                    break;
                case 'userfields':
                    $thefields = explode(',', $option['value']);
                    foreach ($thefields as $f) {
                        $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
                    }
116
                    break;
117
118
119
120
121
122
123
124
125
126
127
                case 'limitfrom' :
                    $limitfrom = clean_param($option['value'], PARAM_INT);
                    break;
                case 'limitnumber' :
                    $limitnumber = clean_param($option['value'], PARAM_INT);
                    break;
            }
        }

        foreach ($params['coursecapabilities'] as $coursecapability) {
            $courseid = $coursecapability['courseid'];
128
            $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
            $coursecontext = context_course::instance($courseid);
            if (!$coursecontext) {
                throw new moodle_exception('cannotfindcourse', 'error', '', null,
                        'The course id ' . $courseid . ' doesn\'t exist.');
            }
            if ($courseid == SITEID) {
                $context = context_system::instance();
            } else {
                $context = $coursecontext;
            }
            try {
                self::validate_context($context);
            } catch (Exception $e) {
                $exceptionparam = new stdClass();
                $exceptionparam->message = $e->getMessage();
                $exceptionparam->courseid = $params['courseid'];
                throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
            }

            if ($courseid == SITEID) {
                require_capability('moodle/site:viewparticipants', $context);
            } else {
                require_capability('moodle/course:viewparticipants', $context);
            }
            // The accessallgroups capability is needed to use this option.
            if (!empty($groupid) && groups_is_member($groupid)) {
                require_capability('moodle/site:accessallgroups', $coursecontext);
            }
            // The course:enrolereview capability is needed to use this option.
            if ($onlyactive) {
                require_capability('moodle/course:enrolreview', $coursecontext);
            }

            // To see the permissions of others role:review capability is required.
            require_capability('moodle/role:review', $coursecontext);
            foreach ($coursecapability['capabilities'] as $capability) {
                $courseusers['courseid'] = $courseid;
                $courseusers['capability'] = $capability;

                list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $capability, $groupid, $onlyactive);

                $sql = "SELECT u.* FROM {user} u WHERE u.id IN ($enrolledsql) ORDER BY u.id ASC";

                $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
                $users = array();
                foreach ($enrolledusers as $courseuser) {
                    if ($userdetails = user_get_user_details($courseuser, $course, $userfields)) {
                        $users[] = $userdetails;
                    }
                }
                $enrolledusers->close();
                $courseusers['users'] = $users;
                $result[] = $courseusers;
            }
        }
        return $result;
    }

    /**
     * Returns description of method result value
     *
     * @return external_multiple_structure
     * @since Moodle 2.4
     */
    public static function get_enrolled_users_with_capability_returns() {
        return  new external_multiple_structure( new external_single_structure (
                array (
                    'courseid' => new external_value(PARAM_INT, 'Course ID number in the Moodle course table'),
                    'capability' => new external_value(PARAM_CAPABILITY, 'Capability name'),
                    'users' => new external_multiple_structure(
                        new external_single_structure(
                array(
201
                    'id'    => new external_value(PARAM_INT, 'ID of the user'),
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
                    'username'    => new external_value(PARAM_RAW, 'Username', VALUE_OPTIONAL),
                    'firstname'   => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
                    'lastname'    => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
                    'fullname'    => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
                    'email'       => new external_value(PARAM_TEXT, 'Email address', VALUE_OPTIONAL),
                    'address'     => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
                    'phone1'      => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
                    'phone2'      => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
                    'icq'         => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
                    'skype'       => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
                    'yahoo'       => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
                    'aim'         => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
                    'msn'         => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
                    'department'  => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
                    'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
                    'interests'   => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
                    'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
                    'lastaccess'  => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
                    'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
                    'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
                    'city'        => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
                    'url'         => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
                    'country'     => new external_value(PARAM_ALPHA, 'Country code of the user, such as AU or CZ', VALUE_OPTIONAL),
                    'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small', VALUE_OPTIONAL),
                    'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big', VALUE_OPTIONAL),
                    'customfields' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'type'  => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field'),
                                'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
                                'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
                                'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field'),
                            )
                        ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
                    'groups' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'id'  => new external_value(PARAM_INT, 'group id'),
                                'name' => new external_value(PARAM_RAW, 'group name'),
                                'description' => new external_value(PARAM_RAW, 'group description'),
                            )
                        ), 'user groups', VALUE_OPTIONAL),
                    'roles' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'roleid'       => new external_value(PARAM_INT, 'role id'),
                                'name'         => new external_value(PARAM_RAW, 'role name'),
                                'shortname'    => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
                                'sortorder'    => new external_value(PARAM_INT, 'role sortorder')
                            )
                        ), 'user roles', VALUE_OPTIONAL),
                    'preferences' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'name'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
                                'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
                            )
                    ), 'User preferences', VALUE_OPTIONAL),
                    'enrolledcourses' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'id'  => new external_value(PARAM_INT, 'Id of the course'),
                                'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
                                'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
                            )
                    ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
                )
                        ), 'List of users that are enrolled in the course and have the specified capability'),
                    )
                )
            );
    }

275
276
    /**
     * Returns description of method parameters
277
     *
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
     * @return external_function_parameters
     */
    public static function get_users_courses_parameters() {
        return new external_function_parameters(
            array(
                'userid' => new external_value(PARAM_INT, 'user id'),
            )
        );
    }

    /**
     * Get list of courses user is enrolled in (only active enrolments are returned).
     * Please note the current user must be able to access the course, otherwise the course is not included.
     *
     * @param int $userid
     * @return array of courses
     */
    public static function get_users_courses($userid) {
296
        global $USER, $DB;
297
298
299
300
301

        // Do basic automatic PARAM checks on incoming data, using params description
        // If any problems are found then exceptions are thrown with helpful error messages
        $params = self::validate_parameters(self::get_users_courses_parameters(), array('userid'=>$userid));

302
303
        $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible,
                   summary, summaryformat, format, showgrades, lang, enablecompletion');
304
305
306
        $result = array();

        foreach ($courses as $course) {
307
            $context = context_course::instance($course->id, IGNORE_MISSING);
308
309
310
311
312
313
            try {
                self::validate_context($context);
            } catch (Exception $e) {
                // current user can not access this course, sorry we can not disclose who is enrolled in this course!
                continue;
            }
314

315
316
317
318
319
            if ($userid != $USER->id and !has_capability('moodle/course:viewparticipants', $context)) {
                // we need capability to view participants
                continue;
            }

320
            list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context);
321
            $enrolledsql = "SELECT COUNT('x') FROM ($enrolledsqlselect) enrolleduserids";
322
323
            $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
327
328
329
330
331

            $result[] = array('id' => $course->id, 'shortname' => $course->shortname, 'fullname' => $course->fullname,
                'idnumber' => $course->idnumber, 'visible' => $course->visible, 'enrolledusercount' => $enrolledusercount,
                'summary' => $course->summary, 'summaryformat' => $course->summaryformat, 'format' => $course->format,
                'showgrades' => $course->showgrades, 'lang' => $course->lang, 'enablecompletion' => $course->enablecompletion
                );
332
        }
333

334
335
336
337
338
        return $result;
    }

    /**
     * Returns description of method result value
339
     *
340
341
342
343
344
345
346
347
348
     * @return external_description
     */
    public static function get_users_courses_returns() {
        return new external_multiple_structure(
            new external_single_structure(
                array(
                    'id'        => new external_value(PARAM_INT, 'id of course'),
                    'shortname' => new external_value(PARAM_RAW, 'short name of course'),
                    'fullname'  => new external_value(PARAM_RAW, 'long name of course'),
349
                    'enrolledusercount' => new external_value(PARAM_INT, 'Number of enrolled users in this course'),
350
351
                    'idnumber'  => new external_value(PARAM_RAW, 'id number of course'),
                    'visible'   => new external_value(PARAM_INT, '1 means visible, 0 means hidden course'),
352
353
354
355
356
                    'summary'   => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
                    'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
                    'format'    => new external_value(PARAM_PLUGIN, 'course format: weeks, topics, social, site', VALUE_OPTIONAL),
                    'showgrades' => new external_value(PARAM_BOOL, 'true if grades are shown, otherwise false', VALUE_OPTIONAL),
                    'lang'      => new external_value(PARAM_LANG, 'forced course language', VALUE_OPTIONAL),
357
358
                    'enablecompletion' => new external_value(PARAM_BOOL, 'true if completion is enabled, otherwise false',
                                                                VALUE_OPTIONAL)
359
360
361
362
                )
            )
        );
    }
Sam Hemelryk's avatar
Sam Hemelryk committed
363

364
365
    /**
     * Returns description of method parameters
366
     *
367
368
369
370
371
372
373
374
375
376
377
378
     * @return external_function_parameters
     */
    public static function get_enrolled_users_parameters() {
        return new external_function_parameters(
            array(
                'courseid' => new external_value(PARAM_INT, 'course id'),
                'options'  => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'name'  => new external_value(PARAM_ALPHANUMEXT, 'option name'),
                            'value' => new external_value(PARAM_RAW, 'option value')
                        )
379
380
                    ), 'Option names:
                            * withcapability (string) return only users with this capability. This option requires \'moodle/role:review\' on the course context.
381
382
383
384
                            * groupid (integer) return only users in this group id. If the course has groups enabled and this param
                                                isn\'t defined, returns all the viewable users.
                                                This option requires \'moodle/site:accessallgroups\' on the course context if the
                                                user doesn\'t belong to the group.
385
386
387
                            * onlyactive (integer) return only users with active enrolments and matching time restrictions. This option requires \'moodle/course:enrolreview\' on the course context.
                            * userfields (\'string, string, ...\') return only the values of these user fields.
                            * limitfrom (integer) sql limit from.
388
389
390
391
                            * limitnumber (integer) maximum number of returned users.
                            * sortby (string) sort by id, firstname or lastname. For ordering like the site does, use siteorder.
                            * sortdirection (string) ASC or DESC',
                            VALUE_DEFAULT, array()),
392
393
394
395
396
397
            )
        );
    }

    /**
     * Get course participants details
398
     *
399
400
     * @param int $courseid  course id
     * @param array $options options {
401
402
403
     *                                'name' => option name
     *                                'value' => option value
     *                               }
404
405
     * @return array An array of users
     */
406
    public static function get_enrolled_users($courseid, $options = array()) {
407
408
409
410
        global $CFG, $USER, $DB;
        require_once($CFG->dirroot . "/user/lib.php");

        $params = self::validate_parameters(
411
            self::get_enrolled_users_parameters(),
412
413
414
415
416
417
418
419
            array(
                'courseid'=>$courseid,
                'options'=>$options
            )
        );
        $withcapability = '';
        $groupid        = 0;
        $onlyactive     = false;
420
        $userfields     = array();
421
422
        $limitfrom = 0;
        $limitnumber = 0;
423
424
425
        $sortby = 'us.id';
        $sortparams = array();
        $sortdirection = 'ASC';
426
427
428
429
430
431
432
433
434
435
436
        foreach ($options as $option) {
            switch ($option['name']) {
            case 'withcapability':
                $withcapability = $option['value'];
                break;
            case 'groupid':
                $groupid = (int)$option['value'];
                break;
            case 'onlyactive':
                $onlyactive = !empty($option['value']);
                break;
437
438
439
440
441
            case 'userfields':
                $thefields = explode(',', $option['value']);
                foreach ($thefields as $f) {
                    $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
                }
442
                break;
443
444
445
446
447
            case 'limitfrom' :
                $limitfrom = clean_param($option['value'], PARAM_INT);
                break;
            case 'limitnumber' :
                $limitnumber = clean_param($option['value'], PARAM_INT);
448
                break;
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
            case 'sortby':
                $sortallowedvalues = array('id', 'firstname', 'lastname', 'siteorder');
                if (!in_array($option['value'], $sortallowedvalues)) {
                    throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $option['value'] . '),' .
                        'allowed values are: ' . implode(',', $sortallowedvalues));
                }
                if ($option['value'] == 'siteorder') {
                    list($sortby, $sortparams) = users_order_by_sql('us');
                } else {
                    $sortby = 'us.' . $option['value'];
                }
                break;
            case 'sortdirection':
                $sortdirection = strtoupper($option['value']);
                $directionallowedvalues = array('ASC', 'DESC');
                if (!in_array($sortdirection, $directionallowedvalues)) {
                    throw new invalid_parameter_exception('Invalid value for sortdirection parameter
                        (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues));
                }
                break;
469
470
471
            }
        }

472
        $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
473
        $coursecontext = context_course::instance($courseid, IGNORE_MISSING);
474
        if ($courseid == SITEID) {
475
            $context = context_system::instance();
476
477
478
479
480
481
482
483
484
        } else {
            $context = $coursecontext;
        }
        try {
            self::validate_context($context);
        } catch (Exception $e) {
            $exceptionparam = new stdClass();
            $exceptionparam->message = $e->getMessage();
            $exceptionparam->courseid = $params['courseid'];
485
            throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
486
487
        }

488
489
490
491
492
493
494
495
496
497
        if ($courseid == SITEID) {
            require_capability('moodle/site:viewparticipants', $context);
        } else {
            require_capability('moodle/course:viewparticipants', $context);
        }
        // to overwrite this parameter, you need role:review capability
        if ($withcapability) {
            require_capability('moodle/role:review', $coursecontext);
        }
        // need accessallgroups capability if you want to overwrite this option
498
        if (!empty($groupid) && !groups_is_member($groupid)) {
499
500
501
502
503
504
505
            require_capability('moodle/site:accessallgroups', $coursecontext);
        }
        // to overwrite this option, you need course:enrolereview permission
        if ($onlyactive) {
            require_capability('moodle/course:enrolreview', $coursecontext);
        }

506
        list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
507
508
509
        $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
        $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
        $enrolledparams['contextlevel'] = CONTEXT_USER;
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531

        $groupjoin = '';
        if (empty($groupid) && groups_get_course_groupmode($course) == SEPARATEGROUPS &&
                !has_capability('moodle/site:accessallgroups', $coursecontext)) {
            // Filter by groups the user can view.
            $usergroups = groups_get_user_groups($course->id);
            if (!empty($usergroups['0'])) {
                list($groupsql, $groupparams) = $DB->get_in_or_equal($usergroups['0'], SQL_PARAMS_NAMED);
                $groupjoin = "JOIN {groups_members} gm ON (u.id = gm.userid AND gm.groupid $groupsql)";
                $enrolledparams = array_merge($enrolledparams, $groupparams);
            } else {
                // User doesn't belong to any group, so he can't see any user. Return an empty array.
                return array();
            }
        }
        $sql = "SELECT us.*
                  FROM {user} us
                  JOIN (
                      SELECT DISTINCT u.id $ctxselect
                        FROM {user} u $ctxjoin $groupjoin
                       WHERE u.id IN ($enrolledsql)
                  ) q ON q.id = us.id
532
533
                ORDER BY $sortby $sortdirection";
        $enrolledparams = array_merge($enrolledparams, $sortparams);
534
        $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
535
536
        $users = array();
        foreach ($enrolledusers as $user) {
537
            context_helper::preload_from_record($user);
538
            if ($userdetails = user_get_user_details($user, $course, $userfields)) {
539
540
541
542
543
544
545
                $users[] = $userdetails;
            }
        }
        $enrolledusers->close();

        return $users;
    }
Sam Hemelryk's avatar
Sam Hemelryk committed
546

547
548
    /**
     * Returns description of method result value
549
     *
550
551
552
553
554
555
     * @return external_description
     */
    public static function get_enrolled_users_returns() {
        return new external_multiple_structure(
            new external_single_structure(
                array(
556
                    'id'    => new external_value(PARAM_INT, 'ID of the user'),
557
558
559
560
561
                    'username'    => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL),
                    'firstname'   => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
                    'lastname'    => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
                    'fullname'    => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
                    'email'       => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
562
                    'address'     => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL),
563
564
565
566
567
568
569
570
571
                    'phone1'      => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
                    'phone2'      => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
                    'icq'         => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
                    'skype'       => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
                    'yahoo'       => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
                    'aim'         => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
                    'msn'         => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
                    'department'  => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
                    'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
572
                    'idnumber'    => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
573
574
575
576
                    'interests'   => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
                    'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
                    'lastaccess'  => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
                    'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
577
                    'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
578
579
580
                    'city'        => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
                    'url'         => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
                    'country'     => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
581
582
                    'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version', VALUE_OPTIONAL),
                    'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version', VALUE_OPTIONAL),
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
                    'customfields' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'type'  => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
                                'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
                                'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
                                'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
                            )
                        ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
                    'groups' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'id'  => new external_value(PARAM_INT, 'group id'),
                                'name' => new external_value(PARAM_RAW, 'group name'),
                                'description' => new external_value(PARAM_RAW, 'group description'),
598
                                'descriptionformat' => new external_format_value('description'),
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
                            )
                        ), 'user groups', VALUE_OPTIONAL),
                    'roles' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'roleid'       => new external_value(PARAM_INT, 'role id'),
                                'name'         => new external_value(PARAM_RAW, 'role name'),
                                'shortname'    => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
                                'sortorder'    => new external_value(PARAM_INT, 'role sortorder')
                            )
                        ), 'user roles', VALUE_OPTIONAL),
                    'preferences' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'name'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
                                'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
                            )
                    ), 'User preferences', VALUE_OPTIONAL),
                    'enrolledcourses' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'id'  => new external_value(PARAM_INT, 'Id of the course'),
                                'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
                                'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
                            )
                    ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
                )
            )
        );
    }

630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
    /**
     * Returns description of get_course_enrolment_methods() parameters
     *
     * @return external_function_parameters
     */
    public static function get_course_enrolment_methods_parameters() {
        return new external_function_parameters(
            array(
                'courseid' => new external_value(PARAM_INT, 'Course id')
            )
        );
    }

    /**
     * Get list of active course enrolment methods for current user.
     *
     * @param int $courseid
     * @return array of course enrolment methods
     */
    public static function get_course_enrolment_methods($courseid) {

        $params = self::validate_parameters(self::get_course_enrolment_methods_parameters(), array('courseid' => $courseid));

        $coursecontext = context_course::instance($params['courseid']);
        $categorycontext = $coursecontext->get_parent_context();
        self::validate_context($categorycontext);

        $result = array();
        $enrolinstances = enrol_get_instances($params['courseid'], true);
        foreach ($enrolinstances as $enrolinstance) {
            if ($enrolplugin = enrol_get_plugin($enrolinstance->enrol)) {
                if ($instanceinfo = $enrolplugin->get_enrol_info($enrolinstance)) {
                    $result[] = (array) $instanceinfo;
                }
            }
        }
        return $result;
    }

    /**
     * Returns description of get_course_enrolment_methods() result value
     *
     * @return external_description
     */
    public static function get_course_enrolment_methods_returns() {
        return new external_multiple_structure(
            new external_single_structure(
                array(
                    'id' => new external_value(PARAM_INT, 'id of course enrolment instance'),
                    'courseid' => new external_value(PARAM_INT, 'id of course'),
                    'type' => new external_value(PARAM_PLUGIN, 'type of enrolment plugin'),
                    'name' => new external_value(PARAM_RAW, 'name of enrolment plugin'),
                    'status' => new external_value(PARAM_RAW, 'status of enrolment plugin'),
                    'wsfunction' => new external_value(PARAM_ALPHANUMEXT, 'webservice function to get more information', VALUE_OPTIONAL),
                )
            )
        );
    }
688
689
690
}

/**
691
692
693
694
695
696
697
 * Role external functions
 *
 * @package    core_role
 * @category   external
 * @copyright  2011 Jerome Mouneyrac
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.2
698
699
700
701
702
 */
class core_role_external extends external_api {

    /**
     * Returns description of method parameters
703
     *
704
705
706
707
708
709
710
711
712
713
     * @return external_function_parameters
     */
    public static function assign_roles_parameters() {
        return new external_function_parameters(
            array(
                'assignments' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'roleid'    => new external_value(PARAM_INT, 'Role to assign to the user'),
                            'userid'    => new external_value(PARAM_INT, 'The user that is going to be assigned'),
714
715
716
717
                            'contextid' => new external_value(PARAM_INT, 'The context to assign the user role in', VALUE_OPTIONAL),
                            'contextlevel' => new external_value(PARAM_ALPHA, 'The context level to assign the user role in
                                    (block, course, coursecat, system, user, module)', VALUE_OPTIONAL),
                            'instanceid' => new external_value(PARAM_INT, 'The Instance id of item where the role needs to be assigned', VALUE_OPTIONAL),
718
719
720
721
722
723
724
725
726
727
                        )
                    )
                )
            )
        );
    }

    /**
     * Manual role assignments to users
     *
728
     * @param array $assignments An array of manual role assignment
729
730
731
732
733
734
735
736
737
738
739
     */
    public static function assign_roles($assignments) {
        global $DB;

        // Do basic automatic PARAM checks on incoming data, using params description
        // If any problems are found then exceptions are thrown with helpful error messages
        $params = self::validate_parameters(self::assign_roles_parameters(), array('assignments'=>$assignments));

        $transaction = $DB->start_delegated_transaction();

        foreach ($params['assignments'] as $assignment) {
740
            // Ensure correct context level with a instance id or contextid is passed.
741
            $context = self::get_context_from_params($assignment);
742
743

            // Ensure the current user is allowed to run this function in the enrolment context.
744
745
746
747
748
749
            self::validate_context($context);
            require_capability('moodle/role:assign', $context);

            // throw an exception if user is not able to assign the role in this context
            $roles = get_assignable_roles($context, ROLENAME_SHORT);

750
            if (!array_key_exists($assignment['roleid'], $roles)) {
751
752
753
                throw new invalid_parameter_exception('Can not assign roleid='.$assignment['roleid'].' in contextid='.$assignment['contextid']);
            }

754
            role_assign($assignment['roleid'], $assignment['userid'], $context->id);
755
756
757
758
759
760
761
        }

        $transaction->allow_commit();
    }

    /**
     * Returns description of method result value
762
763
     *
     * @return null
764
765
766
767
768
769
770
771
     */
    public static function assign_roles_returns() {
        return null;
    }


    /**
     * Returns description of method parameters
772
     *
773
774
775
776
777
778
779
780
781
782
     * @return external_function_parameters
     */
    public static function unassign_roles_parameters() {
        return new external_function_parameters(
            array(
                'unassignments' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'roleid'    => new external_value(PARAM_INT, 'Role to assign to the user'),
                            'userid'    => new external_value(PARAM_INT, 'The user that is going to be assigned'),
783
784
785
786
                            'contextid' => new external_value(PARAM_INT, 'The context to unassign the user role from', VALUE_OPTIONAL),
                            'contextlevel' => new external_value(PARAM_ALPHA, 'The context level to unassign the user role in
+                                    (block, course, coursecat, system, user, module)', VALUE_OPTIONAL),
                            'instanceid' => new external_value(PARAM_INT, 'The Instance id of item where the role needs to be unassigned', VALUE_OPTIONAL),
787
788
789
790
791
792
793
794
795
796
                        )
                    )
                )
            )
        );
    }

     /**
     * Unassign roles from users
     *
797
     * @param array $unassignments An array of unassignment
798
799
800
801
802
803
804
805
806
807
808
809
     */
    public static function unassign_roles($unassignments) {
         global $DB;

        // Do basic automatic PARAM checks on incoming data, using params description
        // If any problems are found then exceptions are thrown with helpful error messages
        $params = self::validate_parameters(self::unassign_roles_parameters(), array('unassignments'=>$unassignments));

        $transaction = $DB->start_delegated_transaction();

        foreach ($params['unassignments'] as $unassignment) {
            // Ensure the current user is allowed to run this function in the unassignment context
810
            $context = self::get_context_from_params($unassignment);
811
812
813
814
815
            self::validate_context($context);
            require_capability('moodle/role:assign', $context);

            // throw an exception if user is not able to unassign the role in this context
            $roles = get_assignable_roles($context, ROLENAME_SHORT);
816
            if (!array_key_exists($unassignment['roleid'], $roles)) {
817
818
819
                throw new invalid_parameter_exception('Can not unassign roleid='.$unassignment['roleid'].' in contextid='.$unassignment['contextid']);
            }

820
            role_unassign($unassignment['roleid'], $unassignment['userid'], $context->id);
821
822
823
824
825
826
827
        }

        $transaction->allow_commit();
    }

   /**
     * Returns description of method result value
828
     *
829
830
831
832
833
834
835
836
837
     * @return null
     */
    public static function unassign_roles_returns() {
        return null;
    }
}


/**
838
839
840
841
842
843
844
845
846
 * Deprecated enrol and role external functions
 *
 * @package    core_enrol
 * @copyright  2010 Jerome Mouneyrac
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
 * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
 * @see core_enrol_external
 * @see core_role_external
847
 */
848
849
class moodle_enrol_external extends external_api {

850

851
852
    /**
     * Returns description of method parameters
853
     *
854
     * @return external_function_parameters
855
856
857
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @see core_enrol_external::get_enrolled_users_parameters()
858
     */
859
    public static function get_enrolled_users_parameters() {
860
861
862
        return new external_function_parameters(
            array(
                'courseid'       => new external_value(PARAM_INT, 'Course id'),
863
864
865
                'withcapability' => new external_value(PARAM_CAPABILITY, 'User should have this capability', VALUE_DEFAULT, null),
                'groupid'        => new external_value(PARAM_INT, 'Group id, null means all groups', VALUE_DEFAULT, null),
                'onlyactive'     => new external_value(PARAM_INT, 'True means only active, false means all participants', VALUE_DEFAULT, 0),
866
867
868
869
870
871
            )
        );
    }

    /**
     * Get list of course participants.
872
     *
873
874
875
876
877
     * @param int $courseid
     * @param text $withcapability
     * @param int $groupid
     * @param bool $onlyactive
     * @return array of course participants
878
879
880
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @see core_enrol_external::get_enrolled_users()
881
     */
882
883
    public static function get_enrolled_users($courseid, $withcapability = null, $groupid = null, $onlyactive = false) {
        global $DB, $CFG, $USER;
884
885
886

        // Do basic automatic PARAM checks on incoming data, using params description
        // If any problems are found then exceptions are thrown with helpful error messages
887
888
889
890
891
892
        $params = self::validate_parameters(self::get_enrolled_users_parameters(), array(
            'courseid'=>$courseid,
            'withcapability'=>$withcapability,
            'groupid'=>$groupid,
            'onlyactive'=>$onlyactive)
        );
893

894
        $coursecontext = context_course::instance($params['courseid'], IGNORE_MISSING);
895
        if ($courseid == SITEID) {
896
            $context = context_system::instance();
897
898
899
900
        } else {
            $context = $coursecontext;
        }

901
902
903
        try {
            self::validate_context($context);
        } catch (Exception $e) {
904
905
906
            $exceptionparam = new stdClass();
            $exceptionparam->message = $e->getMessage();
            $exceptionparam->courseid = $params['courseid'];
907
            throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
908
        }
909
910
911
912
913
914
915
916
917
918

        if ($courseid == SITEID) {
            require_capability('moodle/site:viewparticipants', $context);
        } else {
            require_capability('moodle/course:viewparticipants', $context);
        }

        if ($withcapability) {
            require_capability('moodle/role:review', $coursecontext);
        }
919
920
        if ($groupid && groups_is_member($groupid)) {
            require_capability('moodle/site:accessallgroups', $coursecontext);
921
        }
922
        if ($onlyactive) {
923
924
925
            require_capability('moodle/course:enrolreview', $coursecontext);
        }

926
927
        list($sqlparams, $params) =  get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
        $sql = "SELECT ue.userid, e.courseid, u.firstname, u.lastname, u.username, c.id as usercontextid
928
929
                  FROM {user_enrolments} ue
                  JOIN {enrol} e ON (e.id = ue.enrolid)
930
931
932
933
                  JOIN {user} u ON (ue.userid = u.id)
                  JOIN {context} c ON (u.id = c.instanceid AND contextlevel = " . CONTEXT_USER . ")
                  WHERE e.courseid = :courseid AND ue.userid IN ($sqlparams)
                  GROUP BY ue.userid, e.courseid, u.firstname, u.lastname, u.username, c.id";
934
        $params['courseid'] = $courseid;
935
936
        $enrolledusers = $DB->get_records_sql($sql, $params);
        $result = array();
937
938
        $isadmin = is_siteadmin($USER);
        $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
939
        foreach ($enrolledusers as $enrolleduser) {
940
941
            $profilimgurl = moodle_url::make_pluginfile_url($enrolleduser->usercontextid, 'user', 'icon', NULL, '/', 'f1');
            $profilimgurlsmall = moodle_url::make_pluginfile_url($enrolleduser->usercontextid, 'user', 'icon', NULL, '/', 'f2');
942
943
            $resultuser = array(
                'courseid' => $enrolleduser->courseid,
944
                'userid' => $enrolleduser->userid,
945
                'fullname' => fullname($enrolleduser),
946
                'profileimgurl' => $profilimgurl->out(false),
947
948
949
                'profileimgurlsmall' => $profilimgurlsmall->out(false)
            );
            // check if we can return username
950
951
952
            if ($isadmin) {
                $resultuser['username'] = $enrolleduser->username;
            }
953
954
            // check if we can return first and last name
            if ($isadmin or $canviewfullnames) {
955
956
957
958
                $resultuser['firstname'] = $enrolleduser->firstname;
                $resultuser['lastname'] = $enrolleduser->lastname;
            }
            $result[] = $resultuser;
959
960
961
        }

        return $result;
962
963
964
965
    }

    /**
     * Returns description of method result value
966
     *
967
     * @return external_description
968
969
970
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @see core_enrol_external::get_enrolled_users_returns()
971
972
     */
    public static function get_enrolled_users_returns() {
973
974
975
976
977
        return new external_multiple_structure(
            new external_single_structure(
                array(
                    'courseid' => new external_value(PARAM_INT, 'id of course'),
                    'userid' => new external_value(PARAM_INT, 'id of user'),
978
979
980
981
982
983
                    'firstname' => new external_value(PARAM_RAW, 'first name of user', VALUE_OPTIONAL),
                    'lastname' => new external_value(PARAM_RAW, 'last name of user', VALUE_OPTIONAL),
                    'fullname' => new external_value(PARAM_RAW, 'fullname of user'),
                    'username' => new external_value(PARAM_RAW, 'username of user', VALUE_OPTIONAL),
                    'profileimgurl' => new external_value(PARAM_URL, 'url of the profile image'),
                    'profileimgurlsmall' => new external_value(PARAM_URL, 'url of the profile image (small version)')
984
                )
985
986
987
988
            )
        );
    }

989
990
991
992
993
994
995
996
997
    /**
     * Marking the method as deprecated.
     *
     * @return bool
     */
    public static function get_enrolled_users_is_deprecated() {
        return true;
    }

998
999
    /**
     * Returns description of method parameters
1000
     *