2 // This file is part of Moodle - http://moodle.org/
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.
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
;
26 * User external functions
30 * @copyright 2011 Jerome Mouneyrac
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 class core_user_external
extends \core_external\external_api
{
37 * Returns description of method parameters
39 * @return external_function_parameters
42 public static function create_users_parameters() {
45 'createpassword' => new external_value(PARAM_BOOL
, 'True if password should be created and mailed to user.',
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',
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',
72 'alternatename' => new external_value(core_user
::get_property_type('alternatename'), 'The alternate name of the user',
75 'interests' => new external_value(PARAM_TEXT
, 'User interests (separated by commas)', VALUE_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
),
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
127 public static function create_users($users) {
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();
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';
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'] = '';
218 $updatepassword = true;
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);
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);
255 \core\event\user_created
::create_from_userid($user['id'])->trigger();
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();
275 * Returns description of method result value
277 * @return external_description
280 public static function create_users_returns() {
281 return new external_multiple_structure(
282 new external_single_structure(
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
298 public static function delete_users_parameters() {
299 return new external_function_parameters(
301 'userids' => new external_multiple_structure(new external_value(core_user
::get_property_type('id'), 'user ID')),
309 * @throws moodle_exception
310 * @param array $userids
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();
345 * Returns description of method result value
350 public static function delete_users_returns() {
355 * Returns description of method parameters.
357 * @return external_function_parameters
360 public static function update_user_preferences_parameters() {
361 return new external_function_parameters(
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(
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.
383 * @param bool|null $emailstop
384 * @param array $preferences
388 public static function update_user_preferences($userid = 0, $emailstop = null, $preferences = array()) {
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)) {
399 $systemcontext = context_system
::instance();
400 self
::validate_context($systemcontext);
403 'emailstop' => $emailstop,
404 'preferences' => $preferences
406 $params = self
::validate_parameters(self
::update_user_preferences_parameters(), $params);
407 $preferences = $params['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();
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;
451 * Returns description of method result value
456 public static function update_user_preferences_returns() {
461 * Returns description of method parameters
463 * @return external_function_parameters
466 public static function update_users_parameters() {
468 'id' => new external_value(core_user
::get_property_type('id'), 'ID of the user'),
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',
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',
493 'userpicture' => new external_value(PARAM_INT
,
494 'The itemid where the new user picture has been uploaded to, 0 to delete', VALUE_OPTIONAL
),
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',
502 'alternatename' => new external_value(core_user
::get_property_type('alternatename'), 'The alternate name of the user',
505 'interests' => new external_value(PARAM_TEXT
, 'User interests (separated by commas)', VALUE_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
),
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)
552 * @param array $users
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
,
572 'accepted_types' => 'optimised_image');
575 foreach ($params['users'] as $user) {
576 // Catch any exception while updating a user and return it as a warning.
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,
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';
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;
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);
663 \core\event\user_updated
::create_from_userid($user['id'])->trigger();
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) {
680 $transaction->rollback($e);
681 } catch (Exception
$e) {
683 $warning['item'] = 'user';
684 $warning['itemid'] = $user['id'];
685 if ($e instanceof moodle_exception
) {
686 $warning['warningcode'] = $e->errorcode
;
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
705 public static function update_users_returns() {
706 return new external_single_structure(
708 'warnings' => new external_warnings()
714 * Returns description of method parameters
716 * @return external_function_parameters
719 public static function get_users_by_field_parameters() {
720 return new external_function_parameters(
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.
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();
753 $paramtype = core_user
::get_property_type('id');
756 $paramtype = core_user
::get_property_type('idnumber');
759 $paramtype = core_user
::get_property_type('username');
762 $paramtype = core_user
::get_property_type('email');
765 throw new coding_exception('invalid field parameter',
766 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
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
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
817 public static function get_users_parameters() {
818 return new external_function_parameters(
820 'criteria' => new external_multiple_structure(
821 new external_single_structure(
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.
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.
864 $sqlparams = 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');
876 $usedkeys[$criteria['key']] = true;
879 $invalidcriteria = false;
880 // Clean the parameters.
881 $paramtype = PARAM_RAW
;
882 switch ($criteria['key']) {
884 $paramtype = core_user
::get_property_type('id');
887 $paramtype = core_user
::get_property_type('idnumber');
890 $paramtype = core_user
::get_property_type('username');
893 // We use PARAM_RAW to allow searches with %.
894 $paramtype = core_user
::get_property_type('email');
897 $paramtype = core_user
::get_property_type('auth');
901 $paramtype = core_user
::get_property_type('firstname');
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.
907 'item' => $criteria['key'],
908 'warningcode' => 'invalidfieldparameter',
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]);
918 if (!$invalidcriteria) {
919 $cleanedvalue = clean_param($criteria['value'], $paramtype);
924 switch ($criteria['key']) {
929 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
930 $sqlparams[$criteria['key']] = $cleanedvalue;
935 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
936 $sqlparams[$criteria['key']] = $cleanedvalue;
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)) {
956 foreach ($params['criteria'] as $criteria) {
957 if (empty($userdetails[$criteria['key']])) {
963 $returnedusers[] = $userdetails;
968 return array('users' => $returnedusers, 'warnings' => $warnings);
972 * Returns description of get_users result value.
974 * @return external_description
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
993 public static function get_course_user_profiles_parameters() {
994 return new external_function_parameters(
996 'userlist' => new external_multiple_structure(
997 new external_single_structure(
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
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));
1021 $courseids = array();
1022 foreach ($params['userlist'] as $value) {
1023 $userids[] = $value['userid'];
1024 $courseids[$value['userid']] = $value['courseid'];
1027 // Cache all courses.
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);
1041 $courses[$course->id
] = $course;
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);
1054 foreach ($users as $user) {
1055 if (!empty($user->deleted
)) {
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;
1073 * Returns description of method result value
1075 * @return external_description
1078 public static function get_course_user_profiles_returns() {
1079 $additionalfields = array(
1080 'groups' => new external_multiple_structure(
1081 new external_single_structure(
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(
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(
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(
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(
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
1177 public static function add_user_private_files_parameters() {
1178 return new external_function_parameters(
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
1193 public static function add_user_private_files($draftid) {
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,
1216 'areamaxbytes' => $maxareabytes);
1218 file_merge_files_from_draft_area_into_filearea($draftid, $context->id
, 'user', 'private', 0, $options);
1224 * Returns description of method result value
1226 * @return external_description
1229 public static function add_user_private_files_returns() {
1234 * Returns description of method parameters.
1236 * @return external_function_parameters
1239 public static function add_user_device_parameters() {
1240 return new external_function_parameters(
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.
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,
1275 'platform' => $platform,
1276 'version' => $version,
1277 'pushid' => $pushid,
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'
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);
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']);
1327 * Returns description of method result value.
1329 * @return external_multiple_structure
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
1344 public static function remove_user_device_parameters() {
1345 return new external_function_parameters(
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',
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.
1363 public static function remove_user_device($uuid, $appid = "") {
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']);
1378 $warnings[] = array(
1379 'item' => $params['uuid'],
1380 'warningcode' => 'devicedoesnotexist',
1381 'message' => 'The device doesn\'t exists in the database'
1386 'removed' => $removed,
1387 'warnings' => $warnings
1394 * Returns description of method result value.
1396 * @return external_multiple_structure
1399 public static function remove_user_device_returns() {
1400 return new external_single_structure(
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
1414 public static function view_user_list_parameters() {
1415 return new external_function_parameters(
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
1428 * @throws moodle_exception
1430 public static function view_user_list($courseid) {
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(),
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();
1451 $context = context_course
::instance($course->id
);
1453 self
::validate_context($context);
1455 course_require_view_participants($context);
1457 user_list_view($course, $context);
1460 $result['status'] = true;
1461 $result['warnings'] = $warnings;
1466 * Returns description of method result value
1468 * @return external_description
1471 public static function view_user_list_returns() {
1472 return new external_single_structure(
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
1486 public static function view_user_profile_parameters() {
1487 return new external_function_parameters(
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
1502 * @throws moodle_exception
1504 public static function view_user_profile($userid, $courseid = 0) {
1506 require_once($CFG->dirroot
. "/user/profile/lib.php");
1508 $params = self
::validate_parameters(self
::view_user_profile_parameters(),
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();;
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);
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);
1557 $result['status'] = true;
1558 $result['warnings'] = $warnings;
1563 * Returns description of method result value
1565 * @return external_description
1568 public static function view_user_profile_returns() {
1569 return new external_single_structure(
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
1583 public static function get_user_preferences_parameters() {
1584 return new external_function_parameters(
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
1599 * @throws moodle_exception
1601 public static function get_user_preferences($name = '', $userid = 0) {
1604 $params = self
::validate_parameters(self
::get_user_preferences_parameters(),
1609 $preferences = array();
1610 $warnings = array();
1612 $context = context_system
::instance();
1613 self
::validate_context($context);
1615 if (empty($params['name'])) {
1618 if (empty($params['userid'])) {
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(
1643 $result['preferences'] = $preferences;
1644 $result['warnings'] = $warnings;
1649 * Returns description of method result value
1651 * @return external_description
1654 public static function get_user_preferences_returns() {
1655 return new external_single_structure(
1657 'preferences' => new external_multiple_structure(
1658 new external_single_structure(
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
1677 public static function update_picture_parameters() {
1678 return new external_function_parameters(
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
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(),
1703 'draftitemid' => $draftitemid,
1704 'delete' => $delete,
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
) {
1718 require_capability('moodle/user:editownprofile', $context);
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
,
1740 'accepted_types' => 'optimised_image'
1742 $user->deletepicture
= $params['delete'];
1743 $user->imagefile
= $params['draftitemid'];
1744 $success = core_user
::update_picture($user, $filemanageroptions);
1747 'success' => $success,
1748 'warnings' => array(),
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);
1759 * Returns description of method result value
1761 * @return external_description
1764 public static function update_picture_returns() {
1765 return new external_single_structure(
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
1780 public static function set_user_preferences_parameters() {
1781 return new external_function_parameters(
1783 'preferences' => new external_multiple_structure(
1784 new external_single_structure(
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
1802 * @throws moodle_exception
1804 public static function set_user_preferences($preferences) {
1807 $params = self
::validate_parameters(self
::set_user_preferences_parameters(), array('preferences' => $preferences));
1808 $warnings = 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']];
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(
1827 'itemid' => $pref['userid'],
1828 'warningcode' => 'invaliduser',
1829 'message' => $e->getMessage()
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
);
1840 'name' => $pref['name'],
1841 'userid' => $user->id
,
1844 $warnings[] = array(
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(
1854 'itemid' => $user->id
,
1855 'warningcode' => 'errorsavingpreference',
1856 'message' => $e->getMessage()
1862 $result['saved'] = $saved;
1863 $result['warnings'] = $warnings;
1868 * Returns description of method result value
1870 * @return external_description
1873 public static function set_user_preferences_returns() {
1874 return new external_single_structure(
1876 'saved' => new external_multiple_structure(
1877 new external_single_structure(
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
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
1904 * @throws moodle_exception
1906 public static function agree_site_policy() {
1907 global $CFG, $DB, $USER;
1909 $warnings = array();
1911 $context = context_system
::instance();
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.
1923 $manager = new \core_privacy\local\sitepolicy\
manager();
1924 if (!empty($USER->policyagreed
)) {
1926 $warnings[] = array(
1928 'itemid' => $USER->id
,
1929 'warningcode' => 'alreadyagreed',
1930 'message' => 'The user already agreed the site policy.'
1932 } else if (!$manager->is_defined()) {
1934 $warnings[] = array(
1936 'itemid' => $USER->id
,
1937 'warningcode' => 'nositepolicy',
1938 'message' => 'The site does not have a site policy configured.'
1941 $status = $manager->accept();
1945 $result['status'] = $status;
1946 $result['warnings'] = $warnings;
1951 * Returns description of method result value.
1953 * @return external_description
1956 public static function agree_site_policy_returns() {
1957 return new external_single_structure(
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
1971 public static function get_private_files_info_parameters() {
1972 return new external_function_parameters(
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
1985 * @throws moodle_exception
1987 public static function get_private_files_info($userid = 0) {
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);
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');
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;
2020 * Returns description of method result value.
2022 * @return external_description
2025 public static function get_private_files_info_returns() {
2026 return new external_single_structure(
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()