Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
use core_external\external_description;
18
use core_external\external_value;
19
use core_external\external_format_value;
20
use core_external\external_single_structure;
21
use core_external\external_multiple_structure;
22
use core_external\external_function_parameters;
23
use core_external\external_warnings;
24
 
25
/**
26
 * User external functions
27
 *
28
 * @package    core_user
29
 * @category   external
30
 * @copyright  2011 Jerome Mouneyrac
31
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32
 * @since Moodle 2.2
33
 */
34
class core_user_external extends \core_external\external_api {
35
 
36
    /**
37
     * Returns description of method parameters
38
     *
39
     * @return external_function_parameters
40
     * @since Moodle 2.2
41
     */
42
    public static function create_users_parameters() {
43
        global $CFG;
44
        $userfields = [
45
            'createpassword' => new external_value(PARAM_BOOL, 'True if password should be created and mailed to user.',
46
                VALUE_OPTIONAL),
47
            // General.
48
            'username' => new external_value(core_user::get_property_type('username'),
49
                'Username policy is defined in Moodle security config.'),
50
            'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
51
                VALUE_DEFAULT, 'manual', core_user::get_property_null('auth')),
52
            'password' => new external_value(core_user::get_property_type('password'),
53
                'Plain text password consisting of any characters', VALUE_OPTIONAL),
54
            'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user'),
55
            'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user'),
56
            'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address'),
57
            'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email visibility', VALUE_OPTIONAL),
58
            'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
59
            'country' => new external_value(core_user::get_property_type('country'),
60
                'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
61
            'timezone' => new external_value(core_user::get_property_type('timezone'),
62
                'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
63
            'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML',
64
                VALUE_OPTIONAL),
65
            // Additional names.
66
            'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'),
67
                'The first name(s) phonetically of the user', VALUE_OPTIONAL),
68
            'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'),
69
                'The family name phonetically of the user', VALUE_OPTIONAL),
70
            'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user',
71
                VALUE_OPTIONAL),
72
            'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user',
73
                VALUE_OPTIONAL),
74
            // Interests.
75
            'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL),
76
            // Optional.
77
            'idnumber' => new external_value(core_user::get_property_type('idnumber'),
78
                'An arbitrary ID code number perhaps from the institution', VALUE_DEFAULT, ''),
79
            'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
80
            'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
81
            'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
82
            'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
83
            'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
84
            // Other user preferences stored in the user table.
85
            'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
86
                VALUE_DEFAULT, core_user::get_property_default('lang'), core_user::get_property_null('lang')),
87
            'calendartype' => new external_value(core_user::get_property_type('calendartype'),
88
                'Calendar type such as "gregorian", must exist on server', VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
89
            'theme' => new external_value(core_user::get_property_type('theme'),
90
                'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
91
            'mailformat' => new external_value(core_user::get_property_type('mailformat'),
92
                'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
93
            // Custom user profile fields.
94
            'customfields' => new external_multiple_structure(
95
                new external_single_structure(
96
                    [
97
                        'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
98
                        'value' => new external_value(PARAM_RAW, 'The value of the custom field')
99
                    ]
100
                ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
101
            // User preferences.
102
            'preferences' => new external_multiple_structure(
103
            new external_single_structure(
104
                [
105
                    'type'  => new external_value(PARAM_RAW, 'The name of the preference'),
106
                    'value' => new external_value(PARAM_RAW, 'The value of the preference')
107
                ]
108
            ), 'User preferences', VALUE_OPTIONAL),
109
        ];
110
        return new external_function_parameters(
111
            [
112
                'users' => new external_multiple_structure(
113
                    new external_single_structure($userfields)
114
                )
115
            ]
116
        );
117
    }
118
 
119
    /**
120
     * Create one or more users.
121
     *
122
     * @throws invalid_parameter_exception
123
     * @param array $users An array of users to create.
124
     * @return array An array of arrays
125
     * @since Moodle 2.2
126
     */
127
    public static function create_users($users) {
128
        global $CFG, $DB;
129
        require_once($CFG->dirroot."/lib/weblib.php");
130
        require_once($CFG->dirroot."/user/lib.php");
131
        require_once($CFG->dirroot."/user/editlib.php");
132
        require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
133
 
134
        // Ensure the current user is allowed to run this function.
135
        $context = context_system::instance();
136
        self::validate_context($context);
137
        require_capability('moodle/user:create', $context);
138
 
139
        // Do basic automatic PARAM checks on incoming data, using params description.
140
        // If any problems are found then exceptions are thrown with helpful error messages.
141
        $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
142
 
143
        $availableauths  = core_component::get_plugin_list('auth');
144
        unset($availableauths['mnet']);       // These would need mnethostid too.
145
        unset($availableauths['webservice']); // We do not want new webservice users for now.
146
 
147
        $availablethemes = core_component::get_plugin_list('theme');
148
        $availablelangs  = get_string_manager()->get_list_of_translations();
149
 
150
        $transaction = $DB->start_delegated_transaction();
151
 
152
        $userids = array();
1441 ariadna 153
        $newpasswordusers = [];
154
 
1 efrain 155
        foreach ($params['users'] as $user) {
156
            // Make sure that the username, firstname and lastname are not blank.
157
            foreach (array('username', 'firstname', 'lastname') as $fieldname) {
158
                if (trim($user[$fieldname]) === '') {
159
                    throw new invalid_parameter_exception('The field '.$fieldname.' cannot be blank');
160
                }
161
            }
162
 
163
            // Make sure that the username doesn't already exist.
164
            if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
165
                throw new invalid_parameter_exception('Username already exists: '.$user['username']);
166
            }
167
 
168
            // Make sure auth is valid.
169
            if (empty($availableauths[$user['auth']])) {
170
                throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
171
            }
172
 
173
            // Make sure lang is valid.
174
            if (empty($availablelangs[$user['lang']])) {
175
                throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
176
            }
177
 
178
            // Make sure lang is valid.
179
            if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
180
                                                                                     // so no default value
181
                                                                                     // We need to test if the client sent it
182
                                                                                     // => !empty($user['theme']).
183
                throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
184
            }
185
 
186
            // Make sure we have a password or have to create one.
187
            $authplugin = get_auth_plugin($user['auth']);
188
            if ($authplugin->is_internal() && empty($user['password']) && empty($user['createpassword'])) {
189
                throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
190
            }
191
 
192
            $user['confirmed'] = true;
193
            $user['mnethostid'] = $CFG->mnet_localhost_id;
194
 
195
            // Start of user info validation.
196
            // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
197
            if (!validate_email($user['email'])) {
198
                throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
199
            } else if (empty($CFG->allowaccountssameemail)) {
200
                // Make a case-insensitive query for the given email address.
201
                $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid';
202
                $params = array(
203
                    'email' => $user['email'],
204
                    'mnethostid' => $user['mnethostid']
205
                );
206
                // If there are other user(s) that already have the same email, throw an error.
207
                if ($DB->record_exists_select('user', $select, $params)) {
208
                    throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
209
                }
210
            }
211
            // End of user info validation.
212
 
213
            $createpassword = !empty($user['createpassword']);
214
            unset($user['createpassword']);
215
            $updatepassword = false;
216
            if ($authplugin->is_internal()) {
217
                if ($createpassword) {
218
                    $user['password'] = '';
219
                } else {
220
                    $updatepassword = true;
221
                }
222
            } else {
223
                $user['password'] = AUTH_PASSWORD_NOT_CACHED;
224
            }
225
 
226
            // Create the user data now!
227
            $user['id'] = user_create_user($user, $updatepassword, false);
228
 
229
            $userobject = (object)$user;
230
 
231
            // Set user interests.
232
            if (!empty($user['interests'])) {
233
                $trimmedinterests = array_map('trim', explode(',', $user['interests']));
234
                $interests = array_filter($trimmedinterests, function($value) {
235
                    return !empty($value);
236
                });
237
                useredit_update_interests($userobject, $interests);
238
            }
239
 
240
            // Custom fields.
241
            if (!empty($user['customfields'])) {
242
                foreach ($user['customfields'] as $customfield) {
243
                    // Profile_save_data() saves profile file it's expecting a user with the correct id,
244
                    // and custom field to be named profile_field_"shortname".
245
                    $user["profile_field_".$customfield['type']] = $customfield['value'];
246
                }
247
                profile_save_data((object) $user);
248
            }
249
 
250
            if ($createpassword) {
251
                unset_user_preference('create_password', $userobject);
252
                set_user_preference('auth_forcepasswordchange', 1, $userobject);
1441 ariadna 253
                // Queue this user for email notification after user creation is finalized.
254
                $newpasswordusers[] = $userobject;
1 efrain 255
            }
256
 
257
            // Trigger event.
258
            \core\event\user_created::create_from_userid($user['id'])->trigger();
259
 
260
            // Preferences.
261
            if (!empty($user['preferences'])) {
262
                $userpref = (object)$user;
263
                foreach ($user['preferences'] as $preference) {
264
                    $userpref->{'preference_'.$preference['type']} = $preference['value'];
265
                }
266
                useredit_update_user_preference($userpref);
267
            }
268
 
269
            $userids[] = array('id' => $user['id'], 'username' => $user['username']);
270
        }
271
 
272
        $transaction->allow_commit();
273
 
1441 ariadna 274
        // After database commit, send password emails to queued users.
275
        foreach ($newpasswordusers as $userobject) {
276
            setnew_password_and_mail($userobject);
277
        }
278
 
1 efrain 279
        return $userids;
280
    }
281
 
282
    /**
283
     * Returns description of method result value
284
     *
285
     * @return external_description
286
     * @since Moodle 2.2
287
     */
288
    public static function create_users_returns() {
289
        return new external_multiple_structure(
290
            new external_single_structure(
291
                array(
292
                    'id'       => new external_value(core_user::get_property_type('id'), 'user id'),
293
                    'username' => new external_value(core_user::get_property_type('username'), 'user name'),
294
                )
295
            )
296
        );
297
    }
298
 
299
 
300
    /**
301
     * Returns description of method parameters
302
     *
303
     * @return external_function_parameters
304
     * @since Moodle 2.2
305
     */
306
    public static function delete_users_parameters() {
307
        return new external_function_parameters(
308
            array(
309
                'userids' => new external_multiple_structure(new external_value(core_user::get_property_type('id'), 'user ID')),
310
            )
311
        );
312
    }
313
 
314
    /**
315
     * Delete users
316
     *
317
     * @throws moodle_exception
318
     * @param array $userids
319
     * @return null
320
     * @since Moodle 2.2
321
     */
322
    public static function delete_users($userids) {
323
        global $CFG, $DB, $USER;
324
        require_once($CFG->dirroot."/user/lib.php");
325
 
326
        // Ensure the current user is allowed to run this function.
327
        $context = context_system::instance();
328
        require_capability('moodle/user:delete', $context);
329
        self::validate_context($context);
330
 
331
        $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
332
 
333
        $transaction = $DB->start_delegated_transaction();
334
 
335
        foreach ($params['userids'] as $userid) {
336
            $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
337
            // Must not allow deleting of admins or self!!!
338
            if (is_siteadmin($user)) {
339
                throw new moodle_exception('useradminodelete', 'error');
340
            }
341
            if ($USER->id == $user->id) {
342
                throw new moodle_exception('usernotdeletederror', 'error');
343
            }
344
            user_delete_user($user);
345
        }
346
 
347
        $transaction->allow_commit();
348
 
349
        return null;
350
    }
351
 
352
    /**
353
     * Returns description of method result value
354
     *
355
     * @return null
356
     * @since Moodle 2.2
357
     */
358
    public static function delete_users_returns() {
359
        return null;
360
    }
361
 
362
    /**
363
     * Returns description of method parameters.
364
     *
365
     * @return external_function_parameters
366
     * @since Moodle 3.2
367
     */
368
    public static function update_user_preferences_parameters() {
369
        return new external_function_parameters(
370
            array(
371
                'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
372
                'emailstop' => new external_value(core_user::get_property_type('emailstop'),
373
                    'Enable or disable notifications for this user', VALUE_DEFAULT, null),
374
                'preferences' => new external_multiple_structure(
375
                    new external_single_structure(
376
                        array(
377
                            'type'  => new external_value(PARAM_RAW, 'The name of the preference'),
378
                            'value' => new external_value(PARAM_RAW, 'The value of the preference, do not set this field if you
379
                                want to remove (unset) the current value.', VALUE_DEFAULT, null),
380
                        )
381
                    ), 'User preferences', VALUE_DEFAULT, array()
382
                )
383
            )
384
        );
385
    }
386
 
387
    /**
388
     * Update the user's preferences.
389
     *
390
     * @param int $userid
391
     * @param bool|null $emailstop
392
     * @param array $preferences
393
     * @return null
394
     * @since Moodle 3.2
395
     */
396
    public static function update_user_preferences($userid = 0, $emailstop = null, $preferences = array()) {
397
        global $USER, $CFG;
398
 
399
        require_once($CFG->dirroot . '/user/lib.php');
400
        require_once($CFG->dirroot . '/user/editlib.php');
401
        require_once($CFG->dirroot . '/message/lib.php');
402
 
403
        if (empty($userid)) {
404
            $userid = $USER->id;
405
        }
406
 
407
        $systemcontext = context_system::instance();
408
        self::validate_context($systemcontext);
409
        $params = array(
410
            'userid' => $userid,
411
            'emailstop' => $emailstop,
412
            'preferences' => $preferences
413
        );
414
        $params = self::validate_parameters(self::update_user_preferences_parameters(), $params);
415
        $preferences = $params['preferences'];
416
 
417
        // Preferences.
418
        if (!empty($preferences)) {
419
            $userpref = ['id' => $userid];
420
            foreach ($preferences as $preference) {
421
                $userpref['preference_' . $preference['type']] = $preference['value'];
422
            }
423
            useredit_update_user_preference($userpref);
424
        }
425
 
426
        // Check if they want to update the email.
427
        if ($emailstop !== null) {
428
            $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST);
429
            core_user::require_active_user($otheruser);
430
            if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) {
431
                $user = new stdClass();
432
                $user->id = $userid;
433
                $user->emailstop = $emailstop;
434
                user_update_user($user);
435
 
436
                // Update the $USER if we should.
437
                if ($userid == $USER->id) {
438
                    $USER->emailstop = $emailstop;
439
                }
440
            }
441
        }
442
 
443
        return null;
444
    }
445
 
446
    /**
447
     * Returns description of method result value
448
     *
449
     * @return null
450
     * @since Moodle 3.2
451
     */
452
    public static function update_user_preferences_returns() {
453
        return null;
454
    }
455
 
456
    /**
457
     * Returns description of method parameters
458
     *
459
     * @return external_function_parameters
460
     * @since Moodle 2.2
461
     */
462
    public static function update_users_parameters() {
463
        $userfields = [
464
            'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
465
            // General.
466
            'username' => new external_value(core_user::get_property_type('username'),
467
                'Username policy is defined in Moodle security config.', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
468
            'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
469
                VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
470
            'suspended' => new external_value(core_user::get_property_type('suspended'),
471
                'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
472
            'password' => new external_value(core_user::get_property_type('password'),
473
                'Plain text password consisting of any characters', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
474
            'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user',
475
                VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
476
            'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user',
477
                VALUE_OPTIONAL),
478
            'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL,
479
                '', NULL_NOT_ALLOWED),
480
            'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email visibility', VALUE_OPTIONAL),
481
            'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
482
            'country' => new external_value(core_user::get_property_type('country'),
483
                'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
484
            'timezone' => new external_value(core_user::get_property_type('timezone'),
485
                'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
486
            'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML',
487
                VALUE_OPTIONAL),
488
            // User picture.
489
            'userpicture' => new external_value(PARAM_INT,
490
                'The itemid where the new user picture has been uploaded to, 0 to delete', VALUE_OPTIONAL),
491
            // Additional names.
492
            'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'),
493
                'The first name(s) phonetically of the user', VALUE_OPTIONAL),
494
            'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'),
495
                'The family name phonetically of the user', VALUE_OPTIONAL),
496
            'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user',
497
                VALUE_OPTIONAL),
498
            'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user',
499
                VALUE_OPTIONAL),
500
            // Interests.
501
            'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL),
502
            // Optional.
503
            'idnumber' => new external_value(core_user::get_property_type('idnumber'),
504
                'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
505
            'institution' => new external_value(core_user::get_property_type('institution'), 'Institution', VALUE_OPTIONAL),
506
            'department' => new external_value(core_user::get_property_type('department'), 'Department', VALUE_OPTIONAL),
507
            'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone', VALUE_OPTIONAL),
508
            'phone2' => new external_value(core_user::get_property_type('phone2'), 'Mobile phone', VALUE_OPTIONAL),
509
            'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
510
            // Other user preferences stored in the user table.
511
            'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
512
                VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
513
            'calendartype' => new external_value(core_user::get_property_type('calendartype'),
514
                'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
515
            'theme' => new external_value(core_user::get_property_type('theme'),
516
                'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
517
            'mailformat' => new external_value(core_user::get_property_type('mailformat'),
518
                'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
519
            // Custom user profile fields.
520
            'customfields' => new external_multiple_structure(
521
                new external_single_structure(
522
                    [
523
                        'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
524
                        'value' => new external_value(PARAM_RAW, 'The value of the custom field')
525
                    ]
526
                ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
527
            // User preferences.
528
            'preferences' => new external_multiple_structure(
529
                new external_single_structure(
530
                    [
531
                        'type'  => new external_value(PARAM_RAW, 'The name of the preference'),
532
                        'value' => new external_value(PARAM_RAW, 'The value of the preference')
533
                    ]
534
                ), 'User preferences', VALUE_OPTIONAL),
535
        ];
536
        return new external_function_parameters(
537
            [
538
                'users' => new external_multiple_structure(
539
                    new external_single_structure($userfields)
540
                )
541
            ]
542
        );
543
    }
544
 
545
    /**
546
     * Update users
547
     *
548
     * @param array $users
549
     * @return null
550
     * @since Moodle 2.2
551
     */
552
    public static function update_users($users) {
553
        global $CFG, $DB, $USER;
554
        require_once($CFG->dirroot."/user/lib.php");
555
        require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
556
        require_once($CFG->dirroot.'/user/editlib.php');
557
 
558
        // Ensure the current user is allowed to run this function.
559
        $context = context_system::instance();
560
        require_capability('moodle/user:update', $context);
561
        self::validate_context($context);
562
 
563
        $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
564
 
565
        $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
566
                'subdirs'        => 0,
567
                'maxfiles'       => 1,
568
                'accepted_types' => 'optimised_image');
569
 
570
        $warnings = array();
571
        foreach ($params['users'] as $user) {
572
            // Catch any exception while updating a user and return it as a warning.
573
            try {
574
                $transaction = $DB->start_delegated_transaction();
575
 
576
                // First check the user exists.
577
                if (!$existinguser = core_user::get_user($user['id'])) {
578
                    throw new moodle_exception('invaliduserid', '', '', null,
579
                            'Invalid user ID');
580
                }
581
                // Check if we are trying to update an admin.
582
                if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
583
                    throw new moodle_exception('usernotupdatedadmin', '', '', null,
584
                            'Cannot update admin accounts');
585
                }
586
                // Other checks (deleted, remote or guest users).
587
                if ($existinguser->deleted) {
588
                    throw new moodle_exception('usernotupdateddeleted', '', '', null,
589
                            'User is a deleted user');
590
                }
591
                if (is_mnet_remote_user($existinguser)) {
592
                    throw new moodle_exception('usernotupdatedremote', '', '', null,
593
                            'User is a remote user');
594
                }
595
                if (isguestuser($existinguser->id)) {
596
                    throw new moodle_exception('usernotupdatedguest', '', '', null,
597
                            'Cannot update guest account');
598
                }
599
                // Check duplicated emails.
600
                if (isset($user['email']) && $user['email'] !== $existinguser->email) {
601
                    if (!validate_email($user['email'])) {
602
                        throw new moodle_exception('useremailinvalid', '', '', null,
603
                                'Invalid email address');
604
                    } else if (empty($CFG->allowaccountssameemail)) {
605
                        // Make a case-insensitive query for the given email address
606
                        // and make sure to exclude the user being updated.
607
                        $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid';
608
                        $params = array(
609
                            'email' => $user['email'],
610
                            'mnethostid' => $CFG->mnet_localhost_id,
611
                            'userid' => $user['id']
612
                        );
613
                        // Skip if there are other user(s) that already have the same email.
614
                        if ($DB->record_exists_select('user', $select, $params)) {
615
                            throw new moodle_exception('useremailduplicate', '', '', null,
616
                                    'Duplicate email address');
617
                        }
618
                    }
619
                }
620
 
621
                user_update_user($user, true, false);
622
 
623
                $userobject = (object)$user;
624
 
625
                // Update user picture if it was specified for this user.
626
                if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
627
                    $userobject->deletepicture = null;
628
 
629
                    if ($user['userpicture'] == 0) {
630
                        $userobject->deletepicture = true;
631
                    } else {
632
                        $userobject->imagefile = $user['userpicture'];
633
                    }
634
 
635
                    core_user::update_picture($userobject, $filemanageroptions);
636
                }
637
 
638
                // Update user interests.
639
                if (!empty($user['interests'])) {
640
                    $trimmedinterests = array_map('trim', explode(',', $user['interests']));
641
                    $interests = array_filter($trimmedinterests, function($value) {
642
                        return !empty($value);
643
                    });
644
                    useredit_update_interests($userobject, $interests);
645
                }
646
 
647
                // Update user custom fields.
648
                if (!empty($user['customfields'])) {
649
 
650
                    foreach ($user['customfields'] as $customfield) {
651
                        // Profile_save_data() saves profile file it's expecting a user with the correct id,
652
                        // and custom field to be named profile_field_"shortname".
653
                        $user["profile_field_".$customfield['type']] = $customfield['value'];
654
                    }
655
                    profile_save_data((object) $user);
656
                }
657
 
658
                // Trigger event.
659
                \core\event\user_updated::create_from_userid($user['id'])->trigger();
660
 
661
                // Preferences.
662
                if (!empty($user['preferences'])) {
663
                    $userpref = clone($existinguser);
664
                    foreach ($user['preferences'] as $preference) {
665
                        $userpref->{'preference_'.$preference['type']} = $preference['value'];
666
                    }
667
                    useredit_update_user_preference($userpref);
668
                }
669
                if (isset($user['suspended']) and $user['suspended']) {
1441 ariadna 670
                    \core\session\manager::destroy_user_sessions($user['id']);
1 efrain 671
                }
672
 
673
                $transaction->allow_commit();
674
            } catch (Exception $e) {
675
                try {
676
                    $transaction->rollback($e);
677
                } catch (Exception $e) {
678
                    $warning = [];
679
                    $warning['item'] = 'user';
680
                    $warning['itemid'] = $user['id'];
681
                    if ($e instanceof moodle_exception) {
682
                        $warning['warningcode'] = $e->errorcode;
683
                    } else {
684
                        $warning['warningcode'] = $e->getCode();
685
                    }
686
                    $warning['message'] = $e->getMessage();
687
                    $warnings[] = $warning;
688
                }
689
            }
690
        }
691
 
692
        return ['warnings' => $warnings];
693
    }
694
 
695
    /**
696
     * Returns description of method result value
697
     *
698
     * @return external_description
699
     * @since Moodle 2.2
700
     */
701
    public static function update_users_returns() {
702
        return new external_single_structure(
703
            array(
704
                'warnings' => new external_warnings()
705
            )
706
        );
707
    }
708
 
709
    /**
710
     * Returns description of method parameters
711
     *
712
     * @return external_function_parameters
713
     * @since Moodle 2.4
714
     */
715
    public static function get_users_by_field_parameters() {
716
        return new external_function_parameters(
717
            array(
718
                'field' => new external_value(PARAM_ALPHA, 'the search field can be
719
                    \'id\' or \'idnumber\' or \'username\' or \'email\''),
720
                'values' => new external_multiple_structure(
721
                        new external_value(PARAM_RAW, 'the value to match'))
722
            )
723
        );
724
    }
725
 
726
    /**
727
     * Get user information for a unique field.
728
     *
729
     * @throws coding_exception
730
     * @throws invalid_parameter_exception
731
     * @param string $field
732
     * @param array $values
733
     * @return array An array of arrays containg user profiles.
734
     * @since Moodle 2.4
735
     */
736
    public static function get_users_by_field($field, $values) {
737
        global $CFG, $USER, $DB;
738
        require_once($CFG->dirroot . "/user/lib.php");
739
 
740
        $params = self::validate_parameters(self::get_users_by_field_parameters(),
741
                array('field' => $field, 'values' => $values));
742
 
743
        // This array will keep all the users that are allowed to be searched,
744
        // according to the current user's privileges.
745
        $cleanedvalues = array();
746
 
747
        switch ($field) {
748
            case 'id':
749
                $paramtype = core_user::get_property_type('id');
750
                break;
751
            case 'idnumber':
752
                $paramtype = core_user::get_property_type('idnumber');
753
                break;
754
            case 'username':
755
                $paramtype = core_user::get_property_type('username');
756
                break;
757
            case 'email':
758
                $paramtype = core_user::get_property_type('email');
759
                break;
760
            default:
761
                throw new coding_exception('invalid field parameter',
762
                        'The search field \'' . $field . '\' is not supported, look at the web service documentation');
763
        }
764
 
765
        // Clean the values.
766
        foreach ($values as $value) {
767
            $cleanedvalue = clean_param($value, $paramtype);
768
            if ( $value != $cleanedvalue) {
769
                throw new invalid_parameter_exception('The field \'' . $field .
770
                        '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
771
            }
772
            $cleanedvalues[] = $cleanedvalue;
773
        }
774
 
775
        // Retrieve the users.
776
        $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
777
 
778
        $context = context_system::instance();
779
        self::validate_context($context);
780
 
781
        // Finally retrieve each users information.
782
        $returnedusers = array();
783
        foreach ($users as $user) {
784
            $userdetails = user_get_user_details_courses($user);
785
 
786
            // Return the user only if the searched field is returned.
787
            // Otherwise it means that the $USER was not allowed to search the returned user.
788
            if (!empty($userdetails) and !empty($userdetails[$field])) {
789
                $returnedusers[] = $userdetails;
790
            }
791
        }
792
 
793
        return $returnedusers;
794
    }
795
 
796
    /**
797
     * Returns description of method result value
798
     *
799
     * @return external_multiple_structure
800
     * @since Moodle 2.4
801
     */
802
    public static function get_users_by_field_returns() {
803
        return new external_multiple_structure(self::user_description());
804
    }
805
 
806
 
807
    /**
808
     * Returns description of get_users() parameters.
809
     *
810
     * @return external_function_parameters
811
     * @since Moodle 2.5
812
     */
813
    public static function get_users_parameters() {
814
        return new external_function_parameters(
815
            array(
816
                'criteria' => new external_multiple_structure(
817
                    new external_single_structure(
818
                        array(
819
                            'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
820
                                "id" (int) matching user id,
821
                                "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
822
                                "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
823
                                "idnumber" (string) matching user idnumber,
824
                                "username" (string) matching user username,
825
                                "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
826
                                "auth" (string) matching user auth plugin'),
827
                            'value' => new external_value(PARAM_RAW, 'the value to search')
828
                        )
829
                    ), 'the key/value pairs to be considered in user search. Values can not be empty.
830
                        Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
831
                        key occurences are forbidden.
832
                        The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
833
                        the search is still executed on the valid criterias.
834
                        You can search without criteria, but the function is not designed for it.
835
                        It could very slow or timeout. The function is designed to search some specific users.'
836
                )
837
            )
838
        );
839
    }
840
 
841
    /**
842
     * Retrieve matching user.
843
     *
844
     * @throws moodle_exception
845
     * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
846
     * @return array An array of arrays containing user profiles.
847
     * @since Moodle 2.5
848
     */
849
    public static function get_users($criteria = array()) {
850
        global $CFG, $USER, $DB;
851
 
852
        require_once($CFG->dirroot . "/user/lib.php");
853
 
854
        $params = self::validate_parameters(self::get_users_parameters(),
855
                array('criteria' => $criteria));
856
 
857
        // Validate the criteria and retrieve the users.
858
        $users = array();
859
        $warnings = array();
860
        $sqlparams = array();
861
        $usedkeys = array();
862
 
863
        // Do not retrieve deleted users.
864
        $sql = ' deleted = 0';
865
 
866
        foreach ($params['criteria'] as $criteriaindex => $criteria) {
867
 
868
            // Check that the criteria has never been used.
869
            if (array_key_exists($criteria['key'], $usedkeys)) {
870
                throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
871
            } else {
872
                $usedkeys[$criteria['key']] = true;
873
            }
874
 
875
            $invalidcriteria = false;
876
            // Clean the parameters.
877
            $paramtype = PARAM_RAW;
878
            switch ($criteria['key']) {
879
                case 'id':
880
                    $paramtype = core_user::get_property_type('id');
881
                    break;
882
                case 'idnumber':
883
                    $paramtype = core_user::get_property_type('idnumber');
884
                    break;
885
                case 'username':
886
                    $paramtype = core_user::get_property_type('username');
887
                    break;
888
                case 'email':
889
                    // We use PARAM_RAW to allow searches with %.
890
                    $paramtype = core_user::get_property_type('email');
891
                    break;
892
                case 'auth':
893
                    $paramtype = core_user::get_property_type('auth');
894
                    break;
895
                case 'lastname':
896
                case 'firstname':
897
                    $paramtype = core_user::get_property_type('firstname');
898
                    break;
899
                default:
900
                    // Send back a warning that this search key is not supported in this version.
901
                    // This warning will make the function extandable without breaking clients.
902
                    $warnings[] = array(
903
                        'item' => $criteria['key'],
904
                        'warningcode' => 'invalidfieldparameter',
905
                        'message' =>
906
                            'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
907
                    );
908
                    // Do not add this invalid criteria to the created SQL request.
909
                    $invalidcriteria = true;
910
                    unset($params['criteria'][$criteriaindex]);
911
                    break;
912
            }
913
 
914
            if (!$invalidcriteria) {
915
                $cleanedvalue = clean_param($criteria['value'], $paramtype);
916
 
917
                $sql .= ' AND ';
918
 
919
                // Create the SQL.
920
                switch ($criteria['key']) {
921
                    case 'id':
922
                    case 'idnumber':
923
                    case 'username':
924
                    case 'auth':
925
                        $sql .= $criteria['key'] . ' = :' . $criteria['key'];
926
                        $sqlparams[$criteria['key']] = $cleanedvalue;
927
                        break;
928
                    case 'email':
929
                    case 'lastname':
930
                    case 'firstname':
931
                        $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
932
                        $sqlparams[$criteria['key']] = $cleanedvalue;
933
                        break;
934
                    default:
935
                        break;
936
                }
937
            }
938
        }
939
 
940
        $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
941
 
942
        // Finally retrieve each users information.
943
        $returnedusers = array();
944
        foreach ($users as $user) {
945
            $userdetails = user_get_user_details_courses($user);
946
 
947
            // Return the user only if all the searched fields are returned.
948
            // Otherwise it means that the $USER was not allowed to search the returned user.
949
            if (!empty($userdetails)) {
950
                $validuser = true;
951
 
952
                foreach ($params['criteria'] as $criteria) {
953
                    if (empty($userdetails[$criteria['key']])) {
954
                        $validuser = false;
955
                    }
956
                }
957
 
958
                if ($validuser) {
959
                    $returnedusers[] = $userdetails;
960
                }
961
            }
962
        }
963
 
964
        return array('users' => $returnedusers, 'warnings' => $warnings);
965
    }
966
 
967
    /**
968
     * Returns description of get_users result value.
969
     *
970
     * @return external_description
971
     * @since Moodle 2.5
972
     */
973
    public static function get_users_returns() {
974
        return new external_single_structure(
975
            array('users' => new external_multiple_structure(
976
                                self::user_description()
977
                             ),
978
                  'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
979
            )
980
        );
981
    }
982
 
983
    /**
984
     * Returns description of method parameters
985
     *
986
     * @return external_function_parameters
987
     * @since Moodle 2.2
988
     */
989
    public static function get_course_user_profiles_parameters() {
990
        return new external_function_parameters(
991
            array(
992
                'userlist' => new external_multiple_structure(
993
                    new external_single_structure(
994
                        array(
995
                            'userid'    => new external_value(core_user::get_property_type('id'), 'userid'),
996
                            'courseid'    => new external_value(PARAM_INT, 'courseid'),
997
                        )
998
                    )
999
                )
1000
            )
1001
        );
1002
    }
1003
 
1004
    /**
1005
     * Get course participant's details
1006
     *
1007
     * @param array $userlist  array of user ids and according course ids
1008
     * @return array An array of arrays describing course participants
1009
     * @since Moodle 2.2
1010
     */
1011
    public static function get_course_user_profiles($userlist) {
1012
        global $CFG, $USER, $DB;
1013
        require_once($CFG->dirroot . "/user/lib.php");
1014
        $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
1015
 
1016
        $userids = array();
1017
        $courseids = array();
1018
        foreach ($params['userlist'] as $value) {
1019
            $userids[] = $value['userid'];
1020
            $courseids[$value['userid']] = $value['courseid'];
1021
        }
1022
 
1023
        // Cache all courses.
1024
        $courses = array();
1025
        list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
1026
        $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1027
        $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1028
        $params['contextlevel'] = CONTEXT_COURSE;
1029
        $coursesql = "SELECT c.* $cselect
1030
                        FROM {course} c $cjoin
1031
                       WHERE c.id $sqlcourseids";
1032
        $rs = $DB->get_recordset_sql($coursesql, $params);
1033
        foreach ($rs as $course) {
1034
            // Adding course contexts to cache.
1035
            context_helper::preload_from_record($course);
1036
            // Cache courses.
1037
            $courses[$course->id] = $course;
1038
        }
1039
        $rs->close();
1040
 
1041
        list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
1042
        $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1043
        $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
1044
        $params['contextlevel'] = CONTEXT_USER;
1045
        $usersql = "SELECT u.* $uselect
1046
                      FROM {user} u $ujoin
1047
                     WHERE u.id $sqluserids";
1048
        $users = $DB->get_recordset_sql($usersql, $params);
1049
        $result = array();
1050
        foreach ($users as $user) {
1051
            if (!empty($user->deleted)) {
1052
                continue;
1053
            }
1054
            context_helper::preload_from_record($user);
1055
            $course = $courses[$courseids[$user->id]];
1056
            $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
1057
            self::validate_context($context);
1058
            if ($userarray = user_get_user_details($user, $course)) {
1059
                $result[] = $userarray;
1060
            }
1061
        }
1062
 
1063
        $users->close();
1064
 
1065
        return $result;
1066
    }
1067
 
1068
    /**
1069
     * Returns description of method result value
1070
     *
1071
     * @return external_description
1072
     * @since Moodle 2.2
1073
     */
1074
    public static function get_course_user_profiles_returns() {
1075
        $additionalfields = array(
1076
            'groups' => new external_multiple_structure(
1077
                new external_single_structure(
1078
                    array(
1079
                        'id'  => new external_value(PARAM_INT, 'group id'),
1080
                        'name' => new external_value(PARAM_RAW, 'group name'),
1081
                        'description' => new external_value(PARAM_RAW, 'group description'),
1082
                        'descriptionformat' => new external_format_value('description'),
1083
                    )
1084
                ), 'user groups', VALUE_OPTIONAL),
1085
            'roles' => new external_multiple_structure(
1086
                new external_single_structure(
1087
                    array(
1088
                        'roleid'       => new external_value(PARAM_INT, 'role id'),
1089
                        'name'         => new external_value(PARAM_RAW, 'role name'),
1090
                        'shortname'    => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
1091
                        'sortorder'    => new external_value(PARAM_INT, 'role sortorder')
1092
                    )
1093
                ), 'user roles', VALUE_OPTIONAL),
1094
            'enrolledcourses' => new external_multiple_structure(
1095
                new external_single_structure(
1096
                    array(
1097
                        'id'  => new external_value(PARAM_INT, 'Id of the course'),
1098
                        'fullname'  => new external_value(PARAM_RAW, 'Fullname of the course'),
1099
                        'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
1100
                    )
1101
                ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
1102
        );
1103
 
1104
        return new external_multiple_structure(self::user_description($additionalfields));
1105
    }
1106
 
1107
    /**
1108
     * Create user return value description.
1109
     *
1110
     * @param array $additionalfields some additional field
1111
     * @return external_description
1112
     */
1113
    public static function user_description($additionalfields = array()) {
1114
        $userfields = array(
1115
            'id'    => new external_value(core_user::get_property_type('id'), 'ID of the user'),
1116
            'username'    => new external_value(core_user::get_property_type('username'), 'The username', VALUE_OPTIONAL),
1117
            'firstname'   => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL),
1118
            'lastname'    => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
1119
            'fullname'    => new external_value(core_user::get_property_type('firstname'), 'The fullname of the user'),
1120
            'email'       => new external_value(core_user::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
1121
            'address'     => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
1122
            'phone1'      => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
1123
            'phone2'      => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
1124
            'department'  => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
1125
            'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
1126
            'idnumber'    => new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
1127
            'interests'   => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
1128
            'firstaccess' => new external_value(core_user::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL),
1129
            'lastaccess'  => new external_value(core_user::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL),
1130
            'auth'        => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL),
1131
            'suspended'   => new external_value(core_user::get_property_type('suspended'), 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
1132
            'confirmed'   => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
1133
            'lang'        => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
1134
            'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
1135
            'theme'       => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
1136
            'timezone'    => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
1137
            'mailformat'  => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
1138
            'trackforums'  => new external_value(core_user::get_property_type('trackforums'),
1139
                'Whether the user is tracking forums.', VALUE_OPTIONAL),
1140
            'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL),
1141
            'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL),
1142
            'city'        => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
1143
            'country'     => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
1144
            'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
1145
            'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
1146
            'customfields' => new external_multiple_structure(
1147
                new external_single_structure(
1148
                    array(
1149
                        'type'  => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
1150
                        'value' => new external_value(PARAM_RAW, 'The value of the custom field (as stored in the database)'),
1151
                        'displayvalue' => new external_value(PARAM_RAW, 'The value of the custom field for display',
1152
                            VALUE_OPTIONAL),
1153
                        'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
1154
                        'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
1155
                    )
1156
                ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
1157
            'preferences' => new external_multiple_structure(
1158
                new external_single_structure(
1159
                    array(
1160
                        'name'  => new external_value(PARAM_RAW, 'The name of the preferences'),
1161
                        'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1162
                    )
1163
            ), 'Users preferences', VALUE_OPTIONAL)
1164
        );
1165
        if (!empty($additionalfields)) {
1166
            $userfields = array_merge($userfields, $additionalfields);
1167
        }
1168
        return new external_single_structure($userfields);
1169
    }
1170
 
1171
    /**
1172
     * Returns description of method parameters
1173
     *
1174
     * @return external_function_parameters
1175
     * @since Moodle 2.6
1176
     */
1177
    public static function add_user_private_files_parameters() {
1178
        return new external_function_parameters(
1179
            array(
1180
                'draftid' => new external_value(PARAM_INT, 'draft area id')
1181
            )
1182
        );
1183
    }
1184
 
1185
    /**
1186
     * Copy files from a draft area to users private files area.
1187
     *
1188
     * @throws invalid_parameter_exception
1189
     * @throws moodle_exception
1190
     * @param int $draftid Id of a draft area containing files.
1191
     * @return array An array of warnings
1192
     * @since Moodle 2.6
1193
     */
1194
    public static function add_user_private_files($draftid) {
1195
        global $CFG, $USER;
1196
        require_once($CFG->libdir . "/filelib.php");
1197
 
1198
        $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
1199
 
1200
        if (isguestuser()) {
1201
            throw new invalid_parameter_exception('Guest users cannot upload files');
1202
        }
1203
 
1204
        $context = context_user::instance($USER->id);
1205
        require_capability('moodle/user:manageownfiles', $context);
1206
 
1207
        $maxbytes = $CFG->userquota;
1208
        $maxareabytes = $CFG->userquota;
1209
        if (has_capability('moodle/user:ignoreuserquota', $context)) {
1210
            $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1211
            $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1212
        } else {
1213
            // Get current used space for this user (private files only).
1214
            $fileareainfo = file_get_file_area_info($context->id, 'user', 'private');
1215
            $usedspace = $fileareainfo['filesize_without_references'];
1216
 
1217
            // Get the total size of the new files we want to add to private files.
1218
            $newfilesinfo = file_get_draft_area_info($params['draftid']);
1219
 
1220
            if (($newfilesinfo['filesize_without_references'] + $usedspace) > $maxareabytes) {
1221
                throw new moodle_exception('maxareabytes');
1222
            }
1223
        }
1224
 
1225
        $options = array('subdirs' => 1,
1226
                         'maxbytes' => $maxbytes,
1227
                         'maxfiles' => -1,
1228
                         'areamaxbytes' => $maxareabytes);
1229
 
1230
        file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options);
1231
 
1232
        return null;
1233
    }
1234
 
1235
    /**
1236
     * Returns description of method result value
1237
     *
1238
     * @return external_description
1239
     * @since Moodle 2.2
1240
     */
1241
    public static function add_user_private_files_returns() {
1242
        return null;
1243
    }
1244
 
1245
    /**
1246
     * Returns description of method parameters.
1247
     *
1248
     * @return external_function_parameters
1249
     * @since Moodle 2.6
1250
     */
1251
    public static function add_user_device_parameters() {
1252
        return new external_function_parameters(
1253
            array(
1254
                'appid'     => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1255
                'name'      => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1256
                'model'     => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1257
                'platform'  => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1258
                'version'   => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1259
                'pushid'    => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1260
                'uuid'      => new external_value(PARAM_RAW, 'the device UUID'),
1261
                'publickey' => new external_value(PARAM_RAW, 'the app generated public key', VALUE_DEFAULT, null),
1262
            )
1263
        );
1264
    }
1265
 
1266
    /**
1267
     * Add a user device in Moodle database (for PUSH notifications usually).
1268
     *
1269
     * @throws moodle_exception
1270
     * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1271
     * @param string $name The device name, occam or iPhone etc.
1272
     * @param string $model The device model Nexus4 or iPad1.1 etc.
1273
     * @param string $platform The device platform iOs or Android etc.
1274
     * @param string $version The device version 6.1.2 or 4.2.2 etc.
1275
     * @param string $pushid The device PUSH token/key/identifier/registration id.
1276
     * @param string $uuid The device UUID.
1277
     * @param string $publickey The app generated public key
1278
     * @return array List of possible warnings.
1279
     * @since Moodle 2.6
1280
     */
1281
    public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid, $publickey = null) {
1282
        global $CFG, $USER, $DB;
1283
        require_once($CFG->dirroot . "/user/lib.php");
1284
 
1285
        $params = self::validate_parameters(self::add_user_device_parameters(),
1286
                array('appid' => $appid,
1287
                      'name' => $name,
1288
                      'model' => $model,
1289
                      'platform' => $platform,
1290
                      'version' => $version,
1291
                      'pushid' => $pushid,
1292
                      'uuid' => $uuid,
1293
                      'publickey' => $publickey,
1294
                      ));
1295
 
1296
        $warnings = array();
1297
 
1298
        // Prevent duplicate keys for users.
1299
        if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1300
            $warnings['warning'][] = array(
1301
                'item' => $params['pushid'],
1302
                'warningcode' => 'existingkeyforthisuser',
1303
                'message' => 'This key is already stored for this user'
1304
            );
1305
            return $warnings;
1306
        }
1307
 
1308
        // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1309
        // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1310
        if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1311
                'appid' => $params['appid'], 'userid' => $USER->id))) {
1312
 
1313
            foreach ($userdevices as $userdevice) {
1314
                $userdevice->version    = $params['version'];   // Maybe the user upgraded the device.
1315
                $userdevice->pushid     = $params['pushid'];
1316
                $userdevice->publickey  = $params['publickey'];
1317
                $userdevice->timemodified  = time();
1318
                $DB->update_record('user_devices', $userdevice);
1319
            }
1320
 
1321
        } else {
1322
            $userdevice = new stdclass;
1323
            $userdevice->userid     = $USER->id;
1324
            $userdevice->appid      = $params['appid'];
1325
            $userdevice->name       = $params['name'];
1326
            $userdevice->model      = $params['model'];
1327
            $userdevice->platform   = $params['platform'];
1328
            $userdevice->version    = $params['version'];
1329
            $userdevice->pushid     = $params['pushid'];
1330
            $userdevice->uuid       = $params['uuid'];
1331
            $userdevice->publickey  = $params['publickey'];
1332
            $userdevice->timecreated  = time();
1333
            $userdevice->timemodified = $userdevice->timecreated;
1334
 
1335
            if (!$DB->insert_record('user_devices', $userdevice)) {
1336
                throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1337
            }
1338
        }
1339
 
1340
        return $warnings;
1341
    }
1342
 
1343
    /**
1344
     * Returns description of method result value.
1345
     *
1346
     * @return external_multiple_structure
1347
     * @since Moodle 2.6
1348
     */
1349
    public static function add_user_device_returns() {
1350
        return new external_multiple_structure(
1351
           new external_warnings()
1352
        );
1353
    }
1354
 
1355
    /**
1356
     * Returns description of method parameters.
1357
     *
1358
     * @return external_function_parameters
1359
     * @since Moodle 2.9
1360
     */
1361
    public static function remove_user_device_parameters() {
1362
        return new external_function_parameters(
1363
            array(
1364
                'uuid'  => new external_value(PARAM_RAW, 'the device UUID'),
1365
                'appid' => new external_value(PARAM_NOTAGS,
1366
                                                'the app id, if empty devices matching the UUID for the user will be removed',
1367
                                                VALUE_DEFAULT, ''),
1368
            )
1369
        );
1370
    }
1371
 
1372
    /**
1373
     * Remove a user device from the Moodle database (for PUSH notifications usually).
1374
     *
1375
     * @param string $uuid The device UUID.
1376
     * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1377
     * @return array List of possible warnings and removal status.
1378
     * @since Moodle 2.9
1379
     */
1380
    public static function remove_user_device($uuid, $appid = "") {
1381
        global $CFG;
1382
        require_once($CFG->dirroot . "/user/lib.php");
1383
 
1384
        $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1385
 
1386
        $context = context_system::instance();
1387
        self::validate_context($context);
1388
 
1389
        // Warnings array, it can be empty at the end but is mandatory.
1390
        $warnings = array();
1391
 
1392
        $removed = user_remove_user_device($params['uuid'], $params['appid']);
1393
 
1394
        if (!$removed) {
1395
            $warnings[] = array(
1396
                'item' => $params['uuid'],
1397
                'warningcode' => 'devicedoesnotexist',
1398
                'message' => 'The device doesn\'t exists in the database'
1399
            );
1400
        }
1401
 
1402
        $result = array(
1403
            'removed' => $removed,
1404
            'warnings' => $warnings
1405
        );
1406
 
1407
        return $result;
1408
    }
1409
 
1410
    /**
1411
     * Returns description of method result value.
1412
     *
1413
     * @return external_multiple_structure
1414
     * @since Moodle 2.9
1415
     */
1416
    public static function remove_user_device_returns() {
1417
        return new external_single_structure(
1418
            array(
1419
                'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
1420
                'warnings' => new external_warnings(),
1421
            )
1422
        );
1423
    }
1424
 
1425
    /**
1426
     * Returns description of method parameters
1427
     *
1428
     * @return external_function_parameters
1429
     * @since Moodle 2.9
1430
     */
1431
    public static function view_user_list_parameters() {
1432
        return new external_function_parameters(
1433
            array(
1434
                'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site')
1435
            )
1436
        );
1437
    }
1438
 
1439
    /**
1440
     * Trigger the user_list_viewed event.
1441
     *
1442
     * @param int $courseid id of course
1443
     * @return array of warnings and status result
1444
     * @since Moodle 2.9
1445
     * @throws moodle_exception
1446
     */
1447
    public static function view_user_list($courseid) {
1448
        global $CFG;
1449
        require_once($CFG->dirroot . "/user/lib.php");
1450
        require_once($CFG->dirroot . '/course/lib.php');
1451
 
1452
        $params = self::validate_parameters(self::view_user_list_parameters(),
1453
                                            array(
1454
                                                'courseid' => $courseid
1455
                                            ));
1456
 
1457
        $warnings = array();
1458
 
1459
        if (empty($params['courseid'])) {
1460
            $params['courseid'] = SITEID;
1461
        }
1462
 
1463
        $course = get_course($params['courseid']);
1464
 
1465
        if ($course->id == SITEID) {
1466
            $context = context_system::instance();
1467
        } else {
1468
            $context = context_course::instance($course->id);
1469
        }
1470
        self::validate_context($context);
1471
 
1472
        course_require_view_participants($context);
1473
 
1474
        user_list_view($course, $context);
1475
 
1476
        $result = array();
1477
        $result['status'] = true;
1478
        $result['warnings'] = $warnings;
1479
        return $result;
1480
    }
1481
 
1482
    /**
1483
     * Returns description of method result value
1484
     *
1485
     * @return external_description
1486
     * @since Moodle 2.9
1487
     */
1488
    public static function view_user_list_returns() {
1489
        return new external_single_structure(
1490
            array(
1491
                'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1492
                'warnings' => new external_warnings()
1493
            )
1494
        );
1495
    }
1496
 
1497
    /**
1498
     * Returns description of method parameters
1499
     *
1500
     * @return external_function_parameters
1501
     * @since Moodle 2.9
1502
     */
1503
    public static function view_user_profile_parameters() {
1504
        return new external_function_parameters(
1505
            array(
1506
                'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1507
                'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
1508
            )
1509
        );
1510
    }
1511
 
1512
    /**
1513
     * Trigger the user profile viewed event.
1514
     *
1515
     * @param int $userid id of user
1516
     * @param int $courseid id of course
1517
     * @return array of warnings and status result
1518
     * @since Moodle 2.9
1519
     * @throws moodle_exception
1520
     */
1521
    public static function view_user_profile($userid, $courseid = 0) {
1522
        global $CFG, $USER;
1523
        require_once($CFG->dirroot . "/user/profile/lib.php");
1524
 
1525
        $params = self::validate_parameters(self::view_user_profile_parameters(),
1526
                                            array(
1527
                                                'userid' => $userid,
1528
                                                'courseid' => $courseid
1529
                                            ));
1530
 
1531
        $warnings = array();
1532
 
1533
        if (empty($params['userid'])) {
1534
            $params['userid'] = $USER->id;
1535
        }
1536
 
1537
        if (empty($params['courseid'])) {
1538
            $params['courseid'] = SITEID;
1539
        }
1540
 
1541
        $course = get_course($params['courseid']);
1542
        $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1543
        core_user::require_active_user($user);
1544
 
1545
        if ($course->id == SITEID) {
1546
            $coursecontext = context_system::instance();;
1547
        } else {
1548
            $coursecontext = context_course::instance($course->id);
1549
        }
1550
        self::validate_context($coursecontext);
1551
 
1552
        $currentuser = $USER->id == $user->id;
1553
        $usercontext = context_user::instance($user->id);
1554
 
1555
        if (!$currentuser and
1556
                !has_capability('moodle/user:viewdetails', $coursecontext) and
1557
                !has_capability('moodle/user:viewdetails', $usercontext)) {
1558
            throw new moodle_exception('cannotviewprofile');
1559
        }
1560
 
1561
        // Case like user/profile.php.
1562
        if ($course->id == SITEID) {
1563
            profile_view($user, $usercontext);
1564
        } else {
1565
            // Case like user/view.php.
1566
            if (!$currentuser and !can_access_course($course, $user, '', true)) {
1567
                throw new moodle_exception('notenrolledprofile');
1568
            }
1569
 
1570
            profile_view($user, $coursecontext, $course);
1571
        }
1572
 
1573
        $result = array();
1574
        $result['status'] = true;
1575
        $result['warnings'] = $warnings;
1576
        return $result;
1577
    }
1578
 
1579
    /**
1580
     * Returns description of method result value
1581
     *
1582
     * @return external_description
1583
     * @since Moodle 2.9
1584
     */
1585
    public static function view_user_profile_returns() {
1586
        return new external_single_structure(
1587
            array(
1588
                'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1589
                'warnings' => new external_warnings()
1590
            )
1591
        );
1592
    }
1593
 
1594
    /**
1595
     * Returns description of method parameters
1596
     *
1597
     * @return external_function_parameters
1598
     * @since Moodle 3.2
1599
     */
1600
    public static function get_user_preferences_parameters() {
1601
        return new external_function_parameters(
1602
            array(
1603
                'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''),
1604
                'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0)
1605
            )
1606
        );
1607
    }
1608
 
1609
    /**
1610
     * Return user preferences.
1611
     *
1612
     * @param string $name preference name, empty for all
1613
     * @param int $userid id of the user, 0 for current user
1614
     * @return array of warnings and preferences
1615
     * @since Moodle 3.2
1616
     * @throws moodle_exception
1617
     */
1618
    public static function get_user_preferences($name = '', $userid = 0) {
1619
        global $USER;
1620
 
1621
        $params = self::validate_parameters(self::get_user_preferences_parameters(),
1622
                                            array(
1623
                                                'name' => $name,
1624
                                                'userid' => $userid
1625
                                            ));
1626
        $preferences = array();
1627
        $warnings = array();
1628
 
1629
        $context = context_system::instance();
1630
        self::validate_context($context);
1631
 
1632
        if (empty($params['name'])) {
1633
            $name = null;
1634
        }
1635
        if (empty($params['userid'])) {
1636
            $user = null;
1637
        } else {
1638
            $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1639
            core_user::require_active_user($user);
1640
            if ($user->id != $USER->id) {
1641
                // Only admins can retrieve other users preferences.
1642
                require_capability('moodle/site:config', $context);
1643
            }
1644
        }
1645
 
1646
        $userpreferences = get_user_preferences($name, null, $user);
1647
        // Check if we received just one preference.
1648
        if (!is_array($userpreferences)) {
1649
            $userpreferences = array($name => $userpreferences);
1650
        }
1651
 
1652
        foreach ($userpreferences as $name => $value) {
1653
            $preferences[] = array(
1654
                'name' => $name,
1655
                'value' => $value,
1656
            );
1657
        }
1658
 
1659
        $result = array();
1660
        $result['preferences'] = $preferences;
1661
        $result['warnings'] = $warnings;
1662
        return $result;
1663
    }
1664
 
1665
    /**
1666
     * Returns description of method result value
1667
     *
1668
     * @return external_description
1669
     * @since Moodle 3.2
1670
     */
1671
    public static function get_user_preferences_returns() {
1672
        return new external_single_structure(
1673
            array(
1674
                'preferences' => new external_multiple_structure(
1675
                    new external_single_structure(
1676
                        array(
1677
                            'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1678
                            'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1679
                        )
1680
                    ),
1681
                    'User custom fields (also known as user profile fields)'
1682
                ),
1683
                'warnings' => new external_warnings()
1684
            )
1685
        );
1686
    }
1687
 
1688
    /**
1689
     * Returns description of method parameters
1690
     *
1691
     * @return external_function_parameters
1692
     * @since Moodle 3.2
1693
     */
1694
    public static function update_picture_parameters() {
1695
        return new external_function_parameters(
1696
            array(
1697
                'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'),
1698
                'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false),
1699
                'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0)
1700
            )
1701
        );
1702
    }
1703
 
1704
    /**
1705
     * Update or delete the user picture in the site
1706
     *
1707
     * @param  int  $draftitemid id of the user draft file to use as image
1708
     * @param  bool $delete      if we should delete the user picture
1709
     * @param  int $userid       id of the user, 0 for current user
1710
     * @return array warnings and success status
1711
     * @since Moodle 3.2
1712
     * @throws moodle_exception
1713
     */
1714
    public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1715
        global $CFG, $USER, $PAGE;
1716
 
1717
        $params = self::validate_parameters(
1718
            self::update_picture_parameters(),
1719
            array(
1720
                'draftitemid' => $draftitemid,
1721
                'delete' => $delete,
1722
                'userid' => $userid
1723
            )
1724
        );
1725
 
1726
        $context = context_system::instance();
1727
        self::validate_context($context);
1728
 
1729
        if (!empty($CFG->disableuserimages)) {
1730
            throw new moodle_exception('userimagesdisabled', 'admin');
1731
        }
1732
 
1733
        if (empty($params['userid']) or $params['userid'] == $USER->id) {
1734
            $user = $USER;
1735
            require_capability('moodle/user:editownprofile', $context);
1736
        } else {
1737
            $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1738
            core_user::require_active_user($user);
1739
            $personalcontext = context_user::instance($user->id);
1740
 
1741
            require_capability('moodle/user:editprofile', $personalcontext);
1742
            if (is_siteadmin($user) and !is_siteadmin($USER)) {  // Only admins may edit other admins.
1743
                throw new moodle_exception('useradmineditadmin');
1744
            }
1745
        }
1746
 
1747
        // Load the appropriate auth plugin.
1748
        $userauth = get_auth_plugin($user->auth);
1749
        if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1750
            throw new moodle_exception('noprofileedit', 'auth');
1751
        }
1752
 
1753
        $filemanageroptions = array(
1754
            'maxbytes' => $CFG->maxbytes,
1755
            'subdirs' => 0,
1756
            'maxfiles' => 1,
1757
            'accepted_types' => 'optimised_image'
1758
        );
1759
        $user->deletepicture = $params['delete'];
1760
        $user->imagefile = $params['draftitemid'];
1761
        $success = core_user::update_picture($user, $filemanageroptions);
1762
 
1763
        $result = array(
1764
            'success' => $success,
1765
            'warnings' => array(),
1766
        );
1767
        if ($success) {
1768
            $userpicture = new user_picture(core_user::get_user($user->id));
1769
            $userpicture->size = 1; // Size f1.
1770
            $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1771
        }
1772
        return $result;
1773
    }
1774
 
1775
    /**
1776
     * Returns description of method result value
1777
     *
1778
     * @return external_description
1779
     * @since Moodle 3.2
1780
     */
1781
    public static function update_picture_returns() {
1782
        return new external_single_structure(
1783
            array(
1784
                'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'),
1785
                'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL),
1786
                'warnings' => new external_warnings()
1787
            )
1788
        );
1789
    }
1790
 
1791
    /**
1792
     * Returns description of method parameters
1793
     *
1794
     * @return external_function_parameters
1795
     * @since Moodle 3.2
1796
     */
1797
    public static function set_user_preferences_parameters() {
1798
        return new external_function_parameters(
1799
            array(
1800
                'preferences' => new external_multiple_structure(
1801
                    new external_single_structure(
1802
                        array(
1803
                            'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1804
                            'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1805
                            'userid' => new external_value(PARAM_INT,
1806
                                'Id of the user to set the preference (default to current user)', VALUE_DEFAULT, 0),
1807
                        )
1808
                    )
1809
                )
1810
            )
1811
        );
1812
    }
1813
 
1814
    /**
1815
     * Set user preferences.
1816
     *
1817
     * @param array $preferences list of preferences including name, value and userid
1818
     * @return array of warnings and preferences saved
1819
     * @since Moodle 3.2
1820
     * @throws moodle_exception
1821
     */
1822
    public static function set_user_preferences($preferences) {
1823
        global $PAGE, $USER;
1824
 
1825
        $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
1826
        $warnings = array();
1827
        $saved = array();
1828
 
1829
        $context = context_system::instance();
1830
        $PAGE->set_context($context);
1831
 
1832
        $userscache = array();
1833
        foreach ($params['preferences'] as $pref) {
1834
            $userid = $pref['userid'] ?: $USER->id;
1835
 
1836
            // Check to which user set the preference.
1837
            if (!empty($userscache[$userid])) {
1838
                $user = $userscache[$userid];
1839
            } else {
1840
                try {
1841
                    $user = core_user::get_user($userid, '*', MUST_EXIST);
1842
                    core_user::require_active_user($user);
1843
                    $userscache[$userid] = $user;
1844
                } catch (Exception $e) {
1845
                    $warnings[] = array(
1846
                        'item' => 'user',
1847
                        'itemid' => $userid,
1848
                        'warningcode' => 'invaliduser',
1849
                        'message' => $e->getMessage()
1850
                    );
1851
                    continue;
1852
                }
1853
            }
1854
 
1855
            try {
1856
 
1441 ariadna 1857
                if (core_user::can_edit_preference($pref['name'], $user)) {
1 efrain 1858
                    $value = core_user::clean_preference($pref['value'], $pref['name']);
1859
                    set_user_preference($pref['name'], $value, $user->id);
1860
                    $saved[] = array(
1861
                        'name' => $pref['name'],
1862
                        'userid' => $user->id,
1863
                    );
1864
                } else {
1865
                    $warnings[] = array(
1866
                        'item' => 'user',
1867
                        'itemid' => $user->id,
1868
                        'warningcode' => 'nopermission',
1869
                        'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id
1870
                    );
1871
                }
1872
            } catch (Exception $e) {
1873
                $warnings[] = array(
1874
                    'item' => 'user',
1875
                    'itemid' => $user->id,
1876
                    'warningcode' => 'errorsavingpreference',
1877
                    'message' => $e->getMessage()
1878
                );
1879
            }
1880
        }
1881
 
1882
        $result = array();
1883
        $result['saved'] = $saved;
1884
        $result['warnings'] = $warnings;
1885
        return $result;
1886
    }
1887
 
1888
    /**
1889
     * Returns description of method result value
1890
     *
1891
     * @return external_description
1892
     * @since Moodle 3.2
1893
     */
1894
    public static function set_user_preferences_returns() {
1895
        return new external_single_structure(
1896
            array(
1897
                'saved' => new external_multiple_structure(
1898
                    new external_single_structure(
1899
                        array(
1900
                            'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1901
                            'userid' => new external_value(PARAM_INT, 'The user the preference was set for'),
1902
                        )
1903
                    ), 'Preferences saved'
1904
                ),
1905
                'warnings' => new external_warnings()
1906
            )
1907
        );
1908
    }
1909
 
1910
    /**
1911
     * Returns description of method parameters.
1912
     *
1913
     * @return external_function_parameters
1914
     * @since Moodle 3.2
1915
     */
1916
    public static function agree_site_policy_parameters() {
1917
        return new external_function_parameters(array());
1918
    }
1919
 
1920
    /**
1921
     * Agree the site policy for the current user.
1922
     *
1923
     * @return array of warnings and status result
1924
     * @since Moodle 3.2
1925
     * @throws moodle_exception
1926
     */
1927
    public static function agree_site_policy() {
1928
        global $CFG, $DB, $USER;
1929
 
1930
        $warnings = array();
1931
 
1932
        $context = context_system::instance();
1933
        try {
1934
            // We expect an exception here since the user didn't agree the site policy yet.
1935
            self::validate_context($context);
1936
        } catch (Exception $e) {
1937
            // We are expecting only a sitepolicynotagreed exception.
1938
            if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
1939
                // In case we receive a different exception, throw it.
1940
                throw $e;
1941
            }
1942
        }
1943
 
1944
        $manager = new \core_privacy\local\sitepolicy\manager();
1945
        if (!empty($USER->policyagreed)) {
1946
            $status = false;
1947
            $warnings[] = array(
1948
                'item' => 'user',
1949
                'itemid' => $USER->id,
1950
                'warningcode' => 'alreadyagreed',
1951
                'message' => 'The user already agreed the site policy.'
1952
            );
1953
        } else if (!$manager->is_defined()) {
1954
            $status = false;
1955
            $warnings[] = array(
1956
                'item' => 'user',
1957
                'itemid' => $USER->id,
1958
                'warningcode' => 'nositepolicy',
1959
                'message' => 'The site does not have a site policy configured.'
1960
            );
1961
        } else {
1962
            $status = $manager->accept();
1963
        }
1964
 
1965
        $result = array();
1966
        $result['status'] = $status;
1967
        $result['warnings'] = $warnings;
1968
        return $result;
1969
    }
1970
 
1971
    /**
1972
     * Returns description of method result value.
1973
     *
1974
     * @return external_description
1975
     * @since Moodle 3.2
1976
     */
1977
    public static function agree_site_policy_returns() {
1978
        return new external_single_structure(
1979
            array(
1980
                'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'),
1981
                'warnings' => new external_warnings()
1982
            )
1983
        );
1984
    }
1985
 
1986
    /**
1987
     * Returns description of method parameters.
1988
     *
1989
     * @return external_function_parameters
1990
     * @since Moodle 3.4
1991
     */
1992
    public static function get_private_files_info_parameters() {
1993
        return new external_function_parameters(
1994
            array(
1995
                'userid' => new external_value(PARAM_INT, 'Id of the user, default to current user.', VALUE_DEFAULT, 0)
1996
            )
1997
        );
1998
    }
1999
 
2000
    /**
2001
     * Returns general information about files in the user private files area.
2002
     *
2003
     * @param int $userid Id of the user, default to current user.
2004
     * @return array of warnings and file area information
2005
     * @since Moodle 3.4
2006
     * @throws moodle_exception
2007
     */
2008
    public static function get_private_files_info($userid = 0) {
2009
        global $CFG, $USER;
2010
        require_once($CFG->libdir . '/filelib.php');
2011
 
2012
        $params = self::validate_parameters(self::get_private_files_info_parameters(), array('userid' => $userid));
2013
        $warnings = array();
2014
 
2015
        $context = context_system::instance();
2016
        self::validate_context($context);
2017
 
2018
        if (empty($params['userid']) || $params['userid'] == $USER->id) {
2019
            $usercontext = context_user::instance($USER->id);
2020
            require_capability('moodle/user:manageownfiles', $usercontext);
2021
        } else {
2022
            $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2023
            core_user::require_active_user($user);
2024
            // Only admins can retrieve other users information.
2025
            require_capability('moodle/site:config', $context);
2026
            $usercontext = context_user::instance($user->id);
2027
        }
2028
 
2029
        $fileareainfo = file_get_file_area_info($usercontext->id, 'user', 'private');
2030
 
2031
        $result = array();
2032
        $result['filecount'] = $fileareainfo['filecount'];
2033
        $result['foldercount'] = $fileareainfo['foldercount'];
2034
        $result['filesize'] = $fileareainfo['filesize'];
2035
        $result['filesizewithoutreferences'] = $fileareainfo['filesize_without_references'];
2036
        $result['warnings'] = $warnings;
2037
        return $result;
2038
    }
2039
 
2040
    /**
2041
     * Returns description of method result value.
2042
     *
2043
     * @return external_description
2044
     * @since Moodle 3.4
2045
     */
2046
    public static function get_private_files_info_returns() {
2047
        return new external_single_structure(
2048
            array(
2049
                'filecount' => new external_value(PARAM_INT, 'Number of files in the area.'),
2050
                'foldercount' => new external_value(PARAM_INT, 'Number of folders in the area.'),
2051
                'filesize' => new external_value(PARAM_INT, 'Total size of the files in the area.'),
2052
                'filesizewithoutreferences' => new external_value(PARAM_INT, 'Total size of the area excluding file references'),
2053
                'warnings' => new external_warnings()
2054
            )
2055
        );
2056
    }
2057
}