Merge branch 'MDL-76920-master' of https://github.com/cescobedo/moodle
[moodle.git] / user / externallib.php
blob9a58d1103daff2c6c350721ba019fc438b9fa654
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 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;
25 /**
26 * User external functions
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
34 class core_user_external extends \core_external\external_api {
36 /**
37 * Returns description of method parameters
39 * @return external_function_parameters
40 * @since Moodle 2.2
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(
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')
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(
105 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
106 'value' => new external_value(PARAM_RAW, 'The value of the preference')
108 ), 'User preferences', VALUE_OPTIONAL),
110 return new external_function_parameters(
112 'users' => new external_multiple_structure(
113 new external_single_structure($userfields)
120 * Create one or more users.
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
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.
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);
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));
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.
147 $availablethemes = core_component::get_plugin_list('theme');
148 $availablelangs = get_string_manager()->get_list_of_translations();
150 $transaction = $DB->start_delegated_transaction();
152 $userids = array();
153 foreach ($params['users'] as $user) {
154 // Make sure that the username, firstname and lastname are not blank.
155 foreach (array('username', 'firstname', 'lastname') as $fieldname) {
156 if (trim($user[$fieldname]) === '') {
157 throw new invalid_parameter_exception('The field '.$fieldname.' cannot be blank');
161 // Make sure that the username doesn't already exist.
162 if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
163 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
166 // Make sure auth is valid.
167 if (empty($availableauths[$user['auth']])) {
168 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
171 // Make sure lang is valid.
172 if (empty($availablelangs[$user['lang']])) {
173 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
176 // Make sure lang is valid.
177 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
178 // so no default value
179 // We need to test if the client sent it
180 // => !empty($user['theme']).
181 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
184 // Make sure we have a password or have to create one.
185 $authplugin = get_auth_plugin($user['auth']);
186 if ($authplugin->is_internal() && empty($user['password']) && empty($user['createpassword'])) {
187 throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
190 $user['confirmed'] = true;
191 $user['mnethostid'] = $CFG->mnet_localhost_id;
193 // Start of user info validation.
194 // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
195 if (!validate_email($user['email'])) {
196 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
197 } else if (empty($CFG->allowaccountssameemail)) {
198 // Make a case-insensitive query for the given email address.
199 $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid';
200 $params = array(
201 'email' => $user['email'],
202 'mnethostid' => $user['mnethostid']
204 // If there are other user(s) that already have the same email, throw an error.
205 if ($DB->record_exists_select('user', $select, $params)) {
206 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
209 // End of user info validation.
211 $createpassword = !empty($user['createpassword']);
212 unset($user['createpassword']);
213 $updatepassword = false;
214 if ($authplugin->is_internal()) {
215 if ($createpassword) {
216 $user['password'] = '';
217 } else {
218 $updatepassword = true;
220 } else {
221 $user['password'] = AUTH_PASSWORD_NOT_CACHED;
224 // Create the user data now!
225 $user['id'] = user_create_user($user, $updatepassword, false);
227 $userobject = (object)$user;
229 // Set user interests.
230 if (!empty($user['interests'])) {
231 $trimmedinterests = array_map('trim', explode(',', $user['interests']));
232 $interests = array_filter($trimmedinterests, function($value) {
233 return !empty($value);
235 useredit_update_interests($userobject, $interests);
238 // Custom fields.
239 if (!empty($user['customfields'])) {
240 foreach ($user['customfields'] as $customfield) {
241 // Profile_save_data() saves profile file it's expecting a user with the correct id,
242 // and custom field to be named profile_field_"shortname".
243 $user["profile_field_".$customfield['type']] = $customfield['value'];
245 profile_save_data((object) $user);
248 if ($createpassword) {
249 setnew_password_and_mail($userobject);
250 unset_user_preference('create_password', $userobject);
251 set_user_preference('auth_forcepasswordchange', 1, $userobject);
254 // Trigger event.
255 \core\event\user_created::create_from_userid($user['id'])->trigger();
257 // Preferences.
258 if (!empty($user['preferences'])) {
259 $userpref = (object)$user;
260 foreach ($user['preferences'] as $preference) {
261 $userpref->{'preference_'.$preference['type']} = $preference['value'];
263 useredit_update_user_preference($userpref);
266 $userids[] = array('id' => $user['id'], 'username' => $user['username']);
269 $transaction->allow_commit();
271 return $userids;
275 * Returns description of method result value
277 * @return external_description
278 * @since Moodle 2.2
280 public static function create_users_returns() {
281 return new external_multiple_structure(
282 new external_single_structure(
283 array(
284 'id' => new external_value(core_user::get_property_type('id'), 'user id'),
285 'username' => new external_value(core_user::get_property_type('username'), 'user name'),
293 * Returns description of method parameters
295 * @return external_function_parameters
296 * @since Moodle 2.2
298 public static function delete_users_parameters() {
299 return new external_function_parameters(
300 array(
301 'userids' => new external_multiple_structure(new external_value(core_user::get_property_type('id'), 'user ID')),
307 * Delete users
309 * @throws moodle_exception
310 * @param array $userids
311 * @return null
312 * @since Moodle 2.2
314 public static function delete_users($userids) {
315 global $CFG, $DB, $USER;
316 require_once($CFG->dirroot."/user/lib.php");
318 // Ensure the current user is allowed to run this function.
319 $context = context_system::instance();
320 require_capability('moodle/user:delete', $context);
321 self::validate_context($context);
323 $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
325 $transaction = $DB->start_delegated_transaction();
327 foreach ($params['userids'] as $userid) {
328 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
329 // Must not allow deleting of admins or self!!!
330 if (is_siteadmin($user)) {
331 throw new moodle_exception('useradminodelete', 'error');
333 if ($USER->id == $user->id) {
334 throw new moodle_exception('usernotdeletederror', 'error');
336 user_delete_user($user);
339 $transaction->allow_commit();
341 return null;
345 * Returns description of method result value
347 * @return null
348 * @since Moodle 2.2
350 public static function delete_users_returns() {
351 return null;
355 * Returns description of method parameters.
357 * @return external_function_parameters
358 * @since Moodle 3.2
360 public static function update_user_preferences_parameters() {
361 return new external_function_parameters(
362 array(
363 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
364 'emailstop' => new external_value(core_user::get_property_type('emailstop'),
365 'Enable or disable notifications for this user', VALUE_DEFAULT, null),
366 'preferences' => new external_multiple_structure(
367 new external_single_structure(
368 array(
369 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
370 'value' => new external_value(PARAM_RAW, 'The value of the preference, do not set this field if you
371 want to remove (unset) the current value.', VALUE_DEFAULT, null),
373 ), 'User preferences', VALUE_DEFAULT, array()
380 * Update the user's preferences.
382 * @param int $userid
383 * @param bool|null $emailstop
384 * @param array $preferences
385 * @return null
386 * @since Moodle 3.2
388 public static function update_user_preferences($userid = 0, $emailstop = null, $preferences = array()) {
389 global $USER, $CFG;
391 require_once($CFG->dirroot . '/user/lib.php');
392 require_once($CFG->dirroot . '/user/editlib.php');
393 require_once($CFG->dirroot . '/message/lib.php');
395 if (empty($userid)) {
396 $userid = $USER->id;
399 $systemcontext = context_system::instance();
400 self::validate_context($systemcontext);
401 $params = array(
402 'userid' => $userid,
403 'emailstop' => $emailstop,
404 'preferences' => $preferences
406 $params = self::validate_parameters(self::update_user_preferences_parameters(), $params);
407 $preferences = $params['preferences'];
409 // Preferences.
410 if (!empty($preferences)) {
411 $userpref = ['id' => $userid];
412 foreach ($preferences as $preference) {
415 * Rename user message provider preferences to avoid orphan settings on old app versions.
416 * @todo Remove this "translation" block on MDL-73284.
418 if (preg_match('/message_provider_.*_loggedin/', $preference['type']) ||
419 preg_match('/message_provider_.*_loggedoff/', $preference['type'])) {
420 $nameparts = explode('_', $preference['type']);
421 array_pop($nameparts);
422 $preference['type'] = implode('_', $nameparts).'_enabled';
425 $userpref['preference_' . $preference['type']] = $preference['value'];
427 useredit_update_user_preference($userpref);
430 // Check if they want to update the email.
431 if ($emailstop !== null) {
432 $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST);
433 core_user::require_active_user($otheruser);
434 if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) {
435 $user = new stdClass();
436 $user->id = $userid;
437 $user->emailstop = $emailstop;
438 user_update_user($user);
440 // Update the $USER if we should.
441 if ($userid == $USER->id) {
442 $USER->emailstop = $emailstop;
447 return null;
451 * Returns description of method result value
453 * @return null
454 * @since Moodle 3.2
456 public static function update_user_preferences_returns() {
457 return null;
461 * Returns description of method parameters
463 * @return external_function_parameters
464 * @since Moodle 2.2
466 public static function update_users_parameters() {
467 $userfields = [
468 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
469 // General.
470 'username' => new external_value(core_user::get_property_type('username'),
471 'Username policy is defined in Moodle security config.', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
472 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
473 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
474 'suspended' => new external_value(core_user::get_property_type('suspended'),
475 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
476 'password' => new external_value(core_user::get_property_type('password'),
477 'Plain text password consisting of any characters', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
478 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user',
479 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
480 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user',
481 VALUE_OPTIONAL),
482 'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL,
483 '', NULL_NOT_ALLOWED),
484 'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email visibility', VALUE_OPTIONAL),
485 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
486 'country' => new external_value(core_user::get_property_type('country'),
487 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
488 'timezone' => new external_value(core_user::get_property_type('timezone'),
489 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
490 'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML',
491 VALUE_OPTIONAL),
492 // User picture.
493 'userpicture' => new external_value(PARAM_INT,
494 'The itemid where the new user picture has been uploaded to, 0 to delete', VALUE_OPTIONAL),
495 // Additional names.
496 'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'),
497 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
498 'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'),
499 'The family name phonetically of the user', VALUE_OPTIONAL),
500 'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user',
501 VALUE_OPTIONAL),
502 'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user',
503 VALUE_OPTIONAL),
504 // Interests.
505 'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL),
506 // Optional.
507 'idnumber' => new external_value(core_user::get_property_type('idnumber'),
508 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
509 'institution' => new external_value(core_user::get_property_type('institution'), 'Institution', VALUE_OPTIONAL),
510 'department' => new external_value(core_user::get_property_type('department'), 'Department', VALUE_OPTIONAL),
511 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone', VALUE_OPTIONAL),
512 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Mobile phone', VALUE_OPTIONAL),
513 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
514 // Other user preferences stored in the user table.
515 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
516 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
517 'calendartype' => new external_value(core_user::get_property_type('calendartype'),
518 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
519 'theme' => new external_value(core_user::get_property_type('theme'),
520 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
521 'mailformat' => new external_value(core_user::get_property_type('mailformat'),
522 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
523 // Custom user profile fields.
524 'customfields' => new external_multiple_structure(
525 new external_single_structure(
527 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
528 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
530 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
531 // User preferences.
532 'preferences' => new external_multiple_structure(
533 new external_single_structure(
535 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
536 'value' => new external_value(PARAM_RAW, 'The value of the preference')
538 ), 'User preferences', VALUE_OPTIONAL),
540 return new external_function_parameters(
542 'users' => new external_multiple_structure(
543 new external_single_structure($userfields)
550 * Update users
552 * @param array $users
553 * @return null
554 * @since Moodle 2.2
556 public static function update_users($users) {
557 global $CFG, $DB, $USER;
558 require_once($CFG->dirroot."/user/lib.php");
559 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
560 require_once($CFG->dirroot.'/user/editlib.php');
562 // Ensure the current user is allowed to run this function.
563 $context = context_system::instance();
564 require_capability('moodle/user:update', $context);
565 self::validate_context($context);
567 $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
569 $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
570 'subdirs' => 0,
571 'maxfiles' => 1,
572 'accepted_types' => 'optimised_image');
574 $warnings = array();
575 foreach ($params['users'] as $user) {
576 // Catch any exception while updating a user and return it as a warning.
577 try {
578 $transaction = $DB->start_delegated_transaction();
580 // First check the user exists.
581 if (!$existinguser = core_user::get_user($user['id'])) {
582 throw new moodle_exception('invaliduserid', '', '', null,
583 'Invalid user ID');
585 // Check if we are trying to update an admin.
586 if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
587 throw new moodle_exception('usernotupdatedadmin', '', '', null,
588 'Cannot update admin accounts');
590 // Other checks (deleted, remote or guest users).
591 if ($existinguser->deleted) {
592 throw new moodle_exception('usernotupdateddeleted', '', '', null,
593 'User is a deleted user');
595 if (is_mnet_remote_user($existinguser)) {
596 throw new moodle_exception('usernotupdatedremote', '', '', null,
597 'User is a remote user');
599 if (isguestuser($existinguser->id)) {
600 throw new moodle_exception('usernotupdatedguest', '', '', null,
601 'Cannot update guest account');
603 // Check duplicated emails.
604 if (isset($user['email']) && $user['email'] !== $existinguser->email) {
605 if (!validate_email($user['email'])) {
606 throw new moodle_exception('useremailinvalid', '', '', null,
607 'Invalid email address');
608 } else if (empty($CFG->allowaccountssameemail)) {
609 // Make a case-insensitive query for the given email address
610 // and make sure to exclude the user being updated.
611 $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid';
612 $params = array(
613 'email' => $user['email'],
614 'mnethostid' => $CFG->mnet_localhost_id,
615 'userid' => $user['id']
617 // Skip if there are other user(s) that already have the same email.
618 if ($DB->record_exists_select('user', $select, $params)) {
619 throw new moodle_exception('useremailduplicate', '', '', null,
620 'Duplicate email address');
625 user_update_user($user, true, false);
627 $userobject = (object)$user;
629 // Update user picture if it was specified for this user.
630 if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
631 $userobject->deletepicture = null;
633 if ($user['userpicture'] == 0) {
634 $userobject->deletepicture = true;
635 } else {
636 $userobject->imagefile = $user['userpicture'];
639 core_user::update_picture($userobject, $filemanageroptions);
642 // Update user interests.
643 if (!empty($user['interests'])) {
644 $trimmedinterests = array_map('trim', explode(',', $user['interests']));
645 $interests = array_filter($trimmedinterests, function($value) {
646 return !empty($value);
648 useredit_update_interests($userobject, $interests);
651 // Update user custom fields.
652 if (!empty($user['customfields'])) {
654 foreach ($user['customfields'] as $customfield) {
655 // Profile_save_data() saves profile file it's expecting a user with the correct id,
656 // and custom field to be named profile_field_"shortname".
657 $user["profile_field_".$customfield['type']] = $customfield['value'];
659 profile_save_data((object) $user);
662 // Trigger event.
663 \core\event\user_updated::create_from_userid($user['id'])->trigger();
665 // Preferences.
666 if (!empty($user['preferences'])) {
667 $userpref = clone($existinguser);
668 foreach ($user['preferences'] as $preference) {
669 $userpref->{'preference_'.$preference['type']} = $preference['value'];
671 useredit_update_user_preference($userpref);
673 if (isset($user['suspended']) and $user['suspended']) {
674 \core\session\manager::kill_user_sessions($user['id']);
677 $transaction->allow_commit();
678 } catch (Exception $e) {
679 try {
680 $transaction->rollback($e);
681 } catch (Exception $e) {
682 $warning = [];
683 $warning['item'] = 'user';
684 $warning['itemid'] = $user['id'];
685 if ($e instanceof moodle_exception) {
686 $warning['warningcode'] = $e->errorcode;
687 } else {
688 $warning['warningcode'] = $e->getCode();
690 $warning['message'] = $e->getMessage();
691 $warnings[] = $warning;
696 return ['warnings' => $warnings];
700 * Returns description of method result value
702 * @return external_description
703 * @since Moodle 2.2
705 public static function update_users_returns() {
706 return new external_single_structure(
707 array(
708 'warnings' => new external_warnings()
714 * Returns description of method parameters
716 * @return external_function_parameters
717 * @since Moodle 2.4
719 public static function get_users_by_field_parameters() {
720 return new external_function_parameters(
721 array(
722 'field' => new external_value(PARAM_ALPHA, 'the search field can be
723 \'id\' or \'idnumber\' or \'username\' or \'email\''),
724 'values' => new external_multiple_structure(
725 new external_value(PARAM_RAW, 'the value to match'))
731 * Get user information for a unique field.
733 * @throws coding_exception
734 * @throws invalid_parameter_exception
735 * @param string $field
736 * @param array $values
737 * @return array An array of arrays containg user profiles.
738 * @since Moodle 2.4
740 public static function get_users_by_field($field, $values) {
741 global $CFG, $USER, $DB;
742 require_once($CFG->dirroot . "/user/lib.php");
744 $params = self::validate_parameters(self::get_users_by_field_parameters(),
745 array('field' => $field, 'values' => $values));
747 // This array will keep all the users that are allowed to be searched,
748 // according to the current user's privileges.
749 $cleanedvalues = array();
751 switch ($field) {
752 case 'id':
753 $paramtype = core_user::get_property_type('id');
754 break;
755 case 'idnumber':
756 $paramtype = core_user::get_property_type('idnumber');
757 break;
758 case 'username':
759 $paramtype = core_user::get_property_type('username');
760 break;
761 case 'email':
762 $paramtype = core_user::get_property_type('email');
763 break;
764 default:
765 throw new coding_exception('invalid field parameter',
766 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
769 // Clean the values.
770 foreach ($values as $value) {
771 $cleanedvalue = clean_param($value, $paramtype);
772 if ( $value != $cleanedvalue) {
773 throw new invalid_parameter_exception('The field \'' . $field .
774 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
776 $cleanedvalues[] = $cleanedvalue;
779 // Retrieve the users.
780 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
782 $context = context_system::instance();
783 self::validate_context($context);
785 // Finally retrieve each users information.
786 $returnedusers = array();
787 foreach ($users as $user) {
788 $userdetails = user_get_user_details_courses($user);
790 // Return the user only if the searched field is returned.
791 // Otherwise it means that the $USER was not allowed to search the returned user.
792 if (!empty($userdetails) and !empty($userdetails[$field])) {
793 $returnedusers[] = $userdetails;
797 return $returnedusers;
801 * Returns description of method result value
803 * @return external_multiple_structure
804 * @since Moodle 2.4
806 public static function get_users_by_field_returns() {
807 return new external_multiple_structure(self::user_description());
812 * Returns description of get_users() parameters.
814 * @return external_function_parameters
815 * @since Moodle 2.5
817 public static function get_users_parameters() {
818 return new external_function_parameters(
819 array(
820 'criteria' => new external_multiple_structure(
821 new external_single_structure(
822 array(
823 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
824 "id" (int) matching user id,
825 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
826 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
827 "idnumber" (string) matching user idnumber,
828 "username" (string) matching user username,
829 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
830 "auth" (string) matching user auth plugin'),
831 'value' => new external_value(PARAM_RAW, 'the value to search')
833 ), 'the key/value pairs to be considered in user search. Values can not be empty.
834 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
835 key occurences are forbidden.
836 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
837 the search is still executed on the valid criterias.
838 You can search without criteria, but the function is not designed for it.
839 It could very slow or timeout. The function is designed to search some specific users.'
846 * Retrieve matching user.
848 * @throws moodle_exception
849 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
850 * @return array An array of arrays containing user profiles.
851 * @since Moodle 2.5
853 public static function get_users($criteria = array()) {
854 global $CFG, $USER, $DB;
856 require_once($CFG->dirroot . "/user/lib.php");
858 $params = self::validate_parameters(self::get_users_parameters(),
859 array('criteria' => $criteria));
861 // Validate the criteria and retrieve the users.
862 $users = array();
863 $warnings = array();
864 $sqlparams = array();
865 $usedkeys = array();
867 // Do not retrieve deleted users.
868 $sql = ' deleted = 0';
870 foreach ($params['criteria'] as $criteriaindex => $criteria) {
872 // Check that the criteria has never been used.
873 if (array_key_exists($criteria['key'], $usedkeys)) {
874 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
875 } else {
876 $usedkeys[$criteria['key']] = true;
879 $invalidcriteria = false;
880 // Clean the parameters.
881 $paramtype = PARAM_RAW;
882 switch ($criteria['key']) {
883 case 'id':
884 $paramtype = core_user::get_property_type('id');
885 break;
886 case 'idnumber':
887 $paramtype = core_user::get_property_type('idnumber');
888 break;
889 case 'username':
890 $paramtype = core_user::get_property_type('username');
891 break;
892 case 'email':
893 // We use PARAM_RAW to allow searches with %.
894 $paramtype = core_user::get_property_type('email');
895 break;
896 case 'auth':
897 $paramtype = core_user::get_property_type('auth');
898 break;
899 case 'lastname':
900 case 'firstname':
901 $paramtype = core_user::get_property_type('firstname');
902 break;
903 default:
904 // Send back a warning that this search key is not supported in this version.
905 // This warning will make the function extandable without breaking clients.
906 $warnings[] = array(
907 'item' => $criteria['key'],
908 'warningcode' => 'invalidfieldparameter',
909 'message' =>
910 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
912 // Do not add this invalid criteria to the created SQL request.
913 $invalidcriteria = true;
914 unset($params['criteria'][$criteriaindex]);
915 break;
918 if (!$invalidcriteria) {
919 $cleanedvalue = clean_param($criteria['value'], $paramtype);
921 $sql .= ' AND ';
923 // Create the SQL.
924 switch ($criteria['key']) {
925 case 'id':
926 case 'idnumber':
927 case 'username':
928 case 'auth':
929 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
930 $sqlparams[$criteria['key']] = $cleanedvalue;
931 break;
932 case 'email':
933 case 'lastname':
934 case 'firstname':
935 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
936 $sqlparams[$criteria['key']] = $cleanedvalue;
937 break;
938 default:
939 break;
944 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
946 // Finally retrieve each users information.
947 $returnedusers = array();
948 foreach ($users as $user) {
949 $userdetails = user_get_user_details_courses($user);
951 // Return the user only if all the searched fields are returned.
952 // Otherwise it means that the $USER was not allowed to search the returned user.
953 if (!empty($userdetails)) {
954 $validuser = true;
956 foreach ($params['criteria'] as $criteria) {
957 if (empty($userdetails[$criteria['key']])) {
958 $validuser = false;
962 if ($validuser) {
963 $returnedusers[] = $userdetails;
968 return array('users' => $returnedusers, 'warnings' => $warnings);
972 * Returns description of get_users result value.
974 * @return external_description
975 * @since Moodle 2.5
977 public static function get_users_returns() {
978 return new external_single_structure(
979 array('users' => new external_multiple_structure(
980 self::user_description()
982 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
988 * Returns description of method parameters
990 * @return external_function_parameters
991 * @since Moodle 2.2
993 public static function get_course_user_profiles_parameters() {
994 return new external_function_parameters(
995 array(
996 'userlist' => new external_multiple_structure(
997 new external_single_structure(
998 array(
999 'userid' => new external_value(core_user::get_property_type('id'), 'userid'),
1000 'courseid' => new external_value(PARAM_INT, 'courseid'),
1009 * Get course participant's details
1011 * @param array $userlist array of user ids and according course ids
1012 * @return array An array of arrays describing course participants
1013 * @since Moodle 2.2
1015 public static function get_course_user_profiles($userlist) {
1016 global $CFG, $USER, $DB;
1017 require_once($CFG->dirroot . "/user/lib.php");
1018 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
1020 $userids = array();
1021 $courseids = array();
1022 foreach ($params['userlist'] as $value) {
1023 $userids[] = $value['userid'];
1024 $courseids[$value['userid']] = $value['courseid'];
1027 // Cache all courses.
1028 $courses = array();
1029 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
1030 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1031 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1032 $params['contextlevel'] = CONTEXT_COURSE;
1033 $coursesql = "SELECT c.* $cselect
1034 FROM {course} c $cjoin
1035 WHERE c.id $sqlcourseids";
1036 $rs = $DB->get_recordset_sql($coursesql, $params);
1037 foreach ($rs as $course) {
1038 // Adding course contexts to cache.
1039 context_helper::preload_from_record($course);
1040 // Cache courses.
1041 $courses[$course->id] = $course;
1043 $rs->close();
1045 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
1046 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1047 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
1048 $params['contextlevel'] = CONTEXT_USER;
1049 $usersql = "SELECT u.* $uselect
1050 FROM {user} u $ujoin
1051 WHERE u.id $sqluserids";
1052 $users = $DB->get_recordset_sql($usersql, $params);
1053 $result = array();
1054 foreach ($users as $user) {
1055 if (!empty($user->deleted)) {
1056 continue;
1058 context_helper::preload_from_record($user);
1059 $course = $courses[$courseids[$user->id]];
1060 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
1061 self::validate_context($context);
1062 if ($userarray = user_get_user_details($user, $course)) {
1063 $result[] = $userarray;
1067 $users->close();
1069 return $result;
1073 * Returns description of method result value
1075 * @return external_description
1076 * @since Moodle 2.2
1078 public static function get_course_user_profiles_returns() {
1079 $additionalfields = array(
1080 'groups' => new external_multiple_structure(
1081 new external_single_structure(
1082 array(
1083 'id' => new external_value(PARAM_INT, 'group id'),
1084 'name' => new external_value(PARAM_RAW, 'group name'),
1085 'description' => new external_value(PARAM_RAW, 'group description'),
1086 'descriptionformat' => new external_format_value('description'),
1088 ), 'user groups', VALUE_OPTIONAL),
1089 'roles' => new external_multiple_structure(
1090 new external_single_structure(
1091 array(
1092 'roleid' => new external_value(PARAM_INT, 'role id'),
1093 'name' => new external_value(PARAM_RAW, 'role name'),
1094 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
1095 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
1097 ), 'user roles', VALUE_OPTIONAL),
1098 'enrolledcourses' => new external_multiple_structure(
1099 new external_single_structure(
1100 array(
1101 'id' => new external_value(PARAM_INT, 'Id of the course'),
1102 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
1103 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
1105 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
1108 return new external_multiple_structure(self::user_description($additionalfields));
1112 * Create user return value description.
1114 * @param array $additionalfields some additional field
1115 * @return single_structure_description
1117 public static function user_description($additionalfields = array()) {
1118 $userfields = array(
1119 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
1120 'username' => new external_value(core_user::get_property_type('username'), 'The username', VALUE_OPTIONAL),
1121 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL),
1122 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
1123 'fullname' => new external_value(core_user::get_property_type('firstname'), 'The fullname of the user'),
1124 'email' => new external_value(core_user::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
1125 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
1126 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
1127 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
1128 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
1129 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
1130 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
1131 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
1132 'firstaccess' => new external_value(core_user::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL),
1133 'lastaccess' => new external_value(core_user::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL),
1134 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL),
1135 '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),
1136 'confirmed' => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
1137 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
1138 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
1139 'theme' => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
1140 'timezone' => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
1141 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
1142 'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL),
1143 'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL),
1144 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
1145 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
1146 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
1147 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
1148 'customfields' => new external_multiple_structure(
1149 new external_single_structure(
1150 array(
1151 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
1152 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
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'),
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'),
1163 ), 'Users preferences', VALUE_OPTIONAL)
1165 if (!empty($additionalfields)) {
1166 $userfields = array_merge($userfields, $additionalfields);
1168 return new external_single_structure($userfields);
1172 * Returns description of method parameters
1174 * @return external_function_parameters
1175 * @since Moodle 2.6
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')
1186 * Copy files from a draft area to users private files area.
1188 * @throws invalid_parameter_exception
1189 * @param int $draftid Id of a draft area containing files.
1190 * @return array An array of warnings
1191 * @since Moodle 2.6
1193 public static function add_user_private_files($draftid) {
1194 global $CFG, $USER;
1195 require_once($CFG->libdir . "/filelib.php");
1197 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
1199 if (isguestuser()) {
1200 throw new invalid_parameter_exception('Guest users cannot upload files');
1203 $context = context_user::instance($USER->id);
1204 require_capability('moodle/user:manageownfiles', $context);
1206 $maxbytes = $CFG->userquota;
1207 $maxareabytes = $CFG->userquota;
1208 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1209 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1210 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1213 $options = array('subdirs' => 1,
1214 'maxbytes' => $maxbytes,
1215 'maxfiles' => -1,
1216 'areamaxbytes' => $maxareabytes);
1218 file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options);
1220 return null;
1224 * Returns description of method result value
1226 * @return external_description
1227 * @since Moodle 2.2
1229 public static function add_user_private_files_returns() {
1230 return null;
1234 * Returns description of method parameters.
1236 * @return external_function_parameters
1237 * @since Moodle 2.6
1239 public static function add_user_device_parameters() {
1240 return new external_function_parameters(
1241 array(
1242 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1243 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1244 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1245 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1246 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1247 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1248 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1254 * Add a user device in Moodle database (for PUSH notifications usually).
1256 * @throws moodle_exception
1257 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1258 * @param string $name The device name, occam or iPhone etc.
1259 * @param string $model The device model Nexus4 or iPad1.1 etc.
1260 * @param string $platform The device platform iOs or Android etc.
1261 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1262 * @param string $pushid The device PUSH token/key/identifier/registration id.
1263 * @param string $uuid The device UUID.
1264 * @return array List of possible warnings.
1265 * @since Moodle 2.6
1267 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1268 global $CFG, $USER, $DB;
1269 require_once($CFG->dirroot . "/user/lib.php");
1271 $params = self::validate_parameters(self::add_user_device_parameters(),
1272 array('appid' => $appid,
1273 'name' => $name,
1274 'model' => $model,
1275 'platform' => $platform,
1276 'version' => $version,
1277 'pushid' => $pushid,
1278 'uuid' => $uuid
1281 $warnings = array();
1283 // Prevent duplicate keys for users.
1284 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1285 $warnings['warning'][] = array(
1286 'item' => $params['pushid'],
1287 'warningcode' => 'existingkeyforthisuser',
1288 'message' => 'This key is already stored for this user'
1290 return $warnings;
1293 // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1294 // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1295 if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1296 'appid' => $params['appid'], 'userid' => $USER->id))) {
1298 foreach ($userdevices as $userdevice) {
1299 $userdevice->version = $params['version']; // Maybe the user upgraded the device.
1300 $userdevice->pushid = $params['pushid'];
1301 $userdevice->timemodified = time();
1302 $DB->update_record('user_devices', $userdevice);
1305 } else {
1306 $userdevice = new stdclass;
1307 $userdevice->userid = $USER->id;
1308 $userdevice->appid = $params['appid'];
1309 $userdevice->name = $params['name'];
1310 $userdevice->model = $params['model'];
1311 $userdevice->platform = $params['platform'];
1312 $userdevice->version = $params['version'];
1313 $userdevice->pushid = $params['pushid'];
1314 $userdevice->uuid = $params['uuid'];
1315 $userdevice->timecreated = time();
1316 $userdevice->timemodified = $userdevice->timecreated;
1318 if (!$DB->insert_record('user_devices', $userdevice)) {
1319 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1323 return $warnings;
1327 * Returns description of method result value.
1329 * @return external_multiple_structure
1330 * @since Moodle 2.6
1332 public static function add_user_device_returns() {
1333 return new external_multiple_structure(
1334 new external_warnings()
1339 * Returns description of method parameters.
1341 * @return external_function_parameters
1342 * @since Moodle 2.9
1344 public static function remove_user_device_parameters() {
1345 return new external_function_parameters(
1346 array(
1347 'uuid' => new external_value(PARAM_RAW, 'the device UUID'),
1348 'appid' => new external_value(PARAM_NOTAGS,
1349 'the app id, if empty devices matching the UUID for the user will be removed',
1350 VALUE_DEFAULT, ''),
1356 * Remove a user device from the Moodle database (for PUSH notifications usually).
1358 * @param string $uuid The device UUID.
1359 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1360 * @return array List of possible warnings and removal status.
1361 * @since Moodle 2.9
1363 public static function remove_user_device($uuid, $appid = "") {
1364 global $CFG;
1365 require_once($CFG->dirroot . "/user/lib.php");
1367 $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1369 $context = context_system::instance();
1370 self::validate_context($context);
1372 // Warnings array, it can be empty at the end but is mandatory.
1373 $warnings = array();
1375 $removed = user_remove_user_device($params['uuid'], $params['appid']);
1377 if (!$removed) {
1378 $warnings[] = array(
1379 'item' => $params['uuid'],
1380 'warningcode' => 'devicedoesnotexist',
1381 'message' => 'The device doesn\'t exists in the database'
1385 $result = array(
1386 'removed' => $removed,
1387 'warnings' => $warnings
1390 return $result;
1394 * Returns description of method result value.
1396 * @return external_multiple_structure
1397 * @since Moodle 2.9
1399 public static function remove_user_device_returns() {
1400 return new external_single_structure(
1401 array(
1402 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
1403 'warnings' => new external_warnings(),
1409 * Returns description of method parameters
1411 * @return external_function_parameters
1412 * @since Moodle 2.9
1414 public static function view_user_list_parameters() {
1415 return new external_function_parameters(
1416 array(
1417 'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site')
1423 * Trigger the user_list_viewed event.
1425 * @param int $courseid id of course
1426 * @return array of warnings and status result
1427 * @since Moodle 2.9
1428 * @throws moodle_exception
1430 public static function view_user_list($courseid) {
1431 global $CFG;
1432 require_once($CFG->dirroot . "/user/lib.php");
1433 require_once($CFG->dirroot . '/course/lib.php');
1435 $params = self::validate_parameters(self::view_user_list_parameters(),
1436 array(
1437 'courseid' => $courseid
1440 $warnings = array();
1442 if (empty($params['courseid'])) {
1443 $params['courseid'] = SITEID;
1446 $course = get_course($params['courseid']);
1448 if ($course->id == SITEID) {
1449 $context = context_system::instance();
1450 } else {
1451 $context = context_course::instance($course->id);
1453 self::validate_context($context);
1455 course_require_view_participants($context);
1457 user_list_view($course, $context);
1459 $result = array();
1460 $result['status'] = true;
1461 $result['warnings'] = $warnings;
1462 return $result;
1466 * Returns description of method result value
1468 * @return external_description
1469 * @since Moodle 2.9
1471 public static function view_user_list_returns() {
1472 return new external_single_structure(
1473 array(
1474 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1475 'warnings' => new external_warnings()
1481 * Returns description of method parameters
1483 * @return external_function_parameters
1484 * @since Moodle 2.9
1486 public static function view_user_profile_parameters() {
1487 return new external_function_parameters(
1488 array(
1489 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1490 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
1496 * Trigger the user profile viewed event.
1498 * @param int $userid id of user
1499 * @param int $courseid id of course
1500 * @return array of warnings and status result
1501 * @since Moodle 2.9
1502 * @throws moodle_exception
1504 public static function view_user_profile($userid, $courseid = 0) {
1505 global $CFG, $USER;
1506 require_once($CFG->dirroot . "/user/profile/lib.php");
1508 $params = self::validate_parameters(self::view_user_profile_parameters(),
1509 array(
1510 'userid' => $userid,
1511 'courseid' => $courseid
1514 $warnings = array();
1516 if (empty($params['userid'])) {
1517 $params['userid'] = $USER->id;
1520 if (empty($params['courseid'])) {
1521 $params['courseid'] = SITEID;
1524 $course = get_course($params['courseid']);
1525 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1526 core_user::require_active_user($user);
1528 if ($course->id == SITEID) {
1529 $coursecontext = context_system::instance();;
1530 } else {
1531 $coursecontext = context_course::instance($course->id);
1533 self::validate_context($coursecontext);
1535 $currentuser = $USER->id == $user->id;
1536 $usercontext = context_user::instance($user->id);
1538 if (!$currentuser and
1539 !has_capability('moodle/user:viewdetails', $coursecontext) and
1540 !has_capability('moodle/user:viewdetails', $usercontext)) {
1541 throw new moodle_exception('cannotviewprofile');
1544 // Case like user/profile.php.
1545 if ($course->id == SITEID) {
1546 profile_view($user, $usercontext);
1547 } else {
1548 // Case like user/view.php.
1549 if (!$currentuser and !can_access_course($course, $user, '', true)) {
1550 throw new moodle_exception('notenrolledprofile');
1553 profile_view($user, $coursecontext, $course);
1556 $result = array();
1557 $result['status'] = true;
1558 $result['warnings'] = $warnings;
1559 return $result;
1563 * Returns description of method result value
1565 * @return external_description
1566 * @since Moodle 2.9
1568 public static function view_user_profile_returns() {
1569 return new external_single_structure(
1570 array(
1571 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1572 'warnings' => new external_warnings()
1578 * Returns description of method parameters
1580 * @return external_function_parameters
1581 * @since Moodle 3.2
1583 public static function get_user_preferences_parameters() {
1584 return new external_function_parameters(
1585 array(
1586 'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''),
1587 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0)
1593 * Return user preferences.
1595 * @param string $name preference name, empty for all
1596 * @param int $userid id of the user, 0 for current user
1597 * @return array of warnings and preferences
1598 * @since Moodle 3.2
1599 * @throws moodle_exception
1601 public static function get_user_preferences($name = '', $userid = 0) {
1602 global $USER;
1604 $params = self::validate_parameters(self::get_user_preferences_parameters(),
1605 array(
1606 'name' => $name,
1607 'userid' => $userid
1609 $preferences = array();
1610 $warnings = array();
1612 $context = context_system::instance();
1613 self::validate_context($context);
1615 if (empty($params['name'])) {
1616 $name = null;
1618 if (empty($params['userid'])) {
1619 $user = null;
1620 } else {
1621 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1622 core_user::require_active_user($user);
1623 if ($user->id != $USER->id) {
1624 // Only admins can retrieve other users preferences.
1625 require_capability('moodle/site:config', $context);
1629 $userpreferences = get_user_preferences($name, null, $user);
1630 // Check if we received just one preference.
1631 if (!is_array($userpreferences)) {
1632 $userpreferences = array($name => $userpreferences);
1635 foreach ($userpreferences as $name => $value) {
1636 $preferences[] = array(
1637 'name' => $name,
1638 'value' => $value,
1642 $result = array();
1643 $result['preferences'] = $preferences;
1644 $result['warnings'] = $warnings;
1645 return $result;
1649 * Returns description of method result value
1651 * @return external_description
1652 * @since Moodle 3.2
1654 public static function get_user_preferences_returns() {
1655 return new external_single_structure(
1656 array(
1657 'preferences' => new external_multiple_structure(
1658 new external_single_structure(
1659 array(
1660 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1661 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1664 'User custom fields (also known as user profile fields)'
1666 'warnings' => new external_warnings()
1672 * Returns description of method parameters
1674 * @return external_function_parameters
1675 * @since Moodle 3.2
1677 public static function update_picture_parameters() {
1678 return new external_function_parameters(
1679 array(
1680 'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'),
1681 'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false),
1682 'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0)
1688 * Update or delete the user picture in the site
1690 * @param int $draftitemid id of the user draft file to use as image
1691 * @param bool $delete if we should delete the user picture
1692 * @param int $userid id of the user, 0 for current user
1693 * @return array warnings and success status
1694 * @since Moodle 3.2
1695 * @throws moodle_exception
1697 public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1698 global $CFG, $USER, $PAGE;
1700 $params = self::validate_parameters(
1701 self::update_picture_parameters(),
1702 array(
1703 'draftitemid' => $draftitemid,
1704 'delete' => $delete,
1705 'userid' => $userid
1709 $context = context_system::instance();
1710 self::validate_context($context);
1712 if (!empty($CFG->disableuserimages)) {
1713 throw new moodle_exception('userimagesdisabled', 'admin');
1716 if (empty($params['userid']) or $params['userid'] == $USER->id) {
1717 $user = $USER;
1718 require_capability('moodle/user:editownprofile', $context);
1719 } else {
1720 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1721 core_user::require_active_user($user);
1722 $personalcontext = context_user::instance($user->id);
1724 require_capability('moodle/user:editprofile', $personalcontext);
1725 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
1726 throw new moodle_exception('useradmineditadmin');
1730 // Load the appropriate auth plugin.
1731 $userauth = get_auth_plugin($user->auth);
1732 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1733 throw new moodle_exception('noprofileedit', 'auth');
1736 $filemanageroptions = array(
1737 'maxbytes' => $CFG->maxbytes,
1738 'subdirs' => 0,
1739 'maxfiles' => 1,
1740 'accepted_types' => 'optimised_image'
1742 $user->deletepicture = $params['delete'];
1743 $user->imagefile = $params['draftitemid'];
1744 $success = core_user::update_picture($user, $filemanageroptions);
1746 $result = array(
1747 'success' => $success,
1748 'warnings' => array(),
1750 if ($success) {
1751 $userpicture = new user_picture(core_user::get_user($user->id));
1752 $userpicture->size = 1; // Size f1.
1753 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1755 return $result;
1759 * Returns description of method result value
1761 * @return external_description
1762 * @since Moodle 3.2
1764 public static function update_picture_returns() {
1765 return new external_single_structure(
1766 array(
1767 'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'),
1768 'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL),
1769 'warnings' => new external_warnings()
1775 * Returns description of method parameters
1777 * @return external_function_parameters
1778 * @since Moodle 3.2
1780 public static function set_user_preferences_parameters() {
1781 return new external_function_parameters(
1782 array(
1783 'preferences' => new external_multiple_structure(
1784 new external_single_structure(
1785 array(
1786 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1787 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1788 'userid' => new external_value(PARAM_INT, 'Id of the user to set the preference'),
1797 * Set user preferences.
1799 * @param array $preferences list of preferences including name, value and userid
1800 * @return array of warnings and preferences saved
1801 * @since Moodle 3.2
1802 * @throws moodle_exception
1804 public static function set_user_preferences($preferences) {
1805 global $USER;
1807 $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
1808 $warnings = array();
1809 $saved = array();
1811 $context = context_system::instance();
1812 self::validate_context($context);
1814 $userscache = array();
1815 foreach ($params['preferences'] as $pref) {
1816 // Check to which user set the preference.
1817 if (!empty($userscache[$pref['userid']])) {
1818 $user = $userscache[$pref['userid']];
1819 } else {
1820 try {
1821 $user = core_user::get_user($pref['userid'], '*', MUST_EXIST);
1822 core_user::require_active_user($user);
1823 $userscache[$pref['userid']] = $user;
1824 } catch (Exception $e) {
1825 $warnings[] = array(
1826 'item' => 'user',
1827 'itemid' => $pref['userid'],
1828 'warningcode' => 'invaliduser',
1829 'message' => $e->getMessage()
1831 continue;
1835 try {
1836 if (core_user::can_edit_preference($pref['name'], $user)) {
1837 $value = core_user::clean_preference($pref['value'], $pref['name']);
1838 set_user_preference($pref['name'], $value, $user->id);
1839 $saved[] = array(
1840 'name' => $pref['name'],
1841 'userid' => $user->id,
1843 } else {
1844 $warnings[] = array(
1845 'item' => 'user',
1846 'itemid' => $user->id,
1847 'warningcode' => 'nopermission',
1848 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id
1851 } catch (Exception $e) {
1852 $warnings[] = array(
1853 'item' => 'user',
1854 'itemid' => $user->id,
1855 'warningcode' => 'errorsavingpreference',
1856 'message' => $e->getMessage()
1861 $result = array();
1862 $result['saved'] = $saved;
1863 $result['warnings'] = $warnings;
1864 return $result;
1868 * Returns description of method result value
1870 * @return external_description
1871 * @since Moodle 3.2
1873 public static function set_user_preferences_returns() {
1874 return new external_single_structure(
1875 array(
1876 'saved' => new external_multiple_structure(
1877 new external_single_structure(
1878 array(
1879 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1880 'userid' => new external_value(PARAM_INT, 'The user the preference was set for'),
1882 ), 'Preferences saved'
1884 'warnings' => new external_warnings()
1890 * Returns description of method parameters.
1892 * @return external_function_parameters
1893 * @since Moodle 3.2
1895 public static function agree_site_policy_parameters() {
1896 return new external_function_parameters(array());
1900 * Agree the site policy for the current user.
1902 * @return array of warnings and status result
1903 * @since Moodle 3.2
1904 * @throws moodle_exception
1906 public static function agree_site_policy() {
1907 global $CFG, $DB, $USER;
1909 $warnings = array();
1911 $context = context_system::instance();
1912 try {
1913 // We expect an exception here since the user didn't agree the site policy yet.
1914 self::validate_context($context);
1915 } catch (Exception $e) {
1916 // We are expecting only a sitepolicynotagreed exception.
1917 if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
1918 // In case we receive a different exception, throw it.
1919 throw $e;
1923 $manager = new \core_privacy\local\sitepolicy\manager();
1924 if (!empty($USER->policyagreed)) {
1925 $status = false;
1926 $warnings[] = array(
1927 'item' => 'user',
1928 'itemid' => $USER->id,
1929 'warningcode' => 'alreadyagreed',
1930 'message' => 'The user already agreed the site policy.'
1932 } else if (!$manager->is_defined()) {
1933 $status = false;
1934 $warnings[] = array(
1935 'item' => 'user',
1936 'itemid' => $USER->id,
1937 'warningcode' => 'nositepolicy',
1938 'message' => 'The site does not have a site policy configured.'
1940 } else {
1941 $status = $manager->accept();
1944 $result = array();
1945 $result['status'] = $status;
1946 $result['warnings'] = $warnings;
1947 return $result;
1951 * Returns description of method result value.
1953 * @return external_description
1954 * @since Moodle 3.2
1956 public static function agree_site_policy_returns() {
1957 return new external_single_structure(
1958 array(
1959 'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'),
1960 'warnings' => new external_warnings()
1966 * Returns description of method parameters.
1968 * @return external_function_parameters
1969 * @since Moodle 3.4
1971 public static function get_private_files_info_parameters() {
1972 return new external_function_parameters(
1973 array(
1974 'userid' => new external_value(PARAM_INT, 'Id of the user, default to current user.', VALUE_DEFAULT, 0)
1980 * Returns general information about files in the user private files area.
1982 * @param int $userid Id of the user, default to current user.
1983 * @return array of warnings and file area information
1984 * @since Moodle 3.4
1985 * @throws moodle_exception
1987 public static function get_private_files_info($userid = 0) {
1988 global $CFG, $USER;
1989 require_once($CFG->libdir . '/filelib.php');
1991 $params = self::validate_parameters(self::get_private_files_info_parameters(), array('userid' => $userid));
1992 $warnings = array();
1994 $context = context_system::instance();
1995 self::validate_context($context);
1997 if (empty($params['userid']) || $params['userid'] == $USER->id) {
1998 $usercontext = context_user::instance($USER->id);
1999 require_capability('moodle/user:manageownfiles', $usercontext);
2000 } else {
2001 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2002 core_user::require_active_user($user);
2003 // Only admins can retrieve other users information.
2004 require_capability('moodle/site:config', $context);
2005 $usercontext = context_user::instance($user->id);
2008 $fileareainfo = file_get_file_area_info($usercontext->id, 'user', 'private');
2010 $result = array();
2011 $result['filecount'] = $fileareainfo['filecount'];
2012 $result['foldercount'] = $fileareainfo['foldercount'];
2013 $result['filesize'] = $fileareainfo['filesize'];
2014 $result['filesizewithoutreferences'] = $fileareainfo['filesize_without_references'];
2015 $result['warnings'] = $warnings;
2016 return $result;
2020 * Returns description of method result value.
2022 * @return external_description
2023 * @since Moodle 3.4
2025 public static function get_private_files_info_returns() {
2026 return new external_single_structure(
2027 array(
2028 'filecount' => new external_value(PARAM_INT, 'Number of files in the area.'),
2029 'foldercount' => new external_value(PARAM_INT, 'Number of folders in the area.'),
2030 'filesize' => new external_value(PARAM_INT, 'Total size of the files in the area.'),
2031 'filesizewithoutreferences' => new external_value(PARAM_INT, 'Total size of the area excluding file references'),
2032 'warnings' => new external_warnings()