MDL-73358 report: Add page content heading for report pages
[moodle.git] / user / externallib.php
blob0f402dfa9a07daa288e631fff9624ea6da3e643e
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) {
418 $userpref['preference_' . $preference['type']] = $preference['value'];
420 useredit_update_user_preference($userpref);
423 // Check if they want to update the email.
424 if ($emailstop !== null) {
425 $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST);
426 core_user::require_active_user($otheruser);
427 if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) {
428 $user = new stdClass();
429 $user->id = $userid;
430 $user->emailstop = $emailstop;
431 user_update_user($user);
433 // Update the $USER if we should.
434 if ($userid == $USER->id) {
435 $USER->emailstop = $emailstop;
440 return null;
444 * Returns description of method result value
446 * @return null
447 * @since Moodle 3.2
449 public static function update_user_preferences_returns() {
450 return null;
454 * Returns description of method parameters
456 * @return external_function_parameters
457 * @since Moodle 2.2
459 public static function update_users_parameters() {
460 $userfields = [
461 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
462 // General.
463 'username' => new external_value(core_user::get_property_type('username'),
464 'Username policy is defined in Moodle security config.', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
465 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
466 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
467 'suspended' => new external_value(core_user::get_property_type('suspended'),
468 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
469 'password' => new external_value(core_user::get_property_type('password'),
470 'Plain text password consisting of any characters', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
471 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user',
472 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
473 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user',
474 VALUE_OPTIONAL),
475 'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL,
476 '', NULL_NOT_ALLOWED),
477 'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email display', VALUE_OPTIONAL),
478 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
479 'country' => new external_value(core_user::get_property_type('country'),
480 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
481 'timezone' => new external_value(core_user::get_property_type('timezone'),
482 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
483 'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML',
484 VALUE_OPTIONAL),
485 // User picture.
486 'userpicture' => new external_value(PARAM_INT,
487 'The itemid where the new user picture has been uploaded to, 0 to delete', VALUE_OPTIONAL),
488 // Additional names.
489 'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'),
490 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
491 'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'),
492 'The family name phonetically of the user', VALUE_OPTIONAL),
493 'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user',
494 VALUE_OPTIONAL),
495 'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user',
496 VALUE_OPTIONAL),
497 // Interests.
498 'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL),
499 // Optional.
500 'idnumber' => new external_value(core_user::get_property_type('idnumber'),
501 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
502 'institution' => new external_value(core_user::get_property_type('institution'), 'Institution', VALUE_OPTIONAL),
503 'department' => new external_value(core_user::get_property_type('department'), 'Department', VALUE_OPTIONAL),
504 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone', VALUE_OPTIONAL),
505 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Mobile phone', VALUE_OPTIONAL),
506 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
507 // Other user preferences stored in the user table.
508 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
509 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
510 'calendartype' => new external_value(core_user::get_property_type('calendartype'),
511 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
512 'theme' => new external_value(core_user::get_property_type('theme'),
513 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
514 'mailformat' => new external_value(core_user::get_property_type('mailformat'),
515 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
516 // Custom user profile fields.
517 'customfields' => new external_multiple_structure(
518 new external_single_structure(
520 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
521 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
523 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
524 // User preferences.
525 'preferences' => new external_multiple_structure(
526 new external_single_structure(
528 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
529 'value' => new external_value(PARAM_RAW, 'The value of the preference')
531 ), 'User preferences', VALUE_OPTIONAL),
533 return new external_function_parameters(
535 'users' => new external_multiple_structure(
536 new external_single_structure($userfields)
543 * Update users
545 * @param array $users
546 * @return null
547 * @since Moodle 2.2
549 public static function update_users($users) {
550 global $CFG, $DB, $USER;
551 require_once($CFG->dirroot."/user/lib.php");
552 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
553 require_once($CFG->dirroot.'/user/editlib.php');
555 // Ensure the current user is allowed to run this function.
556 $context = context_system::instance();
557 require_capability('moodle/user:update', $context);
558 self::validate_context($context);
560 $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
562 $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
563 'subdirs' => 0,
564 'maxfiles' => 1,
565 'accepted_types' => 'optimised_image');
567 $warnings = array();
568 foreach ($params['users'] as $user) {
569 // Catch any exception while updating a user and return it as a warning.
570 try {
571 $transaction = $DB->start_delegated_transaction();
573 // First check the user exists.
574 if (!$existinguser = core_user::get_user($user['id'])) {
575 throw new moodle_exception('invaliduserid', '', '', null,
576 'Invalid user ID');
578 // Check if we are trying to update an admin.
579 if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
580 throw new moodle_exception('usernotupdatedadmin', '', '', null,
581 'Cannot update admin accounts');
583 // Other checks (deleted, remote or guest users).
584 if ($existinguser->deleted) {
585 throw new moodle_exception('usernotupdateddeleted', '', '', null,
586 'User is a deleted user');
588 if (is_mnet_remote_user($existinguser)) {
589 throw new moodle_exception('usernotupdatedremote', '', '', null,
590 'User is a remote user');
592 if (isguestuser($existinguser->id)) {
593 throw new moodle_exception('usernotupdatedguest', '', '', null,
594 'Cannot update guest account');
596 // Check duplicated emails.
597 if (isset($user['email']) && $user['email'] !== $existinguser->email) {
598 if (!validate_email($user['email'])) {
599 throw new moodle_exception('useremailinvalid', '', '', null,
600 'Invalid email address');
601 } else if (empty($CFG->allowaccountssameemail)) {
602 // Make a case-insensitive query for the given email address
603 // and make sure to exclude the user being updated.
604 $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid';
605 $params = array(
606 'email' => $user['email'],
607 'mnethostid' => $CFG->mnet_localhost_id,
608 'userid' => $user['id']
610 // Skip if there are other user(s) that already have the same email.
611 if ($DB->record_exists_select('user', $select, $params)) {
612 throw new moodle_exception('useremailduplicate', '', '', null,
613 'Duplicate email address');
618 user_update_user($user, true, false);
620 $userobject = (object)$user;
622 // Update user picture if it was specified for this user.
623 if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
624 $userobject->deletepicture = null;
626 if ($user['userpicture'] == 0) {
627 $userobject->deletepicture = true;
628 } else {
629 $userobject->imagefile = $user['userpicture'];
632 core_user::update_picture($userobject, $filemanageroptions);
635 // Update user interests.
636 if (!empty($user['interests'])) {
637 $trimmedinterests = array_map('trim', explode(',', $user['interests']));
638 $interests = array_filter($trimmedinterests, function($value) {
639 return !empty($value);
641 useredit_update_interests($userobject, $interests);
644 // Update user custom fields.
645 if (!empty($user['customfields'])) {
647 foreach ($user['customfields'] as $customfield) {
648 // Profile_save_data() saves profile file it's expecting a user with the correct id,
649 // and custom field to be named profile_field_"shortname".
650 $user["profile_field_".$customfield['type']] = $customfield['value'];
652 profile_save_data((object) $user);
655 // Trigger event.
656 \core\event\user_updated::create_from_userid($user['id'])->trigger();
658 // Preferences.
659 if (!empty($user['preferences'])) {
660 $userpref = clone($existinguser);
661 foreach ($user['preferences'] as $preference) {
662 $userpref->{'preference_'.$preference['type']} = $preference['value'];
664 useredit_update_user_preference($userpref);
666 if (isset($user['suspended']) and $user['suspended']) {
667 \core\session\manager::kill_user_sessions($user['id']);
670 $transaction->allow_commit();
671 } catch (Exception $e) {
672 try {
673 $transaction->rollback($e);
674 } catch (Exception $e) {
675 $warning = [];
676 $warning['item'] = 'user';
677 $warning['itemid'] = $user['id'];
678 if ($e instanceof moodle_exception) {
679 $warning['warningcode'] = $e->errorcode;
680 } else {
681 $warning['warningcode'] = $e->getCode();
683 $warning['message'] = $e->getMessage();
684 $warnings[] = $warning;
689 return ['warnings' => $warnings];
693 * Returns description of method result value
695 * @return external_description
696 * @since Moodle 2.2
698 public static function update_users_returns() {
699 return new external_single_structure(
700 array(
701 'warnings' => new external_warnings()
707 * Returns description of method parameters
709 * @return external_function_parameters
710 * @since Moodle 2.4
712 public static function get_users_by_field_parameters() {
713 return new external_function_parameters(
714 array(
715 'field' => new external_value(PARAM_ALPHA, 'the search field can be
716 \'id\' or \'idnumber\' or \'username\' or \'email\''),
717 'values' => new external_multiple_structure(
718 new external_value(PARAM_RAW, 'the value to match'))
724 * Get user information for a unique field.
726 * @throws coding_exception
727 * @throws invalid_parameter_exception
728 * @param string $field
729 * @param array $values
730 * @return array An array of arrays containg user profiles.
731 * @since Moodle 2.4
733 public static function get_users_by_field($field, $values) {
734 global $CFG, $USER, $DB;
735 require_once($CFG->dirroot . "/user/lib.php");
737 $params = self::validate_parameters(self::get_users_by_field_parameters(),
738 array('field' => $field, 'values' => $values));
740 // This array will keep all the users that are allowed to be searched,
741 // according to the current user's privileges.
742 $cleanedvalues = array();
744 switch ($field) {
745 case 'id':
746 $paramtype = core_user::get_property_type('id');
747 break;
748 case 'idnumber':
749 $paramtype = core_user::get_property_type('idnumber');
750 break;
751 case 'username':
752 $paramtype = core_user::get_property_type('username');
753 break;
754 case 'email':
755 $paramtype = core_user::get_property_type('email');
756 break;
757 default:
758 throw new coding_exception('invalid field parameter',
759 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
762 // Clean the values.
763 foreach ($values as $value) {
764 $cleanedvalue = clean_param($value, $paramtype);
765 if ( $value != $cleanedvalue) {
766 throw new invalid_parameter_exception('The field \'' . $field .
767 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
769 $cleanedvalues[] = $cleanedvalue;
772 // Retrieve the users.
773 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
775 $context = context_system::instance();
776 self::validate_context($context);
778 // Finally retrieve each users information.
779 $returnedusers = array();
780 foreach ($users as $user) {
781 $userdetails = user_get_user_details_courses($user);
783 // Return the user only if the searched field is returned.
784 // Otherwise it means that the $USER was not allowed to search the returned user.
785 if (!empty($userdetails) and !empty($userdetails[$field])) {
786 $returnedusers[] = $userdetails;
790 return $returnedusers;
794 * Returns description of method result value
796 * @return external_multiple_structure
797 * @since Moodle 2.4
799 public static function get_users_by_field_returns() {
800 return new external_multiple_structure(self::user_description());
805 * Returns description of get_users() parameters.
807 * @return external_function_parameters
808 * @since Moodle 2.5
810 public static function get_users_parameters() {
811 return new external_function_parameters(
812 array(
813 'criteria' => new external_multiple_structure(
814 new external_single_structure(
815 array(
816 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
817 "id" (int) matching user id,
818 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
819 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
820 "idnumber" (string) matching user idnumber,
821 "username" (string) matching user username,
822 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
823 "auth" (string) matching user auth plugin'),
824 'value' => new external_value(PARAM_RAW, 'the value to search')
826 ), 'the key/value pairs to be considered in user search. Values can not be empty.
827 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
828 key occurences are forbidden.
829 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
830 the search is still executed on the valid criterias.
831 You can search without criteria, but the function is not designed for it.
832 It could very slow or timeout. The function is designed to search some specific users.'
839 * Retrieve matching user.
841 * @throws moodle_exception
842 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
843 * @return array An array of arrays containing user profiles.
844 * @since Moodle 2.5
846 public static function get_users($criteria = array()) {
847 global $CFG, $USER, $DB;
849 require_once($CFG->dirroot . "/user/lib.php");
851 $params = self::validate_parameters(self::get_users_parameters(),
852 array('criteria' => $criteria));
854 // Validate the criteria and retrieve the users.
855 $users = array();
856 $warnings = array();
857 $sqlparams = array();
858 $usedkeys = array();
860 // Do not retrieve deleted users.
861 $sql = ' deleted = 0';
863 foreach ($params['criteria'] as $criteriaindex => $criteria) {
865 // Check that the criteria has never been used.
866 if (array_key_exists($criteria['key'], $usedkeys)) {
867 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
868 } else {
869 $usedkeys[$criteria['key']] = true;
872 $invalidcriteria = false;
873 // Clean the parameters.
874 $paramtype = PARAM_RAW;
875 switch ($criteria['key']) {
876 case 'id':
877 $paramtype = core_user::get_property_type('id');
878 break;
879 case 'idnumber':
880 $paramtype = core_user::get_property_type('idnumber');
881 break;
882 case 'username':
883 $paramtype = core_user::get_property_type('username');
884 break;
885 case 'email':
886 // We use PARAM_RAW to allow searches with %.
887 $paramtype = core_user::get_property_type('email');
888 break;
889 case 'auth':
890 $paramtype = core_user::get_property_type('auth');
891 break;
892 case 'lastname':
893 case 'firstname':
894 $paramtype = core_user::get_property_type('firstname');
895 break;
896 default:
897 // Send back a warning that this search key is not supported in this version.
898 // This warning will make the function extandable without breaking clients.
899 $warnings[] = array(
900 'item' => $criteria['key'],
901 'warningcode' => 'invalidfieldparameter',
902 'message' =>
903 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
905 // Do not add this invalid criteria to the created SQL request.
906 $invalidcriteria = true;
907 unset($params['criteria'][$criteriaindex]);
908 break;
911 if (!$invalidcriteria) {
912 $cleanedvalue = clean_param($criteria['value'], $paramtype);
914 $sql .= ' AND ';
916 // Create the SQL.
917 switch ($criteria['key']) {
918 case 'id':
919 case 'idnumber':
920 case 'username':
921 case 'auth':
922 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
923 $sqlparams[$criteria['key']] = $cleanedvalue;
924 break;
925 case 'email':
926 case 'lastname':
927 case 'firstname':
928 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
929 $sqlparams[$criteria['key']] = $cleanedvalue;
930 break;
931 default:
932 break;
937 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
939 // Finally retrieve each users information.
940 $returnedusers = array();
941 foreach ($users as $user) {
942 $userdetails = user_get_user_details_courses($user);
944 // Return the user only if all the searched fields are returned.
945 // Otherwise it means that the $USER was not allowed to search the returned user.
946 if (!empty($userdetails)) {
947 $validuser = true;
949 foreach ($params['criteria'] as $criteria) {
950 if (empty($userdetails[$criteria['key']])) {
951 $validuser = false;
955 if ($validuser) {
956 $returnedusers[] = $userdetails;
961 return array('users' => $returnedusers, 'warnings' => $warnings);
965 * Returns description of get_users result value.
967 * @return external_description
968 * @since Moodle 2.5
970 public static function get_users_returns() {
971 return new external_single_structure(
972 array('users' => new external_multiple_structure(
973 self::user_description()
975 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
981 * Returns description of method parameters
983 * @return external_function_parameters
984 * @since Moodle 2.2
986 public static function get_course_user_profiles_parameters() {
987 return new external_function_parameters(
988 array(
989 'userlist' => new external_multiple_structure(
990 new external_single_structure(
991 array(
992 'userid' => new external_value(core_user::get_property_type('id'), 'userid'),
993 'courseid' => new external_value(PARAM_INT, 'courseid'),
1002 * Get course participant's details
1004 * @param array $userlist array of user ids and according course ids
1005 * @return array An array of arrays describing course participants
1006 * @since Moodle 2.2
1008 public static function get_course_user_profiles($userlist) {
1009 global $CFG, $USER, $DB;
1010 require_once($CFG->dirroot . "/user/lib.php");
1011 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
1013 $userids = array();
1014 $courseids = array();
1015 foreach ($params['userlist'] as $value) {
1016 $userids[] = $value['userid'];
1017 $courseids[$value['userid']] = $value['courseid'];
1020 // Cache all courses.
1021 $courses = array();
1022 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
1023 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1024 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1025 $params['contextlevel'] = CONTEXT_COURSE;
1026 $coursesql = "SELECT c.* $cselect
1027 FROM {course} c $cjoin
1028 WHERE c.id $sqlcourseids";
1029 $rs = $DB->get_recordset_sql($coursesql, $params);
1030 foreach ($rs as $course) {
1031 // Adding course contexts to cache.
1032 context_helper::preload_from_record($course);
1033 // Cache courses.
1034 $courses[$course->id] = $course;
1036 $rs->close();
1038 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
1039 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1040 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
1041 $params['contextlevel'] = CONTEXT_USER;
1042 $usersql = "SELECT u.* $uselect
1043 FROM {user} u $ujoin
1044 WHERE u.id $sqluserids";
1045 $users = $DB->get_recordset_sql($usersql, $params);
1046 $result = array();
1047 foreach ($users as $user) {
1048 if (!empty($user->deleted)) {
1049 continue;
1051 context_helper::preload_from_record($user);
1052 $course = $courses[$courseids[$user->id]];
1053 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
1054 self::validate_context($context);
1055 if ($userarray = user_get_user_details($user, $course)) {
1056 $result[] = $userarray;
1060 $users->close();
1062 return $result;
1066 * Returns description of method result value
1068 * @return external_description
1069 * @since Moodle 2.2
1071 public static function get_course_user_profiles_returns() {
1072 $additionalfields = array(
1073 'groups' => new external_multiple_structure(
1074 new external_single_structure(
1075 array(
1076 'id' => new external_value(PARAM_INT, 'group id'),
1077 'name' => new external_value(PARAM_RAW, 'group name'),
1078 'description' => new external_value(PARAM_RAW, 'group description'),
1079 'descriptionformat' => new external_format_value('description'),
1081 ), 'user groups', VALUE_OPTIONAL),
1082 'roles' => new external_multiple_structure(
1083 new external_single_structure(
1084 array(
1085 'roleid' => new external_value(PARAM_INT, 'role id'),
1086 'name' => new external_value(PARAM_RAW, 'role name'),
1087 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
1088 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
1090 ), 'user roles', VALUE_OPTIONAL),
1091 'enrolledcourses' => new external_multiple_structure(
1092 new external_single_structure(
1093 array(
1094 'id' => new external_value(PARAM_INT, 'Id of the course'),
1095 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
1096 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
1098 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
1101 return new external_multiple_structure(self::user_description($additionalfields));
1105 * Create user return value description.
1107 * @param array $additionalfields some additional field
1108 * @return single_structure_description
1110 public static function user_description($additionalfields = array()) {
1111 $userfields = array(
1112 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
1113 'username' => new external_value(core_user::get_property_type('username'), 'The username', VALUE_OPTIONAL),
1114 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL),
1115 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
1116 'fullname' => new external_value(core_user::get_property_type('firstname'), 'The fullname of the user'),
1117 'email' => new external_value(core_user::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
1118 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
1119 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
1120 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
1121 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
1122 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
1123 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
1124 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
1125 'firstaccess' => new external_value(core_user::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL),
1126 'lastaccess' => new external_value(core_user::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL),
1127 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL),
1128 '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),
1129 'confirmed' => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
1130 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
1131 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
1132 'theme' => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
1133 'timezone' => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
1134 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
1135 'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL),
1136 'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL),
1137 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
1138 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
1139 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
1140 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
1141 'customfields' => new external_multiple_structure(
1142 new external_single_structure(
1143 array(
1144 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
1145 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
1146 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
1147 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
1149 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
1150 'preferences' => new external_multiple_structure(
1151 new external_single_structure(
1152 array(
1153 'name' => new external_value(PARAM_RAW, 'The name of the preferences'),
1154 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1156 ), 'Users preferences', VALUE_OPTIONAL)
1158 if (!empty($additionalfields)) {
1159 $userfields = array_merge($userfields, $additionalfields);
1161 return new external_single_structure($userfields);
1165 * Returns description of method parameters
1167 * @return external_function_parameters
1168 * @since Moodle 2.6
1170 public static function add_user_private_files_parameters() {
1171 return new external_function_parameters(
1172 array(
1173 'draftid' => new external_value(PARAM_INT, 'draft area id')
1179 * Copy files from a draft area to users private files area.
1181 * @throws invalid_parameter_exception
1182 * @param int $draftid Id of a draft area containing files.
1183 * @return array An array of warnings
1184 * @since Moodle 2.6
1186 public static function add_user_private_files($draftid) {
1187 global $CFG, $USER;
1188 require_once($CFG->libdir . "/filelib.php");
1190 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
1192 if (isguestuser()) {
1193 throw new invalid_parameter_exception('Guest users cannot upload files');
1196 $context = context_user::instance($USER->id);
1197 require_capability('moodle/user:manageownfiles', $context);
1199 $maxbytes = $CFG->userquota;
1200 $maxareabytes = $CFG->userquota;
1201 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1202 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1203 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1206 $options = array('subdirs' => 1,
1207 'maxbytes' => $maxbytes,
1208 'maxfiles' => -1,
1209 'areamaxbytes' => $maxareabytes);
1211 file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options);
1213 return null;
1217 * Returns description of method result value
1219 * @return external_description
1220 * @since Moodle 2.2
1222 public static function add_user_private_files_returns() {
1223 return null;
1227 * Returns description of method parameters.
1229 * @return external_function_parameters
1230 * @since Moodle 2.6
1232 public static function add_user_device_parameters() {
1233 return new external_function_parameters(
1234 array(
1235 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1236 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1237 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1238 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1239 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1240 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1241 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1247 * Add a user device in Moodle database (for PUSH notifications usually).
1249 * @throws moodle_exception
1250 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1251 * @param string $name The device name, occam or iPhone etc.
1252 * @param string $model The device model Nexus4 or iPad1.1 etc.
1253 * @param string $platform The device platform iOs or Android etc.
1254 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1255 * @param string $pushid The device PUSH token/key/identifier/registration id.
1256 * @param string $uuid The device UUID.
1257 * @return array List of possible warnings.
1258 * @since Moodle 2.6
1260 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1261 global $CFG, $USER, $DB;
1262 require_once($CFG->dirroot . "/user/lib.php");
1264 $params = self::validate_parameters(self::add_user_device_parameters(),
1265 array('appid' => $appid,
1266 'name' => $name,
1267 'model' => $model,
1268 'platform' => $platform,
1269 'version' => $version,
1270 'pushid' => $pushid,
1271 'uuid' => $uuid
1274 $warnings = array();
1276 // Prevent duplicate keys for users.
1277 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1278 $warnings['warning'][] = array(
1279 'item' => $params['pushid'],
1280 'warningcode' => 'existingkeyforthisuser',
1281 'message' => 'This key is already stored for this user'
1283 return $warnings;
1286 // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1287 // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1288 if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1289 'appid' => $params['appid'], 'userid' => $USER->id))) {
1291 foreach ($userdevices as $userdevice) {
1292 $userdevice->version = $params['version']; // Maybe the user upgraded the device.
1293 $userdevice->pushid = $params['pushid'];
1294 $userdevice->timemodified = time();
1295 $DB->update_record('user_devices', $userdevice);
1298 } else {
1299 $userdevice = new stdclass;
1300 $userdevice->userid = $USER->id;
1301 $userdevice->appid = $params['appid'];
1302 $userdevice->name = $params['name'];
1303 $userdevice->model = $params['model'];
1304 $userdevice->platform = $params['platform'];
1305 $userdevice->version = $params['version'];
1306 $userdevice->pushid = $params['pushid'];
1307 $userdevice->uuid = $params['uuid'];
1308 $userdevice->timecreated = time();
1309 $userdevice->timemodified = $userdevice->timecreated;
1311 if (!$DB->insert_record('user_devices', $userdevice)) {
1312 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1316 return $warnings;
1320 * Returns description of method result value.
1322 * @return external_multiple_structure
1323 * @since Moodle 2.6
1325 public static function add_user_device_returns() {
1326 return new external_multiple_structure(
1327 new external_warnings()
1332 * Returns description of method parameters.
1334 * @return external_function_parameters
1335 * @since Moodle 2.9
1337 public static function remove_user_device_parameters() {
1338 return new external_function_parameters(
1339 array(
1340 'uuid' => new external_value(PARAM_RAW, 'the device UUID'),
1341 'appid' => new external_value(PARAM_NOTAGS,
1342 'the app id, if empty devices matching the UUID for the user will be removed',
1343 VALUE_DEFAULT, ''),
1349 * Remove a user device from the Moodle database (for PUSH notifications usually).
1351 * @param string $uuid The device UUID.
1352 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1353 * @return array List of possible warnings and removal status.
1354 * @since Moodle 2.9
1356 public static function remove_user_device($uuid, $appid = "") {
1357 global $CFG;
1358 require_once($CFG->dirroot . "/user/lib.php");
1360 $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1362 $context = context_system::instance();
1363 self::validate_context($context);
1365 // Warnings array, it can be empty at the end but is mandatory.
1366 $warnings = array();
1368 $removed = user_remove_user_device($params['uuid'], $params['appid']);
1370 if (!$removed) {
1371 $warnings[] = array(
1372 'item' => $params['uuid'],
1373 'warningcode' => 'devicedoesnotexist',
1374 'message' => 'The device doesn\'t exists in the database'
1378 $result = array(
1379 'removed' => $removed,
1380 'warnings' => $warnings
1383 return $result;
1387 * Returns description of method result value.
1389 * @return external_multiple_structure
1390 * @since Moodle 2.9
1392 public static function remove_user_device_returns() {
1393 return new external_single_structure(
1394 array(
1395 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
1396 'warnings' => new external_warnings(),
1402 * Returns description of method parameters
1404 * @return external_function_parameters
1405 * @since Moodle 2.9
1407 public static function view_user_list_parameters() {
1408 return new external_function_parameters(
1409 array(
1410 'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site')
1416 * Trigger the user_list_viewed event.
1418 * @param int $courseid id of course
1419 * @return array of warnings and status result
1420 * @since Moodle 2.9
1421 * @throws moodle_exception
1423 public static function view_user_list($courseid) {
1424 global $CFG;
1425 require_once($CFG->dirroot . "/user/lib.php");
1426 require_once($CFG->dirroot . '/course/lib.php');
1428 $params = self::validate_parameters(self::view_user_list_parameters(),
1429 array(
1430 'courseid' => $courseid
1433 $warnings = array();
1435 if (empty($params['courseid'])) {
1436 $params['courseid'] = SITEID;
1439 $course = get_course($params['courseid']);
1441 if ($course->id == SITEID) {
1442 $context = context_system::instance();
1443 } else {
1444 $context = context_course::instance($course->id);
1446 self::validate_context($context);
1448 course_require_view_participants($context);
1450 user_list_view($course, $context);
1452 $result = array();
1453 $result['status'] = true;
1454 $result['warnings'] = $warnings;
1455 return $result;
1459 * Returns description of method result value
1461 * @return external_description
1462 * @since Moodle 2.9
1464 public static function view_user_list_returns() {
1465 return new external_single_structure(
1466 array(
1467 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1468 'warnings' => new external_warnings()
1474 * Returns description of method parameters
1476 * @return external_function_parameters
1477 * @since Moodle 2.9
1479 public static function view_user_profile_parameters() {
1480 return new external_function_parameters(
1481 array(
1482 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1483 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
1489 * Trigger the user profile viewed event.
1491 * @param int $userid id of user
1492 * @param int $courseid id of course
1493 * @return array of warnings and status result
1494 * @since Moodle 2.9
1495 * @throws moodle_exception
1497 public static function view_user_profile($userid, $courseid = 0) {
1498 global $CFG, $USER;
1499 require_once($CFG->dirroot . "/user/profile/lib.php");
1501 $params = self::validate_parameters(self::view_user_profile_parameters(),
1502 array(
1503 'userid' => $userid,
1504 'courseid' => $courseid
1507 $warnings = array();
1509 if (empty($params['userid'])) {
1510 $params['userid'] = $USER->id;
1513 if (empty($params['courseid'])) {
1514 $params['courseid'] = SITEID;
1517 $course = get_course($params['courseid']);
1518 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1519 core_user::require_active_user($user);
1521 if ($course->id == SITEID) {
1522 $coursecontext = context_system::instance();;
1523 } else {
1524 $coursecontext = context_course::instance($course->id);
1526 self::validate_context($coursecontext);
1528 $currentuser = $USER->id == $user->id;
1529 $usercontext = context_user::instance($user->id);
1531 if (!$currentuser and
1532 !has_capability('moodle/user:viewdetails', $coursecontext) and
1533 !has_capability('moodle/user:viewdetails', $usercontext)) {
1534 throw new moodle_exception('cannotviewprofile');
1537 // Case like user/profile.php.
1538 if ($course->id == SITEID) {
1539 profile_view($user, $usercontext);
1540 } else {
1541 // Case like user/view.php.
1542 if (!$currentuser and !can_access_course($course, $user, '', true)) {
1543 throw new moodle_exception('notenrolledprofile');
1546 profile_view($user, $coursecontext, $course);
1549 $result = array();
1550 $result['status'] = true;
1551 $result['warnings'] = $warnings;
1552 return $result;
1556 * Returns description of method result value
1558 * @return external_description
1559 * @since Moodle 2.9
1561 public static function view_user_profile_returns() {
1562 return new external_single_structure(
1563 array(
1564 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1565 'warnings' => new external_warnings()
1571 * Returns description of method parameters
1573 * @return external_function_parameters
1574 * @since Moodle 3.2
1576 public static function get_user_preferences_parameters() {
1577 return new external_function_parameters(
1578 array(
1579 'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''),
1580 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0)
1586 * Return user preferences.
1588 * @param string $name preference name, empty for all
1589 * @param int $userid id of the user, 0 for current user
1590 * @return array of warnings and preferences
1591 * @since Moodle 3.2
1592 * @throws moodle_exception
1594 public static function get_user_preferences($name = '', $userid = 0) {
1595 global $USER;
1597 $params = self::validate_parameters(self::get_user_preferences_parameters(),
1598 array(
1599 'name' => $name,
1600 'userid' => $userid
1602 $preferences = array();
1603 $warnings = array();
1605 $context = context_system::instance();
1606 self::validate_context($context);
1608 if (empty($params['name'])) {
1609 $name = null;
1611 if (empty($params['userid'])) {
1612 $user = null;
1613 } else {
1614 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1615 core_user::require_active_user($user);
1616 if ($user->id != $USER->id) {
1617 // Only admins can retrieve other users preferences.
1618 require_capability('moodle/site:config', $context);
1622 $userpreferences = get_user_preferences($name, null, $user);
1623 // Check if we received just one preference.
1624 if (!is_array($userpreferences)) {
1625 $userpreferences = array($name => $userpreferences);
1628 foreach ($userpreferences as $name => $value) {
1629 $preferences[] = array(
1630 'name' => $name,
1631 'value' => $value,
1635 $result = array();
1636 $result['preferences'] = $preferences;
1637 $result['warnings'] = $warnings;
1638 return $result;
1642 * Returns description of method result value
1644 * @return external_description
1645 * @since Moodle 3.2
1647 public static function get_user_preferences_returns() {
1648 return new external_single_structure(
1649 array(
1650 'preferences' => new external_multiple_structure(
1651 new external_single_structure(
1652 array(
1653 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1654 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1657 'User custom fields (also known as user profile fields)'
1659 'warnings' => new external_warnings()
1665 * Returns description of method parameters
1667 * @return external_function_parameters
1668 * @since Moodle 3.2
1670 public static function update_picture_parameters() {
1671 return new external_function_parameters(
1672 array(
1673 'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'),
1674 'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false),
1675 'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0)
1681 * Update or delete the user picture in the site
1683 * @param int $draftitemid id of the user draft file to use as image
1684 * @param bool $delete if we should delete the user picture
1685 * @param int $userid id of the user, 0 for current user
1686 * @return array warnings and success status
1687 * @since Moodle 3.2
1688 * @throws moodle_exception
1690 public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1691 global $CFG, $USER, $PAGE;
1693 $params = self::validate_parameters(
1694 self::update_picture_parameters(),
1695 array(
1696 'draftitemid' => $draftitemid,
1697 'delete' => $delete,
1698 'userid' => $userid
1702 $context = context_system::instance();
1703 self::validate_context($context);
1705 if (!empty($CFG->disableuserimages)) {
1706 throw new moodle_exception('userimagesdisabled', 'admin');
1709 if (empty($params['userid']) or $params['userid'] == $USER->id) {
1710 $user = $USER;
1711 require_capability('moodle/user:editownprofile', $context);
1712 } else {
1713 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1714 core_user::require_active_user($user);
1715 $personalcontext = context_user::instance($user->id);
1717 require_capability('moodle/user:editprofile', $personalcontext);
1718 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
1719 throw new moodle_exception('useradmineditadmin');
1723 // Load the appropriate auth plugin.
1724 $userauth = get_auth_plugin($user->auth);
1725 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1726 throw new moodle_exception('noprofileedit', 'auth');
1729 $filemanageroptions = array(
1730 'maxbytes' => $CFG->maxbytes,
1731 'subdirs' => 0,
1732 'maxfiles' => 1,
1733 'accepted_types' => 'optimised_image'
1735 $user->deletepicture = $params['delete'];
1736 $user->imagefile = $params['draftitemid'];
1737 $success = core_user::update_picture($user, $filemanageroptions);
1739 $result = array(
1740 'success' => $success,
1741 'warnings' => array(),
1743 if ($success) {
1744 $userpicture = new user_picture(core_user::get_user($user->id));
1745 $userpicture->size = 1; // Size f1.
1746 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1748 return $result;
1752 * Returns description of method result value
1754 * @return external_description
1755 * @since Moodle 3.2
1757 public static function update_picture_returns() {
1758 return new external_single_structure(
1759 array(
1760 'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'),
1761 'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL),
1762 'warnings' => new external_warnings()
1768 * Returns description of method parameters
1770 * @return external_function_parameters
1771 * @since Moodle 3.2
1773 public static function set_user_preferences_parameters() {
1774 return new external_function_parameters(
1775 array(
1776 'preferences' => new external_multiple_structure(
1777 new external_single_structure(
1778 array(
1779 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1780 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1781 'userid' => new external_value(PARAM_INT, 'Id of the user to set the preference'),
1790 * Set user preferences.
1792 * @param array $preferences list of preferences including name, value and userid
1793 * @return array of warnings and preferences saved
1794 * @since Moodle 3.2
1795 * @throws moodle_exception
1797 public static function set_user_preferences($preferences) {
1798 global $USER;
1800 $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
1801 $warnings = array();
1802 $saved = array();
1804 $context = context_system::instance();
1805 self::validate_context($context);
1807 $userscache = array();
1808 foreach ($params['preferences'] as $pref) {
1809 // Check to which user set the preference.
1810 if (!empty($userscache[$pref['userid']])) {
1811 $user = $userscache[$pref['userid']];
1812 } else {
1813 try {
1814 $user = core_user::get_user($pref['userid'], '*', MUST_EXIST);
1815 core_user::require_active_user($user);
1816 $userscache[$pref['userid']] = $user;
1817 } catch (Exception $e) {
1818 $warnings[] = array(
1819 'item' => 'user',
1820 'itemid' => $pref['userid'],
1821 'warningcode' => 'invaliduser',
1822 'message' => $e->getMessage()
1824 continue;
1828 try {
1829 if (core_user::can_edit_preference($pref['name'], $user)) {
1830 $value = core_user::clean_preference($pref['value'], $pref['name']);
1831 set_user_preference($pref['name'], $value, $user->id);
1832 $saved[] = array(
1833 'name' => $pref['name'],
1834 'userid' => $user->id,
1836 } else {
1837 $warnings[] = array(
1838 'item' => 'user',
1839 'itemid' => $user->id,
1840 'warningcode' => 'nopermission',
1841 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id
1844 } catch (Exception $e) {
1845 $warnings[] = array(
1846 'item' => 'user',
1847 'itemid' => $user->id,
1848 'warningcode' => 'errorsavingpreference',
1849 'message' => $e->getMessage()
1854 $result = array();
1855 $result['saved'] = $saved;
1856 $result['warnings'] = $warnings;
1857 return $result;
1861 * Returns description of method result value
1863 * @return external_description
1864 * @since Moodle 3.2
1866 public static function set_user_preferences_returns() {
1867 return new external_single_structure(
1868 array(
1869 'saved' => new external_multiple_structure(
1870 new external_single_structure(
1871 array(
1872 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1873 'userid' => new external_value(PARAM_INT, 'The user the preference was set for'),
1875 ), 'Preferences saved'
1877 'warnings' => new external_warnings()
1883 * Returns description of method parameters.
1885 * @return external_function_parameters
1886 * @since Moodle 3.2
1888 public static function agree_site_policy_parameters() {
1889 return new external_function_parameters(array());
1893 * Agree the site policy for the current user.
1895 * @return array of warnings and status result
1896 * @since Moodle 3.2
1897 * @throws moodle_exception
1899 public static function agree_site_policy() {
1900 global $CFG, $DB, $USER;
1902 $warnings = array();
1904 $context = context_system::instance();
1905 try {
1906 // We expect an exception here since the user didn't agree the site policy yet.
1907 self::validate_context($context);
1908 } catch (Exception $e) {
1909 // We are expecting only a sitepolicynotagreed exception.
1910 if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
1911 // In case we receive a different exception, throw it.
1912 throw $e;
1916 $manager = new \core_privacy\local\sitepolicy\manager();
1917 if (!empty($USER->policyagreed)) {
1918 $status = false;
1919 $warnings[] = array(
1920 'item' => 'user',
1921 'itemid' => $USER->id,
1922 'warningcode' => 'alreadyagreed',
1923 'message' => 'The user already agreed the site policy.'
1925 } else if (!$manager->is_defined()) {
1926 $status = false;
1927 $warnings[] = array(
1928 'item' => 'user',
1929 'itemid' => $USER->id,
1930 'warningcode' => 'nositepolicy',
1931 'message' => 'The site does not have a site policy configured.'
1933 } else {
1934 $status = $manager->accept();
1937 $result = array();
1938 $result['status'] = $status;
1939 $result['warnings'] = $warnings;
1940 return $result;
1944 * Returns description of method result value.
1946 * @return external_description
1947 * @since Moodle 3.2
1949 public static function agree_site_policy_returns() {
1950 return new external_single_structure(
1951 array(
1952 'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'),
1953 'warnings' => new external_warnings()
1959 * Returns description of method parameters.
1961 * @return external_function_parameters
1962 * @since Moodle 3.4
1964 public static function get_private_files_info_parameters() {
1965 return new external_function_parameters(
1966 array(
1967 'userid' => new external_value(PARAM_INT, 'Id of the user, default to current user.', VALUE_DEFAULT, 0)
1973 * Returns general information about files in the user private files area.
1975 * @param int $userid Id of the user, default to current user.
1976 * @return array of warnings and file area information
1977 * @since Moodle 3.4
1978 * @throws moodle_exception
1980 public static function get_private_files_info($userid = 0) {
1981 global $CFG, $USER;
1982 require_once($CFG->libdir . '/filelib.php');
1984 $params = self::validate_parameters(self::get_private_files_info_parameters(), array('userid' => $userid));
1985 $warnings = array();
1987 $context = context_system::instance();
1988 self::validate_context($context);
1990 if (empty($params['userid']) || $params['userid'] == $USER->id) {
1991 $usercontext = context_user::instance($USER->id);
1992 require_capability('moodle/user:manageownfiles', $usercontext);
1993 } else {
1994 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1995 core_user::require_active_user($user);
1996 // Only admins can retrieve other users information.
1997 require_capability('moodle/site:config', $context);
1998 $usercontext = context_user::instance($user->id);
2001 $fileareainfo = file_get_file_area_info($usercontext->id, 'user', 'private');
2003 $result = array();
2004 $result['filecount'] = $fileareainfo['filecount'];
2005 $result['foldercount'] = $fileareainfo['foldercount'];
2006 $result['filesize'] = $fileareainfo['filesize'];
2007 $result['filesizewithoutreferences'] = $fileareainfo['filesize_without_references'];
2008 $result['warnings'] = $warnings;
2009 return $result;
2013 * Returns description of method result value.
2015 * @return external_description
2016 * @since Moodle 3.4
2018 public static function get_private_files_info_returns() {
2019 return new external_single_structure(
2020 array(
2021 'filecount' => new external_value(PARAM_INT, 'Number of files in the area.'),
2022 'foldercount' => new external_value(PARAM_INT, 'Number of folders in the area.'),
2023 'filesize' => new external_value(PARAM_INT, 'Total size of the files in the area.'),
2024 'filesizewithoutreferences' => new external_value(PARAM_INT, 'Total size of the area excluding file references'),
2025 'warnings' => new external_warnings()