externallib.php 44.5 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
20
/**
 * External user API
 *
21
22
23
 * @package    core_user
 * @category   external
 * @copyright  2009 Petr Skodak
24
25
26
27
28
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

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

29
/**
30
31
32
33
34
35
36
 * User external functions
 *
 * @package    core_user
 * @category   external
 * @copyright  2011 Jerome Mouneyrac
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.2
37
38
 */
class core_user_external extends external_api {
39

Petr Skoda's avatar
Petr Skoda committed
40
41
    /**
     * Returns description of method parameters
42
     *
Petr Skoda's avatar
Petr Skoda committed
43
     * @return external_function_parameters
44
     * @since Moodle 2.2
Petr Skoda's avatar
Petr Skoda committed
45
     */
skodak's avatar
skodak committed
46
    public static function create_users_parameters() {
Petr Skoda's avatar
Petr Skoda committed
47
48
        global $CFG;

49
50
51
52
53
        return new external_function_parameters(
            array(
                'users' => new external_multiple_structure(
                    new external_single_structure(
                        array(
54
                            'username'    => new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config. Must be lowercase.'),
Petr Skoda's avatar
Petr Skoda committed
55
                            'password'    => new external_value(PARAM_RAW, 'Plain text password consisting of any characters'),
Petr Skoda's avatar
Petr Skoda committed
56
57
58
                            'firstname'   => new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
                            'lastname'    => new external_value(PARAM_NOTAGS, 'The family name of the user'),
                            'email'       => new external_value(PARAM_EMAIL, 'A valid and unique email address'),
59
                            'auth'        => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT, 'manual', NULL_NOT_ALLOWED),
60
                            'idnumber'    => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_DEFAULT, ''),
61
                            'lang'        => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_DEFAULT, $CFG->lang, NULL_NOT_ALLOWED),
62
                            'theme'       => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
63
                            'timezone'    => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
64
                            'mailformat'  => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
65
                            'description' => new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
66
67
                            'city'        => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
                            'country'     => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
68
69
70
                            'preferences' => new external_multiple_structure(
                                new external_single_structure(
                                    array(
Petr Skoda's avatar
Petr Skoda committed
71
                                        'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
72
73
                                        'value' => new external_value(PARAM_RAW, 'The value of the preference')
                                    )
74
                                ), 'User preferences', VALUE_OPTIONAL),
75
76
77
                            'customfields' => new external_multiple_structure(
                                new external_single_structure(
                                    array(
Petr Skoda's avatar
Petr Skoda committed
78
                                        'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
79
80
                                        'value' => new external_value(PARAM_RAW, 'The value of the custom field')
                                    )
81
                                ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
82
83
84
85
86
                        )
                    )
                )
            )
        );
87
88
    }

skodak's avatar
skodak committed
89
    /**
90
91
     * Create one or more users
     *
92
     * @param array $users An array of users to create.
Petr Skoda's avatar
Petr Skoda committed
93
     * @return array An array of arrays
94
     * @since Moodle 2.2
95
     */
Petr Skoda's avatar
Petr Skoda committed
96
    public static function create_users($users) {
97
        global $CFG, $DB;
98
        require_once($CFG->dirroot."/lib/weblib.php");
99
        require_once($CFG->dirroot."/user/lib.php");
100
        require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function
101

102
        // Ensure the current user is allowed to run this function
103
        $context = context_system::instance();
104
        self::validate_context($context);
105
        require_capability('moodle/user:create', $context);
106

107
108
        // Do basic automatic PARAM checks on incoming data, using params description
        // If any problems are found then exceptions are thrown with helpful error messages
Petr Skoda's avatar
Petr Skoda committed
109
        $params = self::validate_parameters(self::create_users_parameters(), array('users'=>$users));
110

Petr Skoda's avatar
Petr Skoda committed
111
112
113
114
115
        $availableauths  = get_plugin_list('auth');
        unset($availableauths['mnet']);       // these would need mnethostid too
        unset($availableauths['webservice']); // we do not want new webservice users for now

        $availablethemes = get_plugin_list('theme');
116
        $availablelangs  = get_string_manager()->get_list_of_translations();
117

118
        $transaction = $DB->start_delegated_transaction();
119

120
        $userids = array();
Petr Skoda's avatar
Petr Skoda committed
121
        foreach ($params['users'] as $user) {
Petr Skoda's avatar
Petr Skoda committed
122
123
124
            // Make sure that the username doesn't already exist
            if ($DB->record_exists('user', array('username'=>$user['username'], 'mnethostid'=>$CFG->mnet_localhost_id))) {
                throw new invalid_parameter_exception('Username already exists: '.$user['username']);
125
126
            }

Petr Skoda's avatar
Petr Skoda committed
127
128
129
            // Make sure auth is valid
            if (empty($availableauths[$user['auth']])) {
                throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
130
131
            }

Petr Skoda's avatar
Petr Skoda committed
132
133
134
            // Make sure lang is valid
            if (empty($availablelangs[$user['lang']])) {
                throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
135
136
            }

Petr Skoda's avatar
Petr Skoda committed
137
            // Make sure lang is valid
138
139
140
141
            if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { //theme is VALUE_OPTIONAL,
                                                                                     // so no default value.
                                                                                     // We need to test if the client sent it
                                                                                     // => !empty($user['theme'])
Petr Skoda's avatar
Petr Skoda committed
142
                throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
143
            }
144

145
            $user['confirmed'] = true;
146
            $user['mnethostid'] = $CFG->mnet_localhost_id;
147

148
149
150
151
152
153
154
155
156
            // Start of user info validation.
            // Lets make sure we validate current user info as handled by current GUI. see user/editadvanced_form.php function validation()
            if (!validate_email($user['email'])) {
                throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
            } else if ($DB->record_exists('user', array('email'=>$user['email'], 'mnethostid'=>$user['mnethostid']))) {
                throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
            }
            // End of user info validation.

157
158
            // create the user data now!
            $user['id'] = user_create_user($user);
159

160
161
162
163
164
165
166
167
168
            // custom fields
            if(!empty($user['customfields'])) {
                foreach($user['customfields'] as $customfield) {
                    $user["profile_field_".$customfield['type']] = $customfield['value']; //profile_save_data() saves profile file
                                                                                            //it's expecting a user with the correct id,
                                                                                            //and custom field to be named profile_field_"shortname"
                }
                profile_save_data((object) $user);
            }
Petr Skoda's avatar
Petr Skoda committed
169

170
171
172
173
174
175
            //preferences
            if (!empty($user['preferences'])) {
                foreach($user['preferences'] as $preference) {
                    set_user_preference($preference['type'], $preference['value'],$user['id']);
                }
            }
skodak's avatar
skodak committed
176

177
            $userids[] = array('id'=>$user['id'], 'username'=>$user['username']);
178
179
        }

180
        $transaction->allow_commit();
Petr Skoda's avatar
Petr Skoda committed
181

182
        return $userids;
183
184
    }

Petr Skoda's avatar
Petr Skoda committed
185
186
   /**
     * Returns description of method result value
187
     *
Petr Skoda's avatar
Petr Skoda committed
188
     * @return external_description
189
     * @since Moodle 2.2
Petr Skoda's avatar
Petr Skoda committed
190
191
192
193
194
195
     */
    public static function create_users_returns() {
        return new external_multiple_structure(
            new external_single_structure(
                array(
                    'id'       => new external_value(PARAM_INT, 'user id'),
196
                    'username' => new external_value(PARAM_USERNAME, 'user name'),
Petr Skoda's avatar
Petr Skoda committed
197
198
199
                )
            )
        );
skodak's avatar
skodak committed
200
201
202
    }


Petr Skoda's avatar
Petr Skoda committed
203
204
    /**
     * Returns description of method parameters
205
     *
Petr Skoda's avatar
Petr Skoda committed
206
     * @return external_function_parameters
207
     * @since Moodle 2.2
Petr Skoda's avatar
Petr Skoda committed
208
     */
skodak's avatar
skodak committed
209
    public static function delete_users_parameters() {
Petr Skoda's avatar
Petr Skoda committed
210
211
212
213
214
        return new external_function_parameters(
            array(
                'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
            )
        );
skodak's avatar
skodak committed
215
    }
Petr Skoda's avatar
Petr Skoda committed
216

217
218
    /**
     * Delete users
219
     *
220
     * @param array $userids
Sam Hemelryk's avatar
Sam Hemelryk committed
221
     * @return null
222
     * @since Moodle 2.2
223
     */
224
    public static function delete_users($userids) {
225
        global $CFG, $DB, $USER;
226
        require_once($CFG->dirroot."/user/lib.php");
227
228

        // Ensure the current user is allowed to run this function
229
        $context = context_system::instance();
230
231
232
        require_capability('moodle/user:delete', $context);
        self::validate_context($context);

233
        $params = self::validate_parameters(self::delete_users_parameters(), array('userids'=>$userids));
234
235
236
237
238

        $transaction = $DB->start_delegated_transaction();

        foreach ($params['userids'] as $userid) {
            $user = $DB->get_record('user', array('id'=>$userid, 'deleted'=>0), '*', MUST_EXIST);
239
            // must not allow deleting of admins or self!!!
240
241
242
243
244
            if (is_siteadmin($user)) {
                throw new moodle_exception('useradminodelete', 'error');
            }
            if ($USER->id == $user->id) {
                throw new moodle_exception('usernotdeletederror', 'error');
245
            }
246
            user_delete_user($user);
247
248
249
250
251
        }

        $transaction->allow_commit();

        return null;
252
    }
Petr Skoda's avatar
Petr Skoda committed
253
254
255

   /**
     * Returns description of method result value
256
257
258
     *
     * @return null
     * @since Moodle 2.2
Petr Skoda's avatar
Petr Skoda committed
259
     */
skodak's avatar
skodak committed
260
    public static function delete_users_returns() {
Petr Skoda's avatar
Petr Skoda committed
261
        return null;
skodak's avatar
skodak committed
262
    }
263
264


Petr Skoda's avatar
Petr Skoda committed
265
266
    /**
     * Returns description of method parameters
267
     *
Petr Skoda's avatar
Petr Skoda committed
268
     * @return external_function_parameters
269
     * @since Moodle 2.2
Petr Skoda's avatar
Petr Skoda committed
270
     */
skodak's avatar
skodak committed
271
    public static function update_users_parameters() {
272
        global $CFG;
273
        return new external_function_parameters(
274
275
276
277
            array(
                'users' => new external_multiple_structure(
                    new external_single_structure(
                        array(
278
                            'id'    => new external_value(PARAM_INT, 'ID of the user'),
279
                            'username'    => new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config. Must be lowercase.', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
280
281
282
283
                            'password'    => new external_value(PARAM_RAW, 'Plain text password consisting of any characters', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
                            'firstname'   => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
                            'lastname'    => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
                            'email'       => new external_value(PARAM_EMAIL, 'A valid and unique email address', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
284
                            'auth'        => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
285
                            'idnumber'    => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
286
                            'lang'        => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
287
                            'theme'       => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
288
                            'timezone'    => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
289
                            'mailformat'  => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
290
                            'description' => new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
291
292
293
294
295
296
297
298
                            'city'        => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
                            'country'     => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
                            'customfields' => new external_multiple_structure(
                                new external_single_structure(
                                    array(
                                        'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
                                        'value' => new external_value(PARAM_RAW, 'The value of the custom field')
                                    )
299
                                ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
300
301
302
303
304
305
306
                            'preferences' => new external_multiple_structure(
                                new external_single_structure(
                                    array(
                                        'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
                                        'value' => new external_value(PARAM_RAW, 'The value of the preference')
                                    )
                                ), 'User preferences', VALUE_OPTIONAL),
307
308
309
310
311
                        )
                    )
                )
            )
        );
skodak's avatar
skodak committed
312
    }
313

314
315
    /**
     * Update users
316
     *
317
     * @param array $users
Sam Hemelryk's avatar
Sam Hemelryk committed
318
     * @return null
319
     * @since Moodle 2.2
320
     */
321
322
    public static function update_users($users) {
        global $CFG, $DB;
323
        require_once($CFG->dirroot."/user/lib.php");
324
        require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function
325
326

        // Ensure the current user is allowed to run this function
327
        $context = context_system::instance();
328
329
330
331
332
333
334
335
        require_capability('moodle/user:update', $context);
        self::validate_context($context);

        $params = self::validate_parameters(self::update_users_parameters(), array('users'=>$users));

        $transaction = $DB->start_delegated_transaction();

        foreach ($params['users'] as $user) {
336
            user_update_user($user);
337
338
339
340
341
342
343
344
345
346
            //update user custom fields
            if(!empty($user['customfields'])) {

                foreach($user['customfields'] as $customfield) {
                    $user["profile_field_".$customfield['type']] = $customfield['value']; //profile_save_data() saves profile file
                                                                                            //it's expecting a user with the correct id,
                                                                                            //and custom field to be named profile_field_"shortname"
                }
                profile_save_data((object) $user);
            }
347
348
349
350
351
352
353

            //preferences
            if (!empty($user['preferences'])) {
                foreach($user['preferences'] as $preference) {
                    set_user_preference($preference['type'], $preference['value'],$user['id']);
                }
            }
354
355
356
357
358
        }

        $transaction->allow_commit();

        return null;
359
    }
Petr Skoda's avatar
Petr Skoda committed
360
361
362

   /**
     * Returns description of method result value
363
364
365
     *
     * @return null
     * @since Moodle 2.2
Petr Skoda's avatar
Petr Skoda committed
366
     */
skodak's avatar
skodak committed
367
    public static function update_users_returns() {
Petr Skoda's avatar
Petr Skoda committed
368
        return null;
skodak's avatar
skodak committed
369
370
    }

Petr Skoda's avatar
Petr Skoda committed
371
372
    /**
     * Returns description of method parameters
373
     *
Petr Skoda's avatar
Petr Skoda committed
374
     * @return external_function_parameters
375
     * @since Moodle 2.2
Petr Skoda's avatar
Petr Skoda committed
376
     */
377
    public static function get_users_by_id_parameters() {
Petr Skoda's avatar
Petr Skoda committed
378
        return new external_function_parameters(
379
380
381
                array(
                    'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
                )
Petr Skoda's avatar
Petr Skoda committed
382
        );
skodak's avatar
skodak committed
383
    }
Petr Skoda's avatar
Petr Skoda committed
384

Petr Skoda's avatar
Petr Skoda committed
385
386
    /**
     * Get user information
387
388
389
     * - This function is matching the permissions of /user/profil.php
     * - It is also matching some permissions from /user/editadvanced.php for the following fields:
     *   auth, confirmed, idnumber, lang, theme, timezone, mailformat
390
     *
Petr Skoda's avatar
Petr Skoda committed
391
392
     * @param array $userids  array of user ids
     * @return array An array of arrays describing users
393
     * @since Moodle 2.2
Petr Skoda's avatar
Petr Skoda committed
394
     */
395
    public static function get_users_by_id($userids) {
396
        global $CFG, $USER, $DB;
397
        require_once($CFG->dirroot . "/user/lib.php");
398

399
400
        $params = self::validate_parameters(self::get_users_by_id_parameters(),
                array('userids'=>$userids));
401

Dongsheng Cai's avatar
Dongsheng Cai committed
402
403
404
405
406
407
        list($uselect, $ujoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
        list($sqluserids, $params) = $DB->get_in_or_equal($userids);
        $usersql = "SELECT u.* $uselect
                      FROM {user} u $ujoin
                     WHERE u.id $sqluserids";
        $users = $DB->get_recordset_sql($usersql, $params);
skodak's avatar
skodak committed
408

409
        $result = array();
410
        $hasuserupdatecap = has_capability('moodle/user:update', get_system_context());
skodak's avatar
skodak committed
411
        foreach ($users as $user) {
Dongsheng Cai's avatar
Dongsheng Cai committed
412
413
414
415
            if (!empty($user->deleted)) {
                continue;
            }
            context_instance_preload($user);
416
            $usercontext = context_user::instance($user->id, IGNORE_MISSING);
417
            self::validate_context($usercontext);
418
419
            $currentuser = ($user->id == $USER->id);

420
421
422
423
424
425
426
427
428
429
            if ($userarray  = user_get_user_details($user)) {
                //fields matching permissions from /user/editadvanced.php
                if ($currentuser or $hasuserupdatecap) {
                    $userarray['auth']       = $user->auth;
                    $userarray['confirmed']  = $user->confirmed;
                    $userarray['idnumber']   = $user->idnumber;
                    $userarray['lang']       = $user->lang;
                    $userarray['theme']      = $user->theme;
                    $userarray['timezone']   = $user->timezone;
                    $userarray['mailformat'] = $user->mailformat;
430
                }
431
                $result[] = $userarray;
Dongsheng Cai's avatar
Dongsheng Cai committed
432
            }
433
        }
Dongsheng Cai's avatar
Dongsheng Cai committed
434
        $users->close();
Petr Skoda's avatar
Petr Skoda committed
435
436

        return $result;
skodak's avatar
skodak committed
437
    }
Petr Skoda's avatar
Petr Skoda committed
438

439
    /**
Petr Skoda's avatar
Petr Skoda committed
440
     * Returns description of method result value
441
     *
Petr Skoda's avatar
Petr Skoda committed
442
     * @return external_description
443
     * @since Moodle 2.2
Petr Skoda's avatar
Petr Skoda committed
444
     */
445
    public static function get_users_by_id_returns() {
Petr Skoda's avatar
Petr Skoda committed
446
        return new external_multiple_structure(
Dongsheng Cai's avatar
Dongsheng Cai committed
447
448
            new external_single_structure(
                array(
449
                    'id'    => new external_value(PARAM_INT, 'ID of the user'),
450
451
452
453
454
                    '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),
455
                    'address'     => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL),
456
457
458
459
460
461
462
463
464
465
466
467
                    '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),
468
                    'auth'        => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
469
                    'confirmed'   => new external_value(PARAM_INT, 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
470
471
                    'idnumber'    => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
                    'lang'        => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
472
                    'theme'       => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
473
                    'timezone'    => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
474
                    'mailformat'  => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
475
                    'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
476
                    'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
477
478
479
480
481
                    '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),
                    'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
                    'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
Petr Skoda's avatar
Petr Skoda committed
482
                    'customfields' => new external_multiple_structure(
Dongsheng Cai's avatar
Dongsheng Cai committed
483
484
485
486
487
488
489
490
                        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),
491
                    'preferences' => new external_multiple_structure(
Dongsheng Cai's avatar
Dongsheng Cai committed
492
493
494
495
496
497
                        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),
498
                    'enrolledcourses' => new external_multiple_structure(
Dongsheng Cai's avatar
Dongsheng Cai committed
499
500
501
                        new external_single_structure(
                            array(
                                'id'  => new external_value(PARAM_INT, 'Id of the course'),
502
503
                                'fullname'  => new external_value(PARAM_RAW, 'Fullname of the course'),
                                'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
Dongsheng Cai's avatar
Dongsheng Cai committed
504
505
506
507
508
509
510
511
                            )
                    ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
                )
            )
        );
    }
    /**
     * Returns description of method parameters
512
     *
Dongsheng Cai's avatar
Dongsheng Cai committed
513
     * @return external_function_parameters
514
     * @since Moodle 2.2
Dongsheng Cai's avatar
Dongsheng Cai committed
515
     */
516
    public static function get_course_user_profiles_parameters() {
Dongsheng Cai's avatar
Dongsheng Cai committed
517
518
519
520
521
522
523
        return new external_function_parameters(
            array(
                'userlist' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'userid'    => new external_value(PARAM_INT, 'userid'),
                            'courseid'    => new external_value(PARAM_INT, 'courseid'),
524
                        )
Dongsheng Cai's avatar
Dongsheng Cai committed
525
                    )
Petr Skoda's avatar
Petr Skoda committed
526
                )
Dongsheng Cai's avatar
Dongsheng Cai committed
527
528
529
530
531
532
            )
        );
    }

    /**
     * Get course participant's details
533
     *
Dongsheng Cai's avatar
Dongsheng Cai committed
534
535
     * @param array $userlist  array of user ids and according course ids
     * @return array An array of arrays describing course participants
536
     * @since Moodle 2.2
Dongsheng Cai's avatar
Dongsheng Cai committed
537
     */
538
    public static function get_course_user_profiles($userlist) {
Dongsheng Cai's avatar
Dongsheng Cai committed
539
540
        global $CFG, $USER, $DB;
        require_once($CFG->dirroot . "/user/lib.php");
541
        $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist'=>$userlist));
Dongsheng Cai's avatar
Dongsheng Cai committed
542
543
544
545
546
547
548
549
550
551
552
553

        $userids = array();
        $courseids = array();
        foreach ($params['userlist'] as $value) {
            $userids[] = $value['userid'];
            $courseids[$value['userid']] = $value['courseid'];
        }

        // cache all courses
        $courses = array();
        list($cselect, $cjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
        list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids));
554
        $coursesql = "SELECT c.* $cselect
Dongsheng Cai's avatar
Dongsheng Cai committed
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
                        FROM {course} c $cjoin
                       WHERE c.id $sqlcourseids";
        $rs = $DB->get_recordset_sql($coursesql, $params);
        foreach ($rs as $course) {
            // adding course contexts to cache
            context_instance_preload($course);
            // cache courses
            $courses[$course->id] = $course;
        }
        $rs->close();

        list($uselect, $ujoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
        list($sqluserids, $params) = $DB->get_in_or_equal($userids);
        $usersql = "SELECT u.* $uselect
                      FROM {user} u $ujoin
                     WHERE u.id $sqluserids";
        $users = $DB->get_recordset_sql($usersql, $params);
        $result = array();
        foreach ($users as $user) {
            if (!empty($user->deleted)) {
                continue;
            }
            context_instance_preload($user);
            $course = $courses[$courseids[$user->id]];
579
            $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
Dongsheng Cai's avatar
Dongsheng Cai committed
580
            self::validate_context($context);
581
582
            if ($userarray = user_get_user_details($user, $course)) {
                $result[] = $userarray;
Dongsheng Cai's avatar
Dongsheng Cai committed
583
            }
584
        }
Dongsheng Cai's avatar
Dongsheng Cai committed
585

586
        $users->close();
Dongsheng Cai's avatar
Dongsheng Cai committed
587

588
589
        return $result;
    }
Dongsheng Cai's avatar
Dongsheng Cai committed
590

591
592
    /**
     * Returns description of method result value
593
     *
594
     * @return external_description
595
     * @since Moodle 2.2
596
     */
597
    public static function get_course_user_profiles_returns() {
598
599
600
        return new external_multiple_structure(
            new external_single_structure(
                array(
601
                    'id'    => new external_value(PARAM_INT, 'ID of the user'),
602
603
604
605
606
                    '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),
607
                    'address'     => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL),
608
609
610
611
612
613
614
615
616
                    '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),
617
                    'idnumber'    => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
618
619
620
621
                    '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),
622
                    'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
                    '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),
                    'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
                    'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
                    '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'),
643
                                'descriptionformat' => new external_format_value('description'),
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
                            )
                        ), '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)
                )
            )
        );
    }
674
675
}

676
677
678
679
680
681
682
683
684
685
 /**
 * Deprecated user external functions
 *
 * @package    core_user
 * @copyright  2009 Petr Skodak
 * @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.
 * @todo MDL-31194 This will be deleted in Moodle 2.5.
 * @see core_user_external
686
687
688
689
690
 */
class moodle_user_external extends external_api {

    /**
     * Returns description of method parameters
691
     *
692
     * @return external_function_parameters
693
694
695
696
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::create_users_parameters()
697
698
699
700
701
702
703
     */
    public static function create_users_parameters() {
        return core_user_external::create_users_parameters();
    }

    /**
     * Create one or more users
704
     *
705
706
     * @param array $users  An array of users to create.
     * @return array An array of arrays
707
708
709
710
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::create_users()
711
712
713
714
715
716
717
     */
    public static function create_users($users) {
        return core_user_external::create_users($users);
    }

   /**
     * Returns description of method result value
718
     *
719
     * @return external_description
720
721
722
723
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::create_users_returns()
724
725
726
727
728
729
730
731
     */
    public static function create_users_returns() {
        return core_user_external::create_users_returns();
    }


    /**
     * Returns description of method parameters
732
     *
733
     * @return external_function_parameters
734
735
736
737
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::delete_users_parameters()
738
739
740
741
742
743
744
     */
    public static function delete_users_parameters() {
        return core_user_external::delete_users_parameters();
    }

    /**
     * Delete users
745
     *
746
     * @param array $userids
Sam Hemelryk's avatar
Sam Hemelryk committed
747
     * @return null
748
749
750
751
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::delete_users()
752
753
754
755
756
757
758
     */
    public static function delete_users($userids) {
        return core_user_external::delete_users($userids);
    }

   /**
     * Returns description of method result value
759
760
761
762
763
764
     *
     * @return null
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::delete_users_returns()
765
766
767
768
769
770
771
772
     */
    public static function delete_users_returns() {
        return core_user_external::delete_users_returns();
    }


    /**
     * Returns description of method parameters
773
     *
774
     * @return external_function_parameters
775
776
777
778
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::update_users_parameters()
779
780
781
782
783
784
785
     */
    public static function update_users_parameters() {
        return core_user_external::update_users_parameters();
    }

    /**
     * Update users
786
     *
787
     * @param array $users
Sam Hemelryk's avatar
Sam Hemelryk committed
788
     * @return null
789
790
791
792
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::update_users()
793
794
795
796
797
798
799
     */
    public static function update_users($users) {
        return core_user_external::update_users($users);
    }

   /**
     * Returns description of method result value
800
801
802
803
804
805
     *
     * @return null
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::update_users_returns()
806
807
808
809
810
811
812
     */
    public static function update_users_returns() {
        return core_user_external::update_users_returns();
    }

    /**
     * Returns description of method parameters
813
     *
814
     * @return external_function_parameters
815
816
817
818
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::get_users_by_id_parameters()
819
820
821
822
823
824
825
826
827
828
     */
    public static function get_users_by_id_parameters() {
        return core_user_external::get_users_by_id_parameters();
    }

    /**
     * Get user information
     * - This function is matching the permissions of /user/profil.php
     * - It is also matching some permissions from /user/editadvanced.php for the following fields:
     *   auth, confirmed, idnumber, lang, theme, timezone, mailformat
829
     *
830
831
     * @param array $userids  array of user ids
     * @return array An array of arrays describing users
832
833
834
835
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::get_users_by_id()
836
837
838
839
840
841
842
     */
    public static function get_users_by_id($userids) {
        return core_user_external::get_users_by_id($userids);
    }

    /**
     * Returns description of method result value
843
     *
844
     * @return external_description
845
846
847
848
     * @since Moodle 2.0
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::get_users_by_id_returns()
849
850
851
852
853
854
     */
    public static function get_users_by_id_returns() {
        return core_user_external::get_users_by_id_returns();
    }
    /**
     * Returns description of method parameters
855
     *
856
     * @return external_function_parameters
857
858
859
860
     * @since Moodle 2.1
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::get_course_user_profiles_parameters()
861
862
863
864
865
866
867
     */
    public static function get_course_participants_by_id_parameters() {
        return core_user_external::get_course_user_profiles_parameters();
    }

    /**
     * Get course participant's details
868
     *
869
870
     * @param array $userlist  array of user ids and according course ids
     * @return array An array of arrays describing course participants
871
872
873
874
     * @since Moodle 2.1
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::get_course_user_profiles()
875
876
877
878
879
880
881
     */
    public static function get_course_participants_by_id($userlist) {
        return core_user_external::get_course_user_profiles($userlist);
    }

    /**
     * Returns description of method result value
882
     *
883
     * @return external_description
884
885
886
887
     * @since Moodle 2.1
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_user_external::get_course_user_profiles_returns()
888
889
890
891
     */
    public static function get_course_participants_by_id_returns() {
        return core_user_external::get_course_user_profiles_returns();
    }
Dongsheng Cai's avatar
Dongsheng Cai committed
892

893
894
    /**
     * Returns description of method parameters
895
     *
896
     * @return external_function_parameters
897
898
899
900
     * @since Moodle 2.1
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_enrol_external::get_enrolled_users_parameters()
901
902
     */
    public static function get_users_by_courseid_parameters() {
903
904
905
        global $CFG;
        require_once($CFG->dirroot . '/enrol/externallib.php');
        return core_enrol_external::get_enrolled_users_parameters();
906
    }
Dongsheng Cai's avatar
Dongsheng Cai committed
907

908
909
    /**
     * Get course participants details
910
     *
911
912
     * @param int $courseid  course id
     * @param array $options options {
913
914
915
     *                                'name' => option name
     *                                'value' => option value
     *                               }
916
     * @return array An array of users
917
918
919
920
     * @since Moodle 2.1
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_enrol_external::get_enrolled_users()
921
922
     */
    public static function get_users_by_courseid($courseid, $options) {
923
924
925
        global $CFG;
        require_once($CFG->dirroot . '/enrol/externallib.php');
        return core_enrol_external::get_enrolled_users($courseid, $options);
Dongsheng Cai's avatar
Dongsheng Cai committed
926
927
928
    }
    /**
     * Returns description of method result value
929
     *
Dongsheng Cai's avatar
Dongsheng Cai committed
930
     * @return external_description
931
932
933
934
     * @since Moodle 2.1
     * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
     * @todo MDL-31194 This will be deleted in Moodle 2.5.
     * @see core_enrol_external::get_enrolled_users_returns()
Dongsheng Cai's avatar
Dongsheng Cai committed
935
     */
936
    public static function get_users_by_courseid_returns() {
937
938
939
        global $CFG;
        require_once($CFG->dirroot . '/enrol/externallib.php');
        return core_enrol_external::get_enrolled_users_returns();
940
941
    }
}