Merge branch 'MDL-74172-master' of https://github.com/bmbrands/moodle
[moodle.git] / user / externallib.php
blob87f8fbed253f6253d969703651495e7d329e897b
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * External user API
20 * @package core_user
21 * @category external
22 * @copyright 2009 Petr Skodak
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 require_once("$CFG->libdir/externallib.php");
30 /**
31 * User external functions
33 * @package core_user
34 * @category external
35 * @copyright 2011 Jerome Mouneyrac
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 * @since Moodle 2.2
39 class core_user_external extends external_api {
41 /**
42 * Returns description of method parameters
44 * @return external_function_parameters
45 * @since Moodle 2.2
47 public static function create_users_parameters() {
48 global $CFG;
49 $userfields = [
50 'createpassword' => new external_value(PARAM_BOOL, 'True if password should be created and mailed to user.',
51 VALUE_OPTIONAL),
52 // General.
53 'username' => new external_value(core_user::get_property_type('username'),
54 'Username policy is defined in Moodle security config.'),
55 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
56 VALUE_DEFAULT, 'manual', core_user::get_property_null('auth')),
57 'password' => new external_value(core_user::get_property_type('password'),
58 'Plain text password consisting of any characters', VALUE_OPTIONAL),
59 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user'),
60 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user'),
61 'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address'),
62 'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email display', VALUE_OPTIONAL),
63 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
64 'country' => new external_value(core_user::get_property_type('country'),
65 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
66 'timezone' => new external_value(core_user::get_property_type('timezone'),
67 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
68 'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML',
69 VALUE_OPTIONAL),
70 // Additional names.
71 'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'),
72 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
73 'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'),
74 'The family name phonetically of the user', VALUE_OPTIONAL),
75 'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user',
76 VALUE_OPTIONAL),
77 'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user',
78 VALUE_OPTIONAL),
79 // Interests.
80 'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL),
81 // Optional.
82 'idnumber' => new external_value(core_user::get_property_type('idnumber'),
83 'An arbitrary ID code number perhaps from the institution', VALUE_DEFAULT, ''),
84 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
85 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
86 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
87 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
88 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
89 // Other user preferences stored in the user table.
90 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
91 VALUE_DEFAULT, core_user::get_property_default('lang'), core_user::get_property_null('lang')),
92 'calendartype' => new external_value(core_user::get_property_type('calendartype'),
93 'Calendar type such as "gregorian", must exist on server', VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
94 'theme' => new external_value(core_user::get_property_type('theme'),
95 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
96 'mailformat' => new external_value(core_user::get_property_type('mailformat'),
97 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
98 // Custom user profile fields.
99 'customfields' => new external_multiple_structure(
100 new external_single_structure(
102 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
103 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
105 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
106 // User preferences.
107 'preferences' => new external_multiple_structure(
108 new external_single_structure(
110 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
111 'value' => new external_value(PARAM_RAW, 'The value of the preference')
113 ), 'User preferences', VALUE_OPTIONAL),
115 return new external_function_parameters(
117 'users' => new external_multiple_structure(
118 new external_single_structure($userfields)
125 * Create one or more users.
127 * @throws invalid_parameter_exception
128 * @param array $users An array of users to create.
129 * @return array An array of arrays
130 * @since Moodle 2.2
132 public static function create_users($users) {
133 global $CFG, $DB;
134 require_once($CFG->dirroot."/lib/weblib.php");
135 require_once($CFG->dirroot."/user/lib.php");
136 require_once($CFG->dirroot."/user/editlib.php");
137 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
139 // Ensure the current user is allowed to run this function.
140 $context = context_system::instance();
141 self::validate_context($context);
142 require_capability('moodle/user:create', $context);
144 // Do basic automatic PARAM checks on incoming data, using params description.
145 // If any problems are found then exceptions are thrown with helpful error messages.
146 $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
148 $availableauths = core_component::get_plugin_list('auth');
149 unset($availableauths['mnet']); // These would need mnethostid too.
150 unset($availableauths['webservice']); // We do not want new webservice users for now.
152 $availablethemes = core_component::get_plugin_list('theme');
153 $availablelangs = get_string_manager()->get_list_of_translations();
155 $transaction = $DB->start_delegated_transaction();
157 $userids = array();
158 foreach ($params['users'] as $user) {
159 // Make sure that the username, firstname and lastname are not blank.
160 foreach (array('username', 'firstname', 'lastname') as $fieldname) {
161 if (trim($user[$fieldname]) === '') {
162 throw new invalid_parameter_exception('The field '.$fieldname.' cannot be blank');
166 // Make sure that the username doesn't already exist.
167 if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
168 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
171 // Make sure auth is valid.
172 if (empty($availableauths[$user['auth']])) {
173 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
176 // Make sure lang is valid.
177 if (empty($availablelangs[$user['lang']])) {
178 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
181 // Make sure lang is valid.
182 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
183 // so no default value
184 // We need to test if the client sent it
185 // => !empty($user['theme']).
186 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
189 // Make sure we have a password or have to create one.
190 $authplugin = get_auth_plugin($user['auth']);
191 if ($authplugin->is_internal() && empty($user['password']) && empty($user['createpassword'])) {
192 throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
195 $user['confirmed'] = true;
196 $user['mnethostid'] = $CFG->mnet_localhost_id;
198 // Start of user info validation.
199 // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
200 if (!validate_email($user['email'])) {
201 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
202 } else if (empty($CFG->allowaccountssameemail)) {
203 // Make a case-insensitive query for the given email address.
204 $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid';
205 $params = array(
206 'email' => $user['email'],
207 'mnethostid' => $user['mnethostid']
209 // If there are other user(s) that already have the same email, throw an error.
210 if ($DB->record_exists_select('user', $select, $params)) {
211 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
214 // End of user info validation.
216 $createpassword = !empty($user['createpassword']);
217 unset($user['createpassword']);
218 $updatepassword = false;
219 if ($authplugin->is_internal()) {
220 if ($createpassword) {
221 $user['password'] = '';
222 } else {
223 $updatepassword = true;
225 } else {
226 $user['password'] = AUTH_PASSWORD_NOT_CACHED;
229 // Create the user data now!
230 $user['id'] = user_create_user($user, $updatepassword, false);
232 $userobject = (object)$user;
234 // Set user interests.
235 if (!empty($user['interests'])) {
236 $trimmedinterests = array_map('trim', explode(',', $user['interests']));
237 $interests = array_filter($trimmedinterests, function($value) {
238 return !empty($value);
240 useredit_update_interests($userobject, $interests);
243 // Custom fields.
244 if (!empty($user['customfields'])) {
245 foreach ($user['customfields'] as $customfield) {
246 // Profile_save_data() saves profile file it's expecting a user with the correct id,
247 // and custom field to be named profile_field_"shortname".
248 $user["profile_field_".$customfield['type']] = $customfield['value'];
250 profile_save_data((object) $user);
253 if ($createpassword) {
254 setnew_password_and_mail($userobject);
255 unset_user_preference('create_password', $userobject);
256 set_user_preference('auth_forcepasswordchange', 1, $userobject);
259 // Trigger event.
260 \core\event\user_created::create_from_userid($user['id'])->trigger();
262 // Preferences.
263 if (!empty($user['preferences'])) {
264 $userpref = (object)$user;
265 foreach ($user['preferences'] as $preference) {
266 $userpref->{'preference_'.$preference['type']} = $preference['value'];
268 useredit_update_user_preference($userpref);
271 $userids[] = array('id' => $user['id'], 'username' => $user['username']);
274 $transaction->allow_commit();
276 return $userids;
280 * Returns description of method result value
282 * @return external_description
283 * @since Moodle 2.2
285 public static function create_users_returns() {
286 return new external_multiple_structure(
287 new external_single_structure(
288 array(
289 'id' => new external_value(core_user::get_property_type('id'), 'user id'),
290 'username' => new external_value(core_user::get_property_type('username'), 'user name'),
298 * Returns description of method parameters
300 * @return external_function_parameters
301 * @since Moodle 2.2
303 public static function delete_users_parameters() {
304 return new external_function_parameters(
305 array(
306 'userids' => new external_multiple_structure(new external_value(core_user::get_property_type('id'), 'user ID')),
312 * Delete users
314 * @throws moodle_exception
315 * @param array $userids
316 * @return null
317 * @since Moodle 2.2
319 public static function delete_users($userids) {
320 global $CFG, $DB, $USER;
321 require_once($CFG->dirroot."/user/lib.php");
323 // Ensure the current user is allowed to run this function.
324 $context = context_system::instance();
325 require_capability('moodle/user:delete', $context);
326 self::validate_context($context);
328 $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
330 $transaction = $DB->start_delegated_transaction();
332 foreach ($params['userids'] as $userid) {
333 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
334 // Must not allow deleting of admins or self!!!
335 if (is_siteadmin($user)) {
336 throw new moodle_exception('useradminodelete', 'error');
338 if ($USER->id == $user->id) {
339 throw new moodle_exception('usernotdeletederror', 'error');
341 user_delete_user($user);
344 $transaction->allow_commit();
346 return null;
350 * Returns description of method result value
352 * @return null
353 * @since Moodle 2.2
355 public static function delete_users_returns() {
356 return null;
360 * Returns description of method parameters.
362 * @return external_function_parameters
363 * @since Moodle 3.2
365 public static function update_user_preferences_parameters() {
366 return new external_function_parameters(
367 array(
368 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
369 'emailstop' => new external_value(core_user::get_property_type('emailstop'),
370 'Enable or disable notifications for this user', VALUE_DEFAULT, null),
371 'preferences' => new external_multiple_structure(
372 new external_single_structure(
373 array(
374 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
375 'value' => new external_value(PARAM_RAW, 'The value of the preference, do not set this field if you
376 want to remove (unset) the current value.', VALUE_DEFAULT, null),
378 ), 'User preferences', VALUE_DEFAULT, array()
385 * Update the user's preferences.
387 * @param int $userid
388 * @param bool|null $emailstop
389 * @param array $preferences
390 * @return null
391 * @since Moodle 3.2
393 public static function update_user_preferences($userid = 0, $emailstop = null, $preferences = array()) {
394 global $USER, $CFG;
396 require_once($CFG->dirroot . '/user/lib.php');
397 require_once($CFG->dirroot . '/user/editlib.php');
398 require_once($CFG->dirroot . '/message/lib.php');
400 if (empty($userid)) {
401 $userid = $USER->id;
404 $systemcontext = context_system::instance();
405 self::validate_context($systemcontext);
406 $params = array(
407 'userid' => $userid,
408 'emailstop' => $emailstop,
409 'preferences' => $preferences
411 $params = self::validate_parameters(self::update_user_preferences_parameters(), $params);
412 $preferences = $params['preferences'];
414 // Preferences.
415 if (!empty($preferences)) {
416 $userpref = ['id' => $userid];
417 foreach ($preferences as $preference) {
420 * Rename user message provider preferences to avoid orphan settings on old app versions.
421 * @todo Remove this "translation" block on MDL-73284.
423 if (preg_match('/message_provider_.*_loggedin/', $preference['type']) ||
424 preg_match('/message_provider_.*_loggedoff/', $preference['type'])) {
425 $nameparts = explode('_', $preference['type']);
426 array_pop($nameparts);
427 $preference['type'] = implode('_', $nameparts).'_enabled';
430 $userpref['preference_' . $preference['type']] = $preference['value'];
432 useredit_update_user_preference($userpref);
435 // Check if they want to update the email.
436 if ($emailstop !== null) {
437 $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST);
438 core_user::require_active_user($otheruser);
439 if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) {
440 $user = new stdClass();
441 $user->id = $userid;
442 $user->emailstop = $emailstop;
443 user_update_user($user);
445 // Update the $USER if we should.
446 if ($userid == $USER->id) {
447 $USER->emailstop = $emailstop;
452 return null;
456 * Returns description of method result value
458 * @return null
459 * @since Moodle 3.2
461 public static function update_user_preferences_returns() {
462 return null;
466 * Returns description of method parameters
468 * @return external_function_parameters
469 * @since Moodle 2.2
471 public static function update_users_parameters() {
472 $userfields = [
473 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
474 // General.
475 'username' => new external_value(core_user::get_property_type('username'),
476 'Username policy is defined in Moodle security config.', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
477 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
478 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
479 'suspended' => new external_value(core_user::get_property_type('suspended'),
480 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
481 'password' => new external_value(core_user::get_property_type('password'),
482 'Plain text password consisting of any characters', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
483 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user',
484 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
485 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user',
486 VALUE_OPTIONAL),
487 'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL,
488 '', NULL_NOT_ALLOWED),
489 'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email display', VALUE_OPTIONAL),
490 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
491 'country' => new external_value(core_user::get_property_type('country'),
492 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
493 'timezone' => new external_value(core_user::get_property_type('timezone'),
494 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
495 'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML',
496 VALUE_OPTIONAL),
497 // User picture.
498 'userpicture' => new external_value(PARAM_INT,
499 'The itemid where the new user picture has been uploaded to, 0 to delete', VALUE_OPTIONAL),
500 // Additional names.
501 'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'),
502 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
503 'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'),
504 'The family name phonetically of the user', VALUE_OPTIONAL),
505 'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user',
506 VALUE_OPTIONAL),
507 'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user',
508 VALUE_OPTIONAL),
509 // Interests.
510 'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL),
511 // Optional.
512 'idnumber' => new external_value(core_user::get_property_type('idnumber'),
513 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
514 'institution' => new external_value(core_user::get_property_type('institution'), 'Institution', VALUE_OPTIONAL),
515 'department' => new external_value(core_user::get_property_type('department'), 'Department', VALUE_OPTIONAL),
516 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone', VALUE_OPTIONAL),
517 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Mobile phone', VALUE_OPTIONAL),
518 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
519 // Other user preferences stored in the user table.
520 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
521 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
522 'calendartype' => new external_value(core_user::get_property_type('calendartype'),
523 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
524 'theme' => new external_value(core_user::get_property_type('theme'),
525 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
526 'mailformat' => new external_value(core_user::get_property_type('mailformat'),
527 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
528 // Custom user profile fields.
529 'customfields' => new external_multiple_structure(
530 new external_single_structure(
532 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
533 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
535 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
536 // User preferences.
537 'preferences' => new external_multiple_structure(
538 new external_single_structure(
540 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
541 'value' => new external_value(PARAM_RAW, 'The value of the preference')
543 ), 'User preferences', VALUE_OPTIONAL),
545 return new external_function_parameters(
547 'users' => new external_multiple_structure(
548 new external_single_structure($userfields)
555 * Update users
557 * @param array $users
558 * @return null
559 * @since Moodle 2.2
561 public static function update_users($users) {
562 global $CFG, $DB, $USER;
563 require_once($CFG->dirroot."/user/lib.php");
564 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
565 require_once($CFG->dirroot.'/user/editlib.php');
567 // Ensure the current user is allowed to run this function.
568 $context = context_system::instance();
569 require_capability('moodle/user:update', $context);
570 self::validate_context($context);
572 $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
574 $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
575 'subdirs' => 0,
576 'maxfiles' => 1,
577 'accepted_types' => 'optimised_image');
579 $warnings = array();
580 foreach ($params['users'] as $user) {
581 // Catch any exception while updating a user and return it as a warning.
582 try {
583 $transaction = $DB->start_delegated_transaction();
585 // First check the user exists.
586 if (!$existinguser = core_user::get_user($user['id'])) {
587 throw new moodle_exception('invaliduserid', '', '', null,
588 'Invalid user ID');
590 // Check if we are trying to update an admin.
591 if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
592 throw new moodle_exception('usernotupdatedadmin', '', '', null,
593 'Cannot update admin accounts');
595 // Other checks (deleted, remote or guest users).
596 if ($existinguser->deleted) {
597 throw new moodle_exception('usernotupdateddeleted', '', '', null,
598 'User is a deleted user');
600 if (is_mnet_remote_user($existinguser)) {
601 throw new moodle_exception('usernotupdatedremote', '', '', null,
602 'User is a remote user');
604 if (isguestuser($existinguser->id)) {
605 throw new moodle_exception('usernotupdatedguest', '', '', null,
606 'Cannot update guest account');
608 // Check duplicated emails.
609 if (isset($user['email']) && $user['email'] !== $existinguser->email) {
610 if (!validate_email($user['email'])) {
611 throw new moodle_exception('useremailinvalid', '', '', null,
612 'Invalid email address');
613 } else if (empty($CFG->allowaccountssameemail)) {
614 // Make a case-insensitive query for the given email address
615 // and make sure to exclude the user being updated.
616 $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid';
617 $params = array(
618 'email' => $user['email'],
619 'mnethostid' => $CFG->mnet_localhost_id,
620 'userid' => $user['id']
622 // Skip if there are other user(s) that already have the same email.
623 if ($DB->record_exists_select('user', $select, $params)) {
624 throw new moodle_exception('useremailduplicate', '', '', null,
625 'Duplicate email address');
630 user_update_user($user, true, false);
632 $userobject = (object)$user;
634 // Update user picture if it was specified for this user.
635 if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
636 $userobject->deletepicture = null;
638 if ($user['userpicture'] == 0) {
639 $userobject->deletepicture = true;
640 } else {
641 $userobject->imagefile = $user['userpicture'];
644 core_user::update_picture($userobject, $filemanageroptions);
647 // Update user interests.
648 if (!empty($user['interests'])) {
649 $trimmedinterests = array_map('trim', explode(',', $user['interests']));
650 $interests = array_filter($trimmedinterests, function($value) {
651 return !empty($value);
653 useredit_update_interests($userobject, $interests);
656 // Update user custom fields.
657 if (!empty($user['customfields'])) {
659 foreach ($user['customfields'] as $customfield) {
660 // Profile_save_data() saves profile file it's expecting a user with the correct id,
661 // and custom field to be named profile_field_"shortname".
662 $user["profile_field_".$customfield['type']] = $customfield['value'];
664 profile_save_data((object) $user);
667 // Trigger event.
668 \core\event\user_updated::create_from_userid($user['id'])->trigger();
670 // Preferences.
671 if (!empty($user['preferences'])) {
672 $userpref = clone($existinguser);
673 foreach ($user['preferences'] as $preference) {
674 $userpref->{'preference_'.$preference['type']} = $preference['value'];
676 useredit_update_user_preference($userpref);
678 if (isset($user['suspended']) and $user['suspended']) {
679 \core\session\manager::kill_user_sessions($user['id']);
682 $transaction->allow_commit();
683 } catch (Exception $e) {
684 try {
685 $transaction->rollback($e);
686 } catch (Exception $e) {
687 $warning = [];
688 $warning['item'] = 'user';
689 $warning['itemid'] = $user['id'];
690 if ($e instanceof moodle_exception) {
691 $warning['warningcode'] = $e->errorcode;
692 } else {
693 $warning['warningcode'] = $e->getCode();
695 $warning['message'] = $e->getMessage();
696 $warnings[] = $warning;
701 return ['warnings' => $warnings];
705 * Returns description of method result value
707 * @return external_description
708 * @since Moodle 2.2
710 public static function update_users_returns() {
711 return new external_single_structure(
712 array(
713 'warnings' => new external_warnings()
719 * Returns description of method parameters
721 * @return external_function_parameters
722 * @since Moodle 2.4
724 public static function get_users_by_field_parameters() {
725 return new external_function_parameters(
726 array(
727 'field' => new external_value(PARAM_ALPHA, 'the search field can be
728 \'id\' or \'idnumber\' or \'username\' or \'email\''),
729 'values' => new external_multiple_structure(
730 new external_value(PARAM_RAW, 'the value to match'))
736 * Get user information for a unique field.
738 * @throws coding_exception
739 * @throws invalid_parameter_exception
740 * @param string $field
741 * @param array $values
742 * @return array An array of arrays containg user profiles.
743 * @since Moodle 2.4
745 public static function get_users_by_field($field, $values) {
746 global $CFG, $USER, $DB;
747 require_once($CFG->dirroot . "/user/lib.php");
749 $params = self::validate_parameters(self::get_users_by_field_parameters(),
750 array('field' => $field, 'values' => $values));
752 // This array will keep all the users that are allowed to be searched,
753 // according to the current user's privileges.
754 $cleanedvalues = array();
756 switch ($field) {
757 case 'id':
758 $paramtype = core_user::get_property_type('id');
759 break;
760 case 'idnumber':
761 $paramtype = core_user::get_property_type('idnumber');
762 break;
763 case 'username':
764 $paramtype = core_user::get_property_type('username');
765 break;
766 case 'email':
767 $paramtype = core_user::get_property_type('email');
768 break;
769 default:
770 throw new coding_exception('invalid field parameter',
771 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
774 // Clean the values.
775 foreach ($values as $value) {
776 $cleanedvalue = clean_param($value, $paramtype);
777 if ( $value != $cleanedvalue) {
778 throw new invalid_parameter_exception('The field \'' . $field .
779 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
781 $cleanedvalues[] = $cleanedvalue;
784 // Retrieve the users.
785 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
787 $context = context_system::instance();
788 self::validate_context($context);
790 // Finally retrieve each users information.
791 $returnedusers = array();
792 foreach ($users as $user) {
793 $userdetails = user_get_user_details_courses($user);
795 // Return the user only if the searched field is returned.
796 // Otherwise it means that the $USER was not allowed to search the returned user.
797 if (!empty($userdetails) and !empty($userdetails[$field])) {
798 $returnedusers[] = $userdetails;
802 return $returnedusers;
806 * Returns description of method result value
808 * @return external_multiple_structure
809 * @since Moodle 2.4
811 public static function get_users_by_field_returns() {
812 return new external_multiple_structure(self::user_description());
817 * Returns description of get_users() parameters.
819 * @return external_function_parameters
820 * @since Moodle 2.5
822 public static function get_users_parameters() {
823 return new external_function_parameters(
824 array(
825 'criteria' => new external_multiple_structure(
826 new external_single_structure(
827 array(
828 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
829 "id" (int) matching user id,
830 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
831 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
832 "idnumber" (string) matching user idnumber,
833 "username" (string) matching user username,
834 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
835 "auth" (string) matching user auth plugin'),
836 'value' => new external_value(PARAM_RAW, 'the value to search')
838 ), 'the key/value pairs to be considered in user search. Values can not be empty.
839 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
840 key occurences are forbidden.
841 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
842 the search is still executed on the valid criterias.
843 You can search without criteria, but the function is not designed for it.
844 It could very slow or timeout. The function is designed to search some specific users.'
851 * Retrieve matching user.
853 * @throws moodle_exception
854 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
855 * @return array An array of arrays containing user profiles.
856 * @since Moodle 2.5
858 public static function get_users($criteria = array()) {
859 global $CFG, $USER, $DB;
861 require_once($CFG->dirroot . "/user/lib.php");
863 $params = self::validate_parameters(self::get_users_parameters(),
864 array('criteria' => $criteria));
866 // Validate the criteria and retrieve the users.
867 $users = array();
868 $warnings = array();
869 $sqlparams = array();
870 $usedkeys = array();
872 // Do not retrieve deleted users.
873 $sql = ' deleted = 0';
875 foreach ($params['criteria'] as $criteriaindex => $criteria) {
877 // Check that the criteria has never been used.
878 if (array_key_exists($criteria['key'], $usedkeys)) {
879 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
880 } else {
881 $usedkeys[$criteria['key']] = true;
884 $invalidcriteria = false;
885 // Clean the parameters.
886 $paramtype = PARAM_RAW;
887 switch ($criteria['key']) {
888 case 'id':
889 $paramtype = core_user::get_property_type('id');
890 break;
891 case 'idnumber':
892 $paramtype = core_user::get_property_type('idnumber');
893 break;
894 case 'username':
895 $paramtype = core_user::get_property_type('username');
896 break;
897 case 'email':
898 // We use PARAM_RAW to allow searches with %.
899 $paramtype = core_user::get_property_type('email');
900 break;
901 case 'auth':
902 $paramtype = core_user::get_property_type('auth');
903 break;
904 case 'lastname':
905 case 'firstname':
906 $paramtype = core_user::get_property_type('firstname');
907 break;
908 default:
909 // Send back a warning that this search key is not supported in this version.
910 // This warning will make the function extandable without breaking clients.
911 $warnings[] = array(
912 'item' => $criteria['key'],
913 'warningcode' => 'invalidfieldparameter',
914 'message' =>
915 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
917 // Do not add this invalid criteria to the created SQL request.
918 $invalidcriteria = true;
919 unset($params['criteria'][$criteriaindex]);
920 break;
923 if (!$invalidcriteria) {
924 $cleanedvalue = clean_param($criteria['value'], $paramtype);
926 $sql .= ' AND ';
928 // Create the SQL.
929 switch ($criteria['key']) {
930 case 'id':
931 case 'idnumber':
932 case 'username':
933 case 'auth':
934 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
935 $sqlparams[$criteria['key']] = $cleanedvalue;
936 break;
937 case 'email':
938 case 'lastname':
939 case 'firstname':
940 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
941 $sqlparams[$criteria['key']] = $cleanedvalue;
942 break;
943 default:
944 break;
949 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
951 // Finally retrieve each users information.
952 $returnedusers = array();
953 foreach ($users as $user) {
954 $userdetails = user_get_user_details_courses($user);
956 // Return the user only if all the searched fields are returned.
957 // Otherwise it means that the $USER was not allowed to search the returned user.
958 if (!empty($userdetails)) {
959 $validuser = true;
961 foreach ($params['criteria'] as $criteria) {
962 if (empty($userdetails[$criteria['key']])) {
963 $validuser = false;
967 if ($validuser) {
968 $returnedusers[] = $userdetails;
973 return array('users' => $returnedusers, 'warnings' => $warnings);
977 * Returns description of get_users result value.
979 * @return external_description
980 * @since Moodle 2.5
982 public static function get_users_returns() {
983 return new external_single_structure(
984 array('users' => new external_multiple_structure(
985 self::user_description()
987 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
993 * Returns description of method parameters
995 * @return external_function_parameters
996 * @since Moodle 2.2
998 public static function get_course_user_profiles_parameters() {
999 return new external_function_parameters(
1000 array(
1001 'userlist' => new external_multiple_structure(
1002 new external_single_structure(
1003 array(
1004 'userid' => new external_value(core_user::get_property_type('id'), 'userid'),
1005 'courseid' => new external_value(PARAM_INT, 'courseid'),
1014 * Get course participant's details
1016 * @param array $userlist array of user ids and according course ids
1017 * @return array An array of arrays describing course participants
1018 * @since Moodle 2.2
1020 public static function get_course_user_profiles($userlist) {
1021 global $CFG, $USER, $DB;
1022 require_once($CFG->dirroot . "/user/lib.php");
1023 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
1025 $userids = array();
1026 $courseids = array();
1027 foreach ($params['userlist'] as $value) {
1028 $userids[] = $value['userid'];
1029 $courseids[$value['userid']] = $value['courseid'];
1032 // Cache all courses.
1033 $courses = array();
1034 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
1035 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1036 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1037 $params['contextlevel'] = CONTEXT_COURSE;
1038 $coursesql = "SELECT c.* $cselect
1039 FROM {course} c $cjoin
1040 WHERE c.id $sqlcourseids";
1041 $rs = $DB->get_recordset_sql($coursesql, $params);
1042 foreach ($rs as $course) {
1043 // Adding course contexts to cache.
1044 context_helper::preload_from_record($course);
1045 // Cache courses.
1046 $courses[$course->id] = $course;
1048 $rs->close();
1050 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
1051 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1052 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
1053 $params['contextlevel'] = CONTEXT_USER;
1054 $usersql = "SELECT u.* $uselect
1055 FROM {user} u $ujoin
1056 WHERE u.id $sqluserids";
1057 $users = $DB->get_recordset_sql($usersql, $params);
1058 $result = array();
1059 foreach ($users as $user) {
1060 if (!empty($user->deleted)) {
1061 continue;
1063 context_helper::preload_from_record($user);
1064 $course = $courses[$courseids[$user->id]];
1065 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
1066 self::validate_context($context);
1067 if ($userarray = user_get_user_details($user, $course)) {
1068 $result[] = $userarray;
1072 $users->close();
1074 return $result;
1078 * Returns description of method result value
1080 * @return external_description
1081 * @since Moodle 2.2
1083 public static function get_course_user_profiles_returns() {
1084 $additionalfields = array(
1085 'groups' => new external_multiple_structure(
1086 new external_single_structure(
1087 array(
1088 'id' => new external_value(PARAM_INT, 'group id'),
1089 'name' => new external_value(PARAM_RAW, 'group name'),
1090 'description' => new external_value(PARAM_RAW, 'group description'),
1091 'descriptionformat' => new external_format_value('description'),
1093 ), 'user groups', VALUE_OPTIONAL),
1094 'roles' => new external_multiple_structure(
1095 new external_single_structure(
1096 array(
1097 'roleid' => new external_value(PARAM_INT, 'role id'),
1098 'name' => new external_value(PARAM_RAW, 'role name'),
1099 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
1100 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
1102 ), 'user roles', VALUE_OPTIONAL),
1103 'enrolledcourses' => new external_multiple_structure(
1104 new external_single_structure(
1105 array(
1106 'id' => new external_value(PARAM_INT, 'Id of the course'),
1107 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
1108 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
1110 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
1113 return new external_multiple_structure(self::user_description($additionalfields));
1117 * Create user return value description.
1119 * @param array $additionalfields some additional field
1120 * @return single_structure_description
1122 public static function user_description($additionalfields = array()) {
1123 $userfields = array(
1124 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
1125 'username' => new external_value(core_user::get_property_type('username'), 'The username', VALUE_OPTIONAL),
1126 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL),
1127 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
1128 'fullname' => new external_value(core_user::get_property_type('firstname'), 'The fullname of the user'),
1129 'email' => new external_value(core_user::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
1130 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
1131 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
1132 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
1133 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
1134 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
1135 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
1136 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
1137 'firstaccess' => new external_value(core_user::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL),
1138 'lastaccess' => new external_value(core_user::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL),
1139 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL),
1140 '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),
1141 'confirmed' => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
1142 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
1143 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
1144 'theme' => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
1145 'timezone' => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
1146 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
1147 'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL),
1148 'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL),
1149 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
1150 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
1151 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
1152 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
1153 'customfields' => new external_multiple_structure(
1154 new external_single_structure(
1155 array(
1156 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
1157 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
1158 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
1159 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
1161 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
1162 'preferences' => new external_multiple_structure(
1163 new external_single_structure(
1164 array(
1165 'name' => new external_value(PARAM_RAW, 'The name of the preferences'),
1166 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1168 ), 'Users preferences', VALUE_OPTIONAL)
1170 if (!empty($additionalfields)) {
1171 $userfields = array_merge($userfields, $additionalfields);
1173 return new external_single_structure($userfields);
1177 * Returns description of method parameters
1179 * @return external_function_parameters
1180 * @since Moodle 2.6
1182 public static function add_user_private_files_parameters() {
1183 return new external_function_parameters(
1184 array(
1185 'draftid' => new external_value(PARAM_INT, 'draft area id')
1191 * Copy files from a draft area to users private files area.
1193 * @throws invalid_parameter_exception
1194 * @param int $draftid Id of a draft area containing files.
1195 * @return array An array of warnings
1196 * @since Moodle 2.6
1198 public static function add_user_private_files($draftid) {
1199 global $CFG, $USER;
1200 require_once($CFG->libdir . "/filelib.php");
1202 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
1204 if (isguestuser()) {
1205 throw new invalid_parameter_exception('Guest users cannot upload files');
1208 $context = context_user::instance($USER->id);
1209 require_capability('moodle/user:manageownfiles', $context);
1211 $maxbytes = $CFG->userquota;
1212 $maxareabytes = $CFG->userquota;
1213 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1214 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1215 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1218 $options = array('subdirs' => 1,
1219 'maxbytes' => $maxbytes,
1220 'maxfiles' => -1,
1221 'areamaxbytes' => $maxareabytes);
1223 file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options);
1225 return null;
1229 * Returns description of method result value
1231 * @return external_description
1232 * @since Moodle 2.2
1234 public static function add_user_private_files_returns() {
1235 return null;
1239 * Returns description of method parameters.
1241 * @return external_function_parameters
1242 * @since Moodle 2.6
1244 public static function add_user_device_parameters() {
1245 return new external_function_parameters(
1246 array(
1247 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1248 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1249 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1250 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1251 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1252 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1253 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1259 * Add a user device in Moodle database (for PUSH notifications usually).
1261 * @throws moodle_exception
1262 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1263 * @param string $name The device name, occam or iPhone etc.
1264 * @param string $model The device model Nexus4 or iPad1.1 etc.
1265 * @param string $platform The device platform iOs or Android etc.
1266 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1267 * @param string $pushid The device PUSH token/key/identifier/registration id.
1268 * @param string $uuid The device UUID.
1269 * @return array List of possible warnings.
1270 * @since Moodle 2.6
1272 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1273 global $CFG, $USER, $DB;
1274 require_once($CFG->dirroot . "/user/lib.php");
1276 $params = self::validate_parameters(self::add_user_device_parameters(),
1277 array('appid' => $appid,
1278 'name' => $name,
1279 'model' => $model,
1280 'platform' => $platform,
1281 'version' => $version,
1282 'pushid' => $pushid,
1283 'uuid' => $uuid
1286 $warnings = array();
1288 // Prevent duplicate keys for users.
1289 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1290 $warnings['warning'][] = array(
1291 'item' => $params['pushid'],
1292 'warningcode' => 'existingkeyforthisuser',
1293 'message' => 'This key is already stored for this user'
1295 return $warnings;
1298 // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1299 // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1300 if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1301 'appid' => $params['appid'], 'userid' => $USER->id))) {
1303 foreach ($userdevices as $userdevice) {
1304 $userdevice->version = $params['version']; // Maybe the user upgraded the device.
1305 $userdevice->pushid = $params['pushid'];
1306 $userdevice->timemodified = time();
1307 $DB->update_record('user_devices', $userdevice);
1310 } else {
1311 $userdevice = new stdclass;
1312 $userdevice->userid = $USER->id;
1313 $userdevice->appid = $params['appid'];
1314 $userdevice->name = $params['name'];
1315 $userdevice->model = $params['model'];
1316 $userdevice->platform = $params['platform'];
1317 $userdevice->version = $params['version'];
1318 $userdevice->pushid = $params['pushid'];
1319 $userdevice->uuid = $params['uuid'];
1320 $userdevice->timecreated = time();
1321 $userdevice->timemodified = $userdevice->timecreated;
1323 if (!$DB->insert_record('user_devices', $userdevice)) {
1324 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1328 return $warnings;
1332 * Returns description of method result value.
1334 * @return external_multiple_structure
1335 * @since Moodle 2.6
1337 public static function add_user_device_returns() {
1338 return new external_multiple_structure(
1339 new external_warnings()
1344 * Returns description of method parameters.
1346 * @return external_function_parameters
1347 * @since Moodle 2.9
1349 public static function remove_user_device_parameters() {
1350 return new external_function_parameters(
1351 array(
1352 'uuid' => new external_value(PARAM_RAW, 'the device UUID'),
1353 'appid' => new external_value(PARAM_NOTAGS,
1354 'the app id, if empty devices matching the UUID for the user will be removed',
1355 VALUE_DEFAULT, ''),
1361 * Remove a user device from the Moodle database (for PUSH notifications usually).
1363 * @param string $uuid The device UUID.
1364 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1365 * @return array List of possible warnings and removal status.
1366 * @since Moodle 2.9
1368 public static function remove_user_device($uuid, $appid = "") {
1369 global $CFG;
1370 require_once($CFG->dirroot . "/user/lib.php");
1372 $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1374 $context = context_system::instance();
1375 self::validate_context($context);
1377 // Warnings array, it can be empty at the end but is mandatory.
1378 $warnings = array();
1380 $removed = user_remove_user_device($params['uuid'], $params['appid']);
1382 if (!$removed) {
1383 $warnings[] = array(
1384 'item' => $params['uuid'],
1385 'warningcode' => 'devicedoesnotexist',
1386 'message' => 'The device doesn\'t exists in the database'
1390 $result = array(
1391 'removed' => $removed,
1392 'warnings' => $warnings
1395 return $result;
1399 * Returns description of method result value.
1401 * @return external_multiple_structure
1402 * @since Moodle 2.9
1404 public static function remove_user_device_returns() {
1405 return new external_single_structure(
1406 array(
1407 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
1408 'warnings' => new external_warnings(),
1414 * Returns description of method parameters
1416 * @return external_function_parameters
1417 * @since Moodle 2.9
1419 public static function view_user_list_parameters() {
1420 return new external_function_parameters(
1421 array(
1422 'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site')
1428 * Trigger the user_list_viewed event.
1430 * @param int $courseid id of course
1431 * @return array of warnings and status result
1432 * @since Moodle 2.9
1433 * @throws moodle_exception
1435 public static function view_user_list($courseid) {
1436 global $CFG;
1437 require_once($CFG->dirroot . "/user/lib.php");
1438 require_once($CFG->dirroot . '/course/lib.php');
1440 $params = self::validate_parameters(self::view_user_list_parameters(),
1441 array(
1442 'courseid' => $courseid
1445 $warnings = array();
1447 if (empty($params['courseid'])) {
1448 $params['courseid'] = SITEID;
1451 $course = get_course($params['courseid']);
1453 if ($course->id == SITEID) {
1454 $context = context_system::instance();
1455 } else {
1456 $context = context_course::instance($course->id);
1458 self::validate_context($context);
1460 course_require_view_participants($context);
1462 user_list_view($course, $context);
1464 $result = array();
1465 $result['status'] = true;
1466 $result['warnings'] = $warnings;
1467 return $result;
1471 * Returns description of method result value
1473 * @return external_description
1474 * @since Moodle 2.9
1476 public static function view_user_list_returns() {
1477 return new external_single_structure(
1478 array(
1479 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1480 'warnings' => new external_warnings()
1486 * Returns description of method parameters
1488 * @return external_function_parameters
1489 * @since Moodle 2.9
1491 public static function view_user_profile_parameters() {
1492 return new external_function_parameters(
1493 array(
1494 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1495 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
1501 * Trigger the user profile viewed event.
1503 * @param int $userid id of user
1504 * @param int $courseid id of course
1505 * @return array of warnings and status result
1506 * @since Moodle 2.9
1507 * @throws moodle_exception
1509 public static function view_user_profile($userid, $courseid = 0) {
1510 global $CFG, $USER;
1511 require_once($CFG->dirroot . "/user/profile/lib.php");
1513 $params = self::validate_parameters(self::view_user_profile_parameters(),
1514 array(
1515 'userid' => $userid,
1516 'courseid' => $courseid
1519 $warnings = array();
1521 if (empty($params['userid'])) {
1522 $params['userid'] = $USER->id;
1525 if (empty($params['courseid'])) {
1526 $params['courseid'] = SITEID;
1529 $course = get_course($params['courseid']);
1530 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1531 core_user::require_active_user($user);
1533 if ($course->id == SITEID) {
1534 $coursecontext = context_system::instance();;
1535 } else {
1536 $coursecontext = context_course::instance($course->id);
1538 self::validate_context($coursecontext);
1540 $currentuser = $USER->id == $user->id;
1541 $usercontext = context_user::instance($user->id);
1543 if (!$currentuser and
1544 !has_capability('moodle/user:viewdetails', $coursecontext) and
1545 !has_capability('moodle/user:viewdetails', $usercontext)) {
1546 throw new moodle_exception('cannotviewprofile');
1549 // Case like user/profile.php.
1550 if ($course->id == SITEID) {
1551 profile_view($user, $usercontext);
1552 } else {
1553 // Case like user/view.php.
1554 if (!$currentuser and !can_access_course($course, $user, '', true)) {
1555 throw new moodle_exception('notenrolledprofile');
1558 profile_view($user, $coursecontext, $course);
1561 $result = array();
1562 $result['status'] = true;
1563 $result['warnings'] = $warnings;
1564 return $result;
1568 * Returns description of method result value
1570 * @return external_description
1571 * @since Moodle 2.9
1573 public static function view_user_profile_returns() {
1574 return new external_single_structure(
1575 array(
1576 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1577 'warnings' => new external_warnings()
1583 * Returns description of method parameters
1585 * @return external_function_parameters
1586 * @since Moodle 3.2
1588 public static function get_user_preferences_parameters() {
1589 return new external_function_parameters(
1590 array(
1591 'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''),
1592 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0)
1598 * Return user preferences.
1600 * @param string $name preference name, empty for all
1601 * @param int $userid id of the user, 0 for current user
1602 * @return array of warnings and preferences
1603 * @since Moodle 3.2
1604 * @throws moodle_exception
1606 public static function get_user_preferences($name = '', $userid = 0) {
1607 global $USER;
1609 $params = self::validate_parameters(self::get_user_preferences_parameters(),
1610 array(
1611 'name' => $name,
1612 'userid' => $userid
1614 $preferences = array();
1615 $warnings = array();
1617 $context = context_system::instance();
1618 self::validate_context($context);
1620 if (empty($params['name'])) {
1621 $name = null;
1623 if (empty($params['userid'])) {
1624 $user = null;
1625 } else {
1626 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1627 core_user::require_active_user($user);
1628 if ($user->id != $USER->id) {
1629 // Only admins can retrieve other users preferences.
1630 require_capability('moodle/site:config', $context);
1634 $userpreferences = get_user_preferences($name, null, $user);
1635 // Check if we received just one preference.
1636 if (!is_array($userpreferences)) {
1637 $userpreferences = array($name => $userpreferences);
1640 foreach ($userpreferences as $name => $value) {
1641 $preferences[] = array(
1642 'name' => $name,
1643 'value' => $value,
1647 $result = array();
1648 $result['preferences'] = $preferences;
1649 $result['warnings'] = $warnings;
1650 return $result;
1654 * Returns description of method result value
1656 * @return external_description
1657 * @since Moodle 3.2
1659 public static function get_user_preferences_returns() {
1660 return new external_single_structure(
1661 array(
1662 'preferences' => new external_multiple_structure(
1663 new external_single_structure(
1664 array(
1665 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1666 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1669 'User custom fields (also known as user profile fields)'
1671 'warnings' => new external_warnings()
1677 * Returns description of method parameters
1679 * @return external_function_parameters
1680 * @since Moodle 3.2
1682 public static function update_picture_parameters() {
1683 return new external_function_parameters(
1684 array(
1685 'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'),
1686 'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false),
1687 'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0)
1693 * Update or delete the user picture in the site
1695 * @param int $draftitemid id of the user draft file to use as image
1696 * @param bool $delete if we should delete the user picture
1697 * @param int $userid id of the user, 0 for current user
1698 * @return array warnings and success status
1699 * @since Moodle 3.2
1700 * @throws moodle_exception
1702 public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1703 global $CFG, $USER, $PAGE;
1705 $params = self::validate_parameters(
1706 self::update_picture_parameters(),
1707 array(
1708 'draftitemid' => $draftitemid,
1709 'delete' => $delete,
1710 'userid' => $userid
1714 $context = context_system::instance();
1715 self::validate_context($context);
1717 if (!empty($CFG->disableuserimages)) {
1718 throw new moodle_exception('userimagesdisabled', 'admin');
1721 if (empty($params['userid']) or $params['userid'] == $USER->id) {
1722 $user = $USER;
1723 require_capability('moodle/user:editownprofile', $context);
1724 } else {
1725 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1726 core_user::require_active_user($user);
1727 $personalcontext = context_user::instance($user->id);
1729 require_capability('moodle/user:editprofile', $personalcontext);
1730 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
1731 throw new moodle_exception('useradmineditadmin');
1735 // Load the appropriate auth plugin.
1736 $userauth = get_auth_plugin($user->auth);
1737 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1738 throw new moodle_exception('noprofileedit', 'auth');
1741 $filemanageroptions = array(
1742 'maxbytes' => $CFG->maxbytes,
1743 'subdirs' => 0,
1744 'maxfiles' => 1,
1745 'accepted_types' => 'optimised_image'
1747 $user->deletepicture = $params['delete'];
1748 $user->imagefile = $params['draftitemid'];
1749 $success = core_user::update_picture($user, $filemanageroptions);
1751 $result = array(
1752 'success' => $success,
1753 'warnings' => array(),
1755 if ($success) {
1756 $userpicture = new user_picture(core_user::get_user($user->id));
1757 $userpicture->size = 1; // Size f1.
1758 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1760 return $result;
1764 * Returns description of method result value
1766 * @return external_description
1767 * @since Moodle 3.2
1769 public static function update_picture_returns() {
1770 return new external_single_structure(
1771 array(
1772 'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'),
1773 'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL),
1774 'warnings' => new external_warnings()
1780 * Returns description of method parameters
1782 * @return external_function_parameters
1783 * @since Moodle 3.2
1785 public static function set_user_preferences_parameters() {
1786 return new external_function_parameters(
1787 array(
1788 'preferences' => new external_multiple_structure(
1789 new external_single_structure(
1790 array(
1791 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1792 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1793 'userid' => new external_value(PARAM_INT, 'Id of the user to set the preference'),
1802 * Set user preferences.
1804 * @param array $preferences list of preferences including name, value and userid
1805 * @return array of warnings and preferences saved
1806 * @since Moodle 3.2
1807 * @throws moodle_exception
1809 public static function set_user_preferences($preferences) {
1810 global $USER;
1812 $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
1813 $warnings = array();
1814 $saved = array();
1816 $context = context_system::instance();
1817 self::validate_context($context);
1819 $userscache = array();
1820 foreach ($params['preferences'] as $pref) {
1821 // Check to which user set the preference.
1822 if (!empty($userscache[$pref['userid']])) {
1823 $user = $userscache[$pref['userid']];
1824 } else {
1825 try {
1826 $user = core_user::get_user($pref['userid'], '*', MUST_EXIST);
1827 core_user::require_active_user($user);
1828 $userscache[$pref['userid']] = $user;
1829 } catch (Exception $e) {
1830 $warnings[] = array(
1831 'item' => 'user',
1832 'itemid' => $pref['userid'],
1833 'warningcode' => 'invaliduser',
1834 'message' => $e->getMessage()
1836 continue;
1840 try {
1841 if (core_user::can_edit_preference($pref['name'], $user)) {
1842 $value = core_user::clean_preference($pref['value'], $pref['name']);
1843 set_user_preference($pref['name'], $value, $user->id);
1844 $saved[] = array(
1845 'name' => $pref['name'],
1846 'userid' => $user->id,
1848 } else {
1849 $warnings[] = array(
1850 'item' => 'user',
1851 'itemid' => $user->id,
1852 'warningcode' => 'nopermission',
1853 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id
1856 } catch (Exception $e) {
1857 $warnings[] = array(
1858 'item' => 'user',
1859 'itemid' => $user->id,
1860 'warningcode' => 'errorsavingpreference',
1861 'message' => $e->getMessage()
1866 $result = array();
1867 $result['saved'] = $saved;
1868 $result['warnings'] = $warnings;
1869 return $result;
1873 * Returns description of method result value
1875 * @return external_description
1876 * @since Moodle 3.2
1878 public static function set_user_preferences_returns() {
1879 return new external_single_structure(
1880 array(
1881 'saved' => new external_multiple_structure(
1882 new external_single_structure(
1883 array(
1884 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1885 'userid' => new external_value(PARAM_INT, 'The user the preference was set for'),
1887 ), 'Preferences saved'
1889 'warnings' => new external_warnings()
1895 * Returns description of method parameters.
1897 * @return external_function_parameters
1898 * @since Moodle 3.2
1900 public static function agree_site_policy_parameters() {
1901 return new external_function_parameters(array());
1905 * Agree the site policy for the current user.
1907 * @return array of warnings and status result
1908 * @since Moodle 3.2
1909 * @throws moodle_exception
1911 public static function agree_site_policy() {
1912 global $CFG, $DB, $USER;
1914 $warnings = array();
1916 $context = context_system::instance();
1917 try {
1918 // We expect an exception here since the user didn't agree the site policy yet.
1919 self::validate_context($context);
1920 } catch (Exception $e) {
1921 // We are expecting only a sitepolicynotagreed exception.
1922 if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
1923 // In case we receive a different exception, throw it.
1924 throw $e;
1928 $manager = new \core_privacy\local\sitepolicy\manager();
1929 if (!empty($USER->policyagreed)) {
1930 $status = false;
1931 $warnings[] = array(
1932 'item' => 'user',
1933 'itemid' => $USER->id,
1934 'warningcode' => 'alreadyagreed',
1935 'message' => 'The user already agreed the site policy.'
1937 } else if (!$manager->is_defined()) {
1938 $status = false;
1939 $warnings[] = array(
1940 'item' => 'user',
1941 'itemid' => $USER->id,
1942 'warningcode' => 'nositepolicy',
1943 'message' => 'The site does not have a site policy configured.'
1945 } else {
1946 $status = $manager->accept();
1949 $result = array();
1950 $result['status'] = $status;
1951 $result['warnings'] = $warnings;
1952 return $result;
1956 * Returns description of method result value.
1958 * @return external_description
1959 * @since Moodle 3.2
1961 public static function agree_site_policy_returns() {
1962 return new external_single_structure(
1963 array(
1964 'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'),
1965 'warnings' => new external_warnings()
1971 * Returns description of method parameters.
1973 * @return external_function_parameters
1974 * @since Moodle 3.4
1976 public static function get_private_files_info_parameters() {
1977 return new external_function_parameters(
1978 array(
1979 'userid' => new external_value(PARAM_INT, 'Id of the user, default to current user.', VALUE_DEFAULT, 0)
1985 * Returns general information about files in the user private files area.
1987 * @param int $userid Id of the user, default to current user.
1988 * @return array of warnings and file area information
1989 * @since Moodle 3.4
1990 * @throws moodle_exception
1992 public static function get_private_files_info($userid = 0) {
1993 global $CFG, $USER;
1994 require_once($CFG->libdir . '/filelib.php');
1996 $params = self::validate_parameters(self::get_private_files_info_parameters(), array('userid' => $userid));
1997 $warnings = array();
1999 $context = context_system::instance();
2000 self::validate_context($context);
2002 if (empty($params['userid']) || $params['userid'] == $USER->id) {
2003 $usercontext = context_user::instance($USER->id);
2004 require_capability('moodle/user:manageownfiles', $usercontext);
2005 } else {
2006 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2007 core_user::require_active_user($user);
2008 // Only admins can retrieve other users information.
2009 require_capability('moodle/site:config', $context);
2010 $usercontext = context_user::instance($user->id);
2013 $fileareainfo = file_get_file_area_info($usercontext->id, 'user', 'private');
2015 $result = array();
2016 $result['filecount'] = $fileareainfo['filecount'];
2017 $result['foldercount'] = $fileareainfo['foldercount'];
2018 $result['filesize'] = $fileareainfo['filesize'];
2019 $result['filesizewithoutreferences'] = $fileareainfo['filesize_without_references'];
2020 $result['warnings'] = $warnings;
2021 return $result;
2025 * Returns description of method result value.
2027 * @return external_description
2028 * @since Moodle 3.4
2030 public static function get_private_files_info_returns() {
2031 return new external_single_structure(
2032 array(
2033 'filecount' => new external_value(PARAM_INT, 'Number of files in the area.'),
2034 'foldercount' => new external_value(PARAM_INT, 'Number of folders in the area.'),
2035 'filesize' => new external_value(PARAM_INT, 'Total size of the files in the area.'),
2036 'filesizewithoutreferences' => new external_value(PARAM_INT, 'Total size of the area excluding file references'),
2037 'warnings' => new external_warnings()