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/>.
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");
31 * User external functions
35 * @copyright 2011 Jerome Mouneyrac
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 class core_user_external
extends external_api
{
42 * Returns description of method parameters
44 * @return external_function_parameters
47 public static function create_users_parameters() {
50 'createpassword' => new external_value(PARAM_BOOL
, 'True if password should be created and mailed to user.',
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',
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',
77 'alternatename' => new external_value(core_user
::get_property_type('alternatename'), 'The alternate name of the user',
80 'interests' => new external_value(PARAM_TEXT
, 'User interests (separated by commas)', VALUE_OPTIONAL
),
82 'url' => new external_value(core_user
::get_property_type('url'), 'User web page', VALUE_OPTIONAL
),
83 'icq' => new external_value(core_user
::get_property_type('icq'), 'ICQ number', VALUE_OPTIONAL
),
84 'skype' => new external_value(core_user
::get_property_type('skype'), 'Skype ID', VALUE_OPTIONAL
),
85 'aim' => new external_value(core_user
::get_property_type('aim'), 'AIM ID', VALUE_OPTIONAL
),
86 'yahoo' => new external_value(core_user
::get_property_type('yahoo'), 'Yahoo ID', VALUE_OPTIONAL
),
87 'msn' => new external_value(core_user
::get_property_type('msn'), 'MSN ID', VALUE_OPTIONAL
),
88 'idnumber' => new external_value(core_user
::get_property_type('idnumber'),
89 'An arbitrary ID code number perhaps from the institution', VALUE_DEFAULT
, ''),
90 'institution' => new external_value(core_user
::get_property_type('institution'), 'institution', VALUE_OPTIONAL
),
91 'department' => new external_value(core_user
::get_property_type('department'), 'department', VALUE_OPTIONAL
),
92 'phone1' => new external_value(core_user
::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL
),
93 'phone2' => new external_value(core_user
::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL
),
94 'address' => new external_value(core_user
::get_property_type('address'), 'Postal address', VALUE_OPTIONAL
),
95 // Other user preferences stored in the user table.
96 'lang' => new external_value(core_user
::get_property_type('lang'), 'Language code such as "en", must exist on server',
97 VALUE_DEFAULT
, core_user
::get_property_default('lang'), core_user
::get_property_null('lang')),
98 'calendartype' => new external_value(core_user
::get_property_type('calendartype'),
99 'Calendar type such as "gregorian", must exist on server', VALUE_DEFAULT
, $CFG->calendartype
, VALUE_OPTIONAL
),
100 'theme' => new external_value(core_user
::get_property_type('theme'),
101 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL
),
102 'mailformat' => new external_value(core_user
::get_property_type('mailformat'),
103 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL
),
104 // Custom user profile fields.
105 'customfields' => new external_multiple_structure(
106 new external_single_structure(
108 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the custom field'),
109 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')
111 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL
),
113 'preferences' => new external_multiple_structure(
114 new external_single_structure(
116 'type' => new external_value(PARAM_RAW
, 'The name of the preference'),
117 'value' => new external_value(PARAM_RAW
, 'The value of the preference')
119 ), 'User preferences', VALUE_OPTIONAL
),
121 return new external_function_parameters(
123 'users' => new external_multiple_structure(
124 new external_single_structure($userfields)
131 * Create one or more users.
133 * @throws invalid_parameter_exception
134 * @param array $users An array of users to create.
135 * @return array An array of arrays
138 public static function create_users($users) {
140 require_once($CFG->dirroot
."/lib/weblib.php");
141 require_once($CFG->dirroot
."/user/lib.php");
142 require_once($CFG->dirroot
."/user/editlib.php");
143 require_once($CFG->dirroot
."/user/profile/lib.php"); // Required for customfields related function.
145 // Ensure the current user is allowed to run this function.
146 $context = context_system
::instance();
147 self
::validate_context($context);
148 require_capability('moodle/user:create', $context);
150 // Do basic automatic PARAM checks on incoming data, using params description.
151 // If any problems are found then exceptions are thrown with helpful error messages.
152 $params = self
::validate_parameters(self
::create_users_parameters(), array('users' => $users));
154 $availableauths = core_component
::get_plugin_list('auth');
155 unset($availableauths['mnet']); // These would need mnethostid too.
156 unset($availableauths['webservice']); // We do not want new webservice users for now.
158 $availablethemes = core_component
::get_plugin_list('theme');
159 $availablelangs = get_string_manager()->get_list_of_translations();
161 $transaction = $DB->start_delegated_transaction();
164 $createpassword = false;
165 foreach ($params['users'] as $user) {
166 // Make sure that the username, firstname and lastname are not blank.
167 foreach (array('username', 'firstname', 'lastname') as $fieldname) {
168 if (trim($user[$fieldname]) === '') {
169 throw new invalid_parameter_exception('The field '.$fieldname.' cannot be blank');
173 // Make sure that the username doesn't already exist.
174 if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id
))) {
175 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
178 // Make sure auth is valid.
179 if (empty($availableauths[$user['auth']])) {
180 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
183 // Make sure lang is valid.
184 if (empty($availablelangs[$user['lang']])) {
185 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
188 // Make sure lang is valid.
189 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
190 // so no default value
191 // We need to test if the client sent it
192 // => !empty($user['theme']).
193 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
196 // Make sure we have a password or have to create one.
197 if (empty($user['password']) && empty($user['createpassword'])) {
198 throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
201 $user['confirmed'] = true;
202 $user['mnethostid'] = $CFG->mnet_localhost_id
;
204 // Start of user info validation.
205 // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
206 if (!validate_email($user['email'])) {
207 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
208 } else if (empty($CFG->allowaccountssameemail
) &&
209 $DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
210 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
212 // End of user info validation.
214 $createpassword = !empty($user['createpassword']);
215 unset($user['createpassword']);
216 if ($createpassword) {
217 $user['password'] = '';
218 $updatepassword = false;
220 $updatepassword = true;
223 // Create the user data now!
224 $user['id'] = user_create_user($user, $updatepassword, false);
226 $userobject = (object)$user;
228 // Set user interests.
229 if (!empty($user['interests'])) {
230 $trimmedinterests = array_map('trim', explode(',', $user['interests']));
231 $interests = array_filter($trimmedinterests, function($value) {
232 return !empty($value);
234 useredit_update_interests($userobject, $interests);
238 if (!empty($user['customfields'])) {
239 foreach ($user['customfields'] as $customfield) {
240 // Profile_save_data() saves profile file it's expecting a user with the correct id,
241 // and custom field to be named profile_field_"shortname".
242 $user["profile_field_".$customfield['type']] = $customfield['value'];
244 profile_save_data((object) $user);
247 if ($createpassword) {
248 setnew_password_and_mail($userobject);
249 unset_user_preference('create_password', $userobject);
250 set_user_preference('auth_forcepasswordchange', 1, $userobject);
254 \core\event\user_created
::create_from_userid($user['id'])->trigger();
257 if (!empty($user['preferences'])) {
258 $userpref = (object)$user;
259 foreach ($user['preferences'] as $preference) {
260 $userpref->{'preference_'.$preference['type']} = $preference['value'];
262 useredit_update_user_preference($userpref);
265 $userids[] = array('id' => $user['id'], 'username' => $user['username']);
268 $transaction->allow_commit();
274 * Returns description of method result value
276 * @return external_description
279 public static function create_users_returns() {
280 return new external_multiple_structure(
281 new external_single_structure(
283 'id' => new external_value(core_user
::get_property_type('id'), 'user id'),
284 'username' => new external_value(core_user
::get_property_type('username'), 'user name'),
292 * Returns description of method parameters
294 * @return external_function_parameters
297 public static function delete_users_parameters() {
298 return new external_function_parameters(
300 'userids' => new external_multiple_structure(new external_value(core_user
::get_property_type('id'), 'user ID')),
308 * @throws moodle_exception
309 * @param array $userids
313 public static function delete_users($userids) {
314 global $CFG, $DB, $USER;
315 require_once($CFG->dirroot
."/user/lib.php");
317 // Ensure the current user is allowed to run this function.
318 $context = context_system
::instance();
319 require_capability('moodle/user:delete', $context);
320 self
::validate_context($context);
322 $params = self
::validate_parameters(self
::delete_users_parameters(), array('userids' => $userids));
324 $transaction = $DB->start_delegated_transaction();
326 foreach ($params['userids'] as $userid) {
327 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST
);
328 // Must not allow deleting of admins or self!!!
329 if (is_siteadmin($user)) {
330 throw new moodle_exception('useradminodelete', 'error');
332 if ($USER->id
== $user->id
) {
333 throw new moodle_exception('usernotdeletederror', 'error');
335 user_delete_user($user);
338 $transaction->allow_commit();
344 * Returns description of method result value
349 public static function delete_users_returns() {
354 * Returns description of method parameters.
356 * @return external_function_parameters
359 public static function update_user_preferences_parameters() {
360 return new external_function_parameters(
362 'userid' => new external_value(PARAM_INT
, 'id of the user, default to current user', VALUE_DEFAULT
, 0),
363 'emailstop' => new external_value(core_user
::get_property_type('emailstop'),
364 'Enable or disable notifications for this user', VALUE_DEFAULT
, null),
365 'preferences' => new external_multiple_structure(
366 new external_single_structure(
368 'type' => new external_value(PARAM_RAW
, 'The name of the preference'),
369 'value' => new external_value(PARAM_RAW
, 'The value of the preference')
371 ), 'User preferences', VALUE_DEFAULT
, array()
378 * Update the user's preferences.
381 * @param bool|null $emailstop
382 * @param array $preferences
386 public static function update_user_preferences($userid, $emailstop = null, $preferences = array()) {
389 require_once($CFG->dirroot
. '/user/lib.php');
390 require_once($CFG->dirroot
. '/user/editlib.php');
391 require_once($CFG->dirroot
. '/message/lib.php');
393 if (empty($userid)) {
397 $systemcontext = context_system
::instance();
398 self
::validate_context($systemcontext);
401 'emailstop' => $emailstop,
402 'preferences' => $preferences
404 self
::validate_parameters(self
::update_user_preferences_parameters(), $params);
407 if (!empty($preferences)) {
408 $userpref = ['id' => $userid];
409 foreach ($preferences as $preference) {
410 $userpref['preference_' . $preference['type']] = $preference['value'];
412 useredit_update_user_preference($userpref);
415 // Check if they want to update the email.
416 if ($emailstop !== null) {
417 $otheruser = ($userid == $USER->id
) ?
$USER : core_user
::get_user($userid, '*', MUST_EXIST
);
418 core_user
::require_active_user($otheruser);
419 if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop
!= $emailstop) {
420 $user = new stdClass();
422 $user->emailstop
= $emailstop;
423 user_update_user($user);
425 // Update the $USER if we should.
426 if ($userid == $USER->id
) {
427 $USER->emailstop
= $emailstop;
436 * Returns description of method result value
441 public static function update_user_preferences_returns() {
446 * Returns description of method parameters
448 * @return external_function_parameters
451 public static function update_users_parameters() {
453 'id' => new external_value(core_user
::get_property_type('id'), 'ID of the user'),
455 'username' => new external_value(core_user
::get_property_type('username'),
456 'Username policy is defined in Moodle security config.', VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
457 'auth' => new external_value(core_user
::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
458 VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
459 'suspended' => new external_value(core_user
::get_property_type('suspended'),
460 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL
),
461 'password' => new external_value(core_user
::get_property_type('password'),
462 'Plain text password consisting of any characters', VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
463 'firstname' => new external_value(core_user
::get_property_type('firstname'), 'The first name(s) of the user',
464 VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
465 'lastname' => new external_value(core_user
::get_property_type('lastname'), 'The family name of the user',
467 'email' => new external_value(core_user
::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL
,
468 '', NULL_NOT_ALLOWED
),
469 'maildisplay' => new external_value(core_user
::get_property_type('maildisplay'), 'Email display', VALUE_OPTIONAL
),
470 'city' => new external_value(core_user
::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL
),
471 'country' => new external_value(core_user
::get_property_type('country'),
472 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
473 'timezone' => new external_value(core_user
::get_property_type('timezone'),
474 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL
),
475 'description' => new external_value(core_user
::get_property_type('description'), 'User profile description, no HTML',
478 'userpicture' => new external_value(PARAM_INT
,
479 'The itemid where the new user picture has been uploaded to, 0 to delete', VALUE_OPTIONAL
),
481 'firstnamephonetic' => new external_value(core_user
::get_property_type('firstnamephonetic'),
482 'The first name(s) phonetically of the user', VALUE_OPTIONAL
),
483 'lastnamephonetic' => new external_value(core_user
::get_property_type('lastnamephonetic'),
484 'The family name phonetically of the user', VALUE_OPTIONAL
),
485 'middlename' => new external_value(core_user
::get_property_type('middlename'), 'The middle name of the user',
487 'alternatename' => new external_value(core_user
::get_property_type('alternatename'), 'The alternate name of the user',
490 'interests' => new external_value(PARAM_TEXT
, 'User interests (separated by commas)', VALUE_OPTIONAL
),
492 'url' => new external_value(core_user
::get_property_type('url'), 'User web page', VALUE_OPTIONAL
),
493 'icq' => new external_value(core_user
::get_property_type('icq'), 'ICQ number', VALUE_OPTIONAL
),
494 'skype' => new external_value(core_user
::get_property_type('skype'), 'Skype ID', VALUE_OPTIONAL
),
495 'aim' => new external_value(core_user
::get_property_type('aim'), 'AIM ID', VALUE_OPTIONAL
),
496 'yahoo' => new external_value(core_user
::get_property_type('yahoo'), 'Yahoo ID', VALUE_OPTIONAL
),
497 'msn' => new external_value(core_user
::get_property_type('msn'), 'MSN ID', VALUE_OPTIONAL
),
498 'idnumber' => new external_value(core_user
::get_property_type('idnumber'),
499 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL
),
500 'institution' => new external_value(core_user
::get_property_type('institution'), 'Institution', VALUE_OPTIONAL
),
501 'department' => new external_value(core_user
::get_property_type('department'), 'Department', VALUE_OPTIONAL
),
502 'phone1' => new external_value(core_user
::get_property_type('phone1'), 'Phone', VALUE_OPTIONAL
),
503 'phone2' => new external_value(core_user
::get_property_type('phone2'), 'Mobile phone', VALUE_OPTIONAL
),
504 'address' => new external_value(core_user
::get_property_type('address'), 'Postal address', VALUE_OPTIONAL
),
505 // Other user preferences stored in the user table.
506 'lang' => new external_value(core_user
::get_property_type('lang'), 'Language code such as "en", must exist on server',
507 VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
508 'calendartype' => new external_value(core_user
::get_property_type('calendartype'),
509 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
510 'theme' => new external_value(core_user
::get_property_type('theme'),
511 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL
),
512 'mailformat' => new external_value(core_user
::get_property_type('mailformat'),
513 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL
),
514 // Custom user profile fields.
515 'customfields' => new external_multiple_structure(
516 new external_single_structure(
518 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the custom field'),
519 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')
521 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL
),
523 'preferences' => new external_multiple_structure(
524 new external_single_structure(
526 'type' => new external_value(PARAM_RAW
, 'The name of the preference'),
527 'value' => new external_value(PARAM_RAW
, 'The value of the preference')
529 ), 'User preferences', VALUE_OPTIONAL
),
531 return new external_function_parameters(
533 'users' => new external_multiple_structure(
534 new external_single_structure($userfields)
543 * @param array $users
547 public static function update_users($users) {
548 global $CFG, $DB, $USER;
549 require_once($CFG->dirroot
."/user/lib.php");
550 require_once($CFG->dirroot
."/user/profile/lib.php"); // Required for customfields related function.
551 require_once($CFG->dirroot
.'/user/editlib.php');
553 // Ensure the current user is allowed to run this function.
554 $context = context_system
::instance();
555 require_capability('moodle/user:update', $context);
556 self
::validate_context($context);
558 $params = self
::validate_parameters(self
::update_users_parameters(), array('users' => $users));
560 $filemanageroptions = array('maxbytes' => $CFG->maxbytes
,
563 'accepted_types' => 'web_image');
565 $transaction = $DB->start_delegated_transaction();
567 foreach ($params['users'] as $user) {
568 // First check the user exists.
569 if (!$existinguser = core_user
::get_user($user['id'])) {
572 // Check if we are trying to update an admin.
573 if ($existinguser->id
!= $USER->id
and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
576 // Other checks (deleted, remote or guest users).
577 if ($existinguser->deleted
or is_mnet_remote_user($existinguser) or isguestuser($existinguser->id
)) {
580 // Check duplicated emails.
581 if (isset($user['email']) && $user['email'] !== $existinguser->email
) {
582 if (!validate_email($user['email'])) {
584 } else if (empty($CFG->allowaccountssameemail
) &&
585 $DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $CFG->mnet_localhost_id
))) {
590 user_update_user($user, true, false);
592 $userobject = (object)$user;
594 // Update user picture if it was specified for this user.
595 if (empty($CFG->disableuserimages
) && isset($user['userpicture'])) {
596 $userobject->deletepicture
= null;
598 if ($user['userpicture'] == 0) {
599 $userobject->deletepicture
= true;
601 $userobject->imagefile
= $user['userpicture'];
604 core_user
::update_picture($userobject, $filemanageroptions);
607 // Update user interests.
608 if (!empty($user['interests'])) {
609 $trimmedinterests = array_map('trim', explode(',', $user['interests']));
610 $interests = array_filter($trimmedinterests, function($value) {
611 return !empty($value);
613 useredit_update_interests($userobject, $interests);
616 // Update user custom fields.
617 if (!empty($user['customfields'])) {
619 foreach ($user['customfields'] as $customfield) {
620 // Profile_save_data() saves profile file it's expecting a user with the correct id,
621 // and custom field to be named profile_field_"shortname".
622 $user["profile_field_".$customfield['type']] = $customfield['value'];
624 profile_save_data((object) $user);
628 \core\event\user_updated
::create_from_userid($user['id'])->trigger();
631 if (!empty($user['preferences'])) {
632 $userpref = clone($existinguser);
633 foreach ($user['preferences'] as $preference) {
634 $userpref->{'preference_'.$preference['type']} = $preference['value'];
636 useredit_update_user_preference($userpref);
638 if (isset($user['suspended']) and $user['suspended']) {
639 \core\session\manager
::kill_user_sessions($user['id']);
643 $transaction->allow_commit();
649 * Returns description of method result value
654 public static function update_users_returns() {
659 * Returns description of method parameters
661 * @return external_function_parameters
664 public static function get_users_by_field_parameters() {
665 return new external_function_parameters(
667 'field' => new external_value(PARAM_ALPHA
, 'the search field can be
668 \'id\' or \'idnumber\' or \'username\' or \'email\''),
669 'values' => new external_multiple_structure(
670 new external_value(PARAM_RAW
, 'the value to match'))
676 * Get user information for a unique field.
678 * @throws coding_exception
679 * @throws invalid_parameter_exception
680 * @param string $field
681 * @param array $values
682 * @return array An array of arrays containg user profiles.
685 public static function get_users_by_field($field, $values) {
686 global $CFG, $USER, $DB;
687 require_once($CFG->dirroot
. "/user/lib.php");
689 $params = self
::validate_parameters(self
::get_users_by_field_parameters(),
690 array('field' => $field, 'values' => $values));
692 // This array will keep all the users that are allowed to be searched,
693 // according to the current user's privileges.
694 $cleanedvalues = array();
698 $paramtype = core_user
::get_property_type('id');
701 $paramtype = core_user
::get_property_type('idnumber');
704 $paramtype = core_user
::get_property_type('username');
707 $paramtype = core_user
::get_property_type('email');
710 throw new coding_exception('invalid field parameter',
711 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
715 foreach ($values as $value) {
716 $cleanedvalue = clean_param($value, $paramtype);
717 if ( $value != $cleanedvalue) {
718 throw new invalid_parameter_exception('The field \'' . $field .
719 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
721 $cleanedvalues[] = $cleanedvalue;
724 // Retrieve the users.
725 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
727 $context = context_system
::instance();
728 self
::validate_context($context);
730 // Finally retrieve each users information.
731 $returnedusers = array();
732 foreach ($users as $user) {
733 $userdetails = user_get_user_details_courses($user);
735 // Return the user only if the searched field is returned.
736 // Otherwise it means that the $USER was not allowed to search the returned user.
737 if (!empty($userdetails) and !empty($userdetails[$field])) {
738 $returnedusers[] = $userdetails;
742 return $returnedusers;
746 * Returns description of method result value
748 * @return external_multiple_structure
751 public static function get_users_by_field_returns() {
752 return new external_multiple_structure(self
::user_description());
757 * Returns description of get_users() parameters.
759 * @return external_function_parameters
762 public static function get_users_parameters() {
763 return new external_function_parameters(
765 'criteria' => new external_multiple_structure(
766 new external_single_structure(
768 'key' => new external_value(PARAM_ALPHA
, 'the user column to search, expected keys (value format) are:
769 "id" (int) matching user id,
770 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
771 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
772 "idnumber" (string) matching user idnumber,
773 "username" (string) matching user username,
774 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
775 "auth" (string) matching user auth plugin'),
776 'value' => new external_value(PARAM_RAW
, 'the value to search')
778 ), 'the key/value pairs to be considered in user search. Values can not be empty.
779 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
780 key occurences are forbidden.
781 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
782 the search is still executed on the valid criterias.
783 You can search without criteria, but the function is not designed for it.
784 It could very slow or timeout. The function is designed to search some specific users.'
791 * Retrieve matching user.
793 * @throws moodle_exception
794 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
795 * @return array An array of arrays containing user profiles.
798 public static function get_users($criteria = array()) {
799 global $CFG, $USER, $DB;
801 require_once($CFG->dirroot
. "/user/lib.php");
803 $params = self
::validate_parameters(self
::get_users_parameters(),
804 array('criteria' => $criteria));
806 // Validate the criteria and retrieve the users.
809 $sqlparams = array();
812 // Do not retrieve deleted users.
813 $sql = ' deleted = 0';
815 foreach ($params['criteria'] as $criteriaindex => $criteria) {
817 // Check that the criteria has never been used.
818 if (array_key_exists($criteria['key'], $usedkeys)) {
819 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
821 $usedkeys[$criteria['key']] = true;
824 $invalidcriteria = false;
825 // Clean the parameters.
826 $paramtype = PARAM_RAW
;
827 switch ($criteria['key']) {
829 $paramtype = core_user
::get_property_type('id');
832 $paramtype = core_user
::get_property_type('idnumber');
835 $paramtype = core_user
::get_property_type('username');
838 // We use PARAM_RAW to allow searches with %.
839 $paramtype = core_user
::get_property_type('email');
842 $paramtype = core_user
::get_property_type('auth');
846 $paramtype = core_user
::get_property_type('firstname');
849 // Send back a warning that this search key is not supported in this version.
850 // This warning will make the function extandable without breaking clients.
852 'item' => $criteria['key'],
853 'warningcode' => 'invalidfieldparameter',
855 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
857 // Do not add this invalid criteria to the created SQL request.
858 $invalidcriteria = true;
859 unset($params['criteria'][$criteriaindex]);
863 if (!$invalidcriteria) {
864 $cleanedvalue = clean_param($criteria['value'], $paramtype);
869 switch ($criteria['key']) {
874 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
875 $sqlparams[$criteria['key']] = $cleanedvalue;
880 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
881 $sqlparams[$criteria['key']] = $cleanedvalue;
889 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
891 // Finally retrieve each users information.
892 $returnedusers = array();
893 foreach ($users as $user) {
894 $userdetails = user_get_user_details_courses($user);
896 // Return the user only if all the searched fields are returned.
897 // Otherwise it means that the $USER was not allowed to search the returned user.
898 if (!empty($userdetails)) {
901 foreach ($params['criteria'] as $criteria) {
902 if (empty($userdetails[$criteria['key']])) {
908 $returnedusers[] = $userdetails;
913 return array('users' => $returnedusers, 'warnings' => $warnings);
917 * Returns description of get_users result value.
919 * @return external_description
922 public static function get_users_returns() {
923 return new external_single_structure(
924 array('users' => new external_multiple_structure(
925 self
::user_description()
927 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
933 * Returns description of method parameters
935 * @return external_function_parameters
938 public static function get_course_user_profiles_parameters() {
939 return new external_function_parameters(
941 'userlist' => new external_multiple_structure(
942 new external_single_structure(
944 'userid' => new external_value(core_user
::get_property_type('id'), 'userid'),
945 'courseid' => new external_value(PARAM_INT
, 'courseid'),
954 * Get course participant's details
956 * @param array $userlist array of user ids and according course ids
957 * @return array An array of arrays describing course participants
960 public static function get_course_user_profiles($userlist) {
961 global $CFG, $USER, $DB;
962 require_once($CFG->dirroot
. "/user/lib.php");
963 $params = self
::validate_parameters(self
::get_course_user_profiles_parameters(), array('userlist' => $userlist));
966 $courseids = array();
967 foreach ($params['userlist'] as $value) {
968 $userids[] = $value['userid'];
969 $courseids[$value['userid']] = $value['courseid'];
972 // Cache all courses.
974 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED
);
975 $cselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
976 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
977 $params['contextlevel'] = CONTEXT_COURSE
;
978 $coursesql = "SELECT c.* $cselect
979 FROM {course} c $cjoin
980 WHERE c.id $sqlcourseids";
981 $rs = $DB->get_recordset_sql($coursesql, $params);
982 foreach ($rs as $course) {
983 // Adding course contexts to cache.
984 context_helper
::preload_from_record($course);
986 $courses[$course->id
] = $course;
990 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
);
991 $uselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
992 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
993 $params['contextlevel'] = CONTEXT_USER
;
994 $usersql = "SELECT u.* $uselect
996 WHERE u.id $sqluserids";
997 $users = $DB->get_recordset_sql($usersql, $params);
999 foreach ($users as $user) {
1000 if (!empty($user->deleted
)) {
1003 context_helper
::preload_from_record($user);
1004 $course = $courses[$courseids[$user->id
]];
1005 $context = context_course
::instance($courseids[$user->id
], IGNORE_MISSING
);
1006 self
::validate_context($context);
1007 if ($userarray = user_get_user_details($user, $course)) {
1008 $result[] = $userarray;
1018 * Returns description of method result value
1020 * @return external_description
1023 public static function get_course_user_profiles_returns() {
1024 $additionalfields = array(
1025 'groups' => new external_multiple_structure(
1026 new external_single_structure(
1028 'id' => new external_value(PARAM_INT
, 'group id'),
1029 'name' => new external_value(PARAM_RAW
, 'group name'),
1030 'description' => new external_value(PARAM_RAW
, 'group description'),
1031 'descriptionformat' => new external_format_value('description'),
1033 ), 'user groups', VALUE_OPTIONAL
),
1034 'roles' => new external_multiple_structure(
1035 new external_single_structure(
1037 'roleid' => new external_value(PARAM_INT
, 'role id'),
1038 'name' => new external_value(PARAM_RAW
, 'role name'),
1039 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'role shortname'),
1040 'sortorder' => new external_value(PARAM_INT
, 'role sortorder')
1042 ), 'user roles', VALUE_OPTIONAL
),
1043 'enrolledcourses' => new external_multiple_structure(
1044 new external_single_structure(
1046 'id' => new external_value(PARAM_INT
, 'Id of the course'),
1047 'fullname' => new external_value(PARAM_RAW
, 'Fullname of the course'),
1048 'shortname' => new external_value(PARAM_RAW
, 'Shortname of the course')
1050 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
)
1053 return new external_multiple_structure(self
::user_description($additionalfields));
1057 * Create user return value description.
1059 * @param array $additionalfields some additional field
1060 * @return single_structure_description
1062 public static function user_description($additionalfields = array()) {
1063 $userfields = array(
1064 'id' => new external_value(core_user
::get_property_type('id'), 'ID of the user'),
1065 'username' => new external_value(core_user
::get_property_type('username'), 'The username', VALUE_OPTIONAL
),
1066 'firstname' => new external_value(core_user
::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL
),
1067 'lastname' => new external_value(core_user
::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL
),
1068 'fullname' => new external_value(core_user
::get_property_type('firstname'), 'The fullname of the user'),
1069 'email' => new external_value(core_user
::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL
),
1070 'address' => new external_value(core_user
::get_property_type('address'), 'Postal address', VALUE_OPTIONAL
),
1071 'phone1' => new external_value(core_user
::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL
),
1072 'phone2' => new external_value(core_user
::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL
),
1073 'icq' => new external_value(core_user
::get_property_type('icq'), 'icq number', VALUE_OPTIONAL
),
1074 'skype' => new external_value(core_user
::get_property_type('skype'), 'skype id', VALUE_OPTIONAL
),
1075 'yahoo' => new external_value(core_user
::get_property_type('yahoo'), 'yahoo id', VALUE_OPTIONAL
),
1076 'aim' => new external_value(core_user
::get_property_type('aim'), 'aim id', VALUE_OPTIONAL
),
1077 'msn' => new external_value(core_user
::get_property_type('msn'), 'msn number', VALUE_OPTIONAL
),
1078 'department' => new external_value(core_user
::get_property_type('department'), 'department', VALUE_OPTIONAL
),
1079 'institution' => new external_value(core_user
::get_property_type('institution'), 'institution', VALUE_OPTIONAL
),
1080 'idnumber' => new external_value(core_user
::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL
),
1081 'interests' => new external_value(PARAM_TEXT
, 'user interests (separated by commas)', VALUE_OPTIONAL
),
1082 'firstaccess' => new external_value(core_user
::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL
),
1083 'lastaccess' => new external_value(core_user
::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL
),
1084 'auth' => new external_value(core_user
::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL
),
1085 '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
),
1086 'confirmed' => new external_value(core_user
::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL
),
1087 'lang' => new external_value(core_user
::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL
),
1088 'calendartype' => new external_value(core_user
::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL
),
1089 'theme' => new external_value(core_user
::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL
),
1090 'timezone' => new external_value(core_user
::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL
),
1091 'mailformat' => new external_value(core_user
::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL
),
1092 'description' => new external_value(core_user
::get_property_type('description'), 'User profile description', VALUE_OPTIONAL
),
1093 'descriptionformat' => new external_format_value(core_user
::get_property_type('descriptionformat'), VALUE_OPTIONAL
),
1094 'city' => new external_value(core_user
::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL
),
1095 'url' => new external_value(core_user
::get_property_type('url'), 'URL of the user', VALUE_OPTIONAL
),
1096 'country' => new external_value(core_user
::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
1097 'profileimageurlsmall' => new external_value(PARAM_URL
, 'User image profile URL - small version'),
1098 'profileimageurl' => new external_value(PARAM_URL
, 'User image profile URL - big version'),
1099 'customfields' => new external_multiple_structure(
1100 new external_single_structure(
1102 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The type of the custom field - text field, checkbox...'),
1103 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
1104 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
1105 'shortname' => new external_value(PARAM_RAW
, 'The shortname of the custom field - to be able to build the field class in the code'),
1107 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL
),
1108 'preferences' => new external_multiple_structure(
1109 new external_single_structure(
1111 'name' => new external_value(PARAM_RAW
, 'The name of the preferences'),
1112 'value' => new external_value(PARAM_RAW
, 'The value of the preference'),
1114 ), 'Users preferences', VALUE_OPTIONAL
)
1116 if (!empty($additionalfields)) {
1117 $userfields = array_merge($userfields, $additionalfields);
1119 return new external_single_structure($userfields);
1123 * Returns description of method parameters
1125 * @return external_function_parameters
1128 public static function add_user_private_files_parameters() {
1129 return new external_function_parameters(
1131 'draftid' => new external_value(PARAM_INT
, 'draft area id')
1137 * Copy files from a draft area to users private files area.
1139 * @throws invalid_parameter_exception
1140 * @param int $draftid Id of a draft area containing files.
1141 * @return array An array of warnings
1144 public static function add_user_private_files($draftid) {
1146 require_once($CFG->libdir
. "/filelib.php");
1148 $params = self
::validate_parameters(self
::add_user_private_files_parameters(), array('draftid' => $draftid));
1150 if (isguestuser()) {
1151 throw new invalid_parameter_exception('Guest users cannot upload files');
1154 $context = context_user
::instance($USER->id
);
1155 require_capability('moodle/user:manageownfiles', $context);
1157 $maxbytes = $CFG->userquota
;
1158 $maxareabytes = $CFG->userquota
;
1159 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1160 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
1161 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED
;
1164 $options = array('subdirs' => 1,
1165 'maxbytes' => $maxbytes,
1167 'areamaxbytes' => $maxareabytes);
1169 file_merge_files_from_draft_area_into_filearea($draftid, $context->id
, 'user', 'private', 0, $options);
1175 * Returns description of method result value
1177 * @return external_description
1180 public static function add_user_private_files_returns() {
1185 * Returns description of method parameters.
1187 * @return external_function_parameters
1190 public static function add_user_device_parameters() {
1191 return new external_function_parameters(
1193 'appid' => new external_value(PARAM_NOTAGS
, 'the app id, usually something like com.moodle.moodlemobile'),
1194 'name' => new external_value(PARAM_NOTAGS
, 'the device name, \'occam\' or \'iPhone\' etc.'),
1195 'model' => new external_value(PARAM_NOTAGS
, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1196 'platform' => new external_value(PARAM_NOTAGS
, 'the device platform \'iOS\' or \'Android\' etc.'),
1197 'version' => new external_value(PARAM_NOTAGS
, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1198 'pushid' => new external_value(PARAM_RAW
, 'the device PUSH token/key/identifier/registration id'),
1199 'uuid' => new external_value(PARAM_RAW
, 'the device UUID')
1205 * Add a user device in Moodle database (for PUSH notifications usually).
1207 * @throws moodle_exception
1208 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1209 * @param string $name The device name, occam or iPhone etc.
1210 * @param string $model The device model Nexus4 or iPad1.1 etc.
1211 * @param string $platform The device platform iOs or Android etc.
1212 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1213 * @param string $pushid The device PUSH token/key/identifier/registration id.
1214 * @param string $uuid The device UUID.
1215 * @return array List of possible warnings.
1218 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1219 global $CFG, $USER, $DB;
1220 require_once($CFG->dirroot
. "/user/lib.php");
1222 $params = self
::validate_parameters(self
::add_user_device_parameters(),
1223 array('appid' => $appid,
1226 'platform' => $platform,
1227 'version' => $version,
1228 'pushid' => $pushid,
1232 $warnings = array();
1234 // Prevent duplicate keys for users.
1235 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id
))) {
1236 $warnings['warning'][] = array(
1237 'item' => $params['pushid'],
1238 'warningcode' => 'existingkeyforthisuser',
1239 'message' => 'This key is already stored for this user'
1244 // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1245 // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1246 if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1247 'appid' => $params['appid'], 'userid' => $USER->id
))) {
1249 foreach ($userdevices as $userdevice) {
1250 $userdevice->version
= $params['version']; // Maybe the user upgraded the device.
1251 $userdevice->pushid
= $params['pushid'];
1252 $userdevice->timemodified
= time();
1253 $DB->update_record('user_devices', $userdevice);
1257 $userdevice = new stdclass
;
1258 $userdevice->userid
= $USER->id
;
1259 $userdevice->appid
= $params['appid'];
1260 $userdevice->name
= $params['name'];
1261 $userdevice->model
= $params['model'];
1262 $userdevice->platform
= $params['platform'];
1263 $userdevice->version
= $params['version'];
1264 $userdevice->pushid
= $params['pushid'];
1265 $userdevice->uuid
= $params['uuid'];
1266 $userdevice->timecreated
= time();
1267 $userdevice->timemodified
= $userdevice->timecreated
;
1269 if (!$DB->insert_record('user_devices', $userdevice)) {
1270 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1278 * Returns description of method result value.
1280 * @return external_multiple_structure
1283 public static function add_user_device_returns() {
1284 return new external_multiple_structure(
1285 new external_warnings()
1290 * Returns description of method parameters.
1292 * @return external_function_parameters
1295 public static function remove_user_device_parameters() {
1296 return new external_function_parameters(
1298 'uuid' => new external_value(PARAM_RAW
, 'the device UUID'),
1299 'appid' => new external_value(PARAM_NOTAGS
,
1300 'the app id, if empty devices matching the UUID for the user will be removed',
1307 * Remove a user device from the Moodle database (for PUSH notifications usually).
1309 * @param string $uuid The device UUID.
1310 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1311 * @return array List of possible warnings and removal status.
1314 public static function remove_user_device($uuid, $appid = "") {
1316 require_once($CFG->dirroot
. "/user/lib.php");
1318 $params = self
::validate_parameters(self
::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1320 $context = context_system
::instance();
1321 self
::validate_context($context);
1323 // Warnings array, it can be empty at the end but is mandatory.
1324 $warnings = array();
1326 $removed = user_remove_user_device($params['uuid'], $params['appid']);
1329 $warnings[] = array(
1330 'item' => $params['uuid'],
1331 'warningcode' => 'devicedoesnotexist',
1332 'message' => 'The device doesn\'t exists in the database'
1337 'removed' => $removed,
1338 'warnings' => $warnings
1345 * Returns description of method result value.
1347 * @return external_multiple_structure
1350 public static function remove_user_device_returns() {
1351 return new external_single_structure(
1353 'removed' => new external_value(PARAM_BOOL
, 'True if removed, false if not removed because it doesn\'t exists'),
1354 'warnings' => new external_warnings(),
1360 * Returns description of method parameters
1362 * @return external_function_parameters
1365 public static function view_user_list_parameters() {
1366 return new external_function_parameters(
1368 'courseid' => new external_value(PARAM_INT
, 'id of the course, 0 for site')
1374 * Trigger the user_list_viewed event.
1376 * @param int $courseid id of course
1377 * @return array of warnings and status result
1379 * @throws moodle_exception
1381 public static function view_user_list($courseid) {
1383 require_once($CFG->dirroot
. "/user/lib.php");
1384 require_once($CFG->dirroot
. '/course/lib.php');
1386 $params = self
::validate_parameters(self
::view_user_list_parameters(),
1388 'courseid' => $courseid
1391 $warnings = array();
1393 if (empty($params['courseid'])) {
1394 $params['courseid'] = SITEID
;
1397 $course = get_course($params['courseid']);
1399 if ($course->id
== SITEID
) {
1400 $context = context_system
::instance();
1402 $context = context_course
::instance($course->id
);
1404 self
::validate_context($context);
1406 course_require_view_participants($context);
1408 user_list_view($course, $context);
1411 $result['status'] = true;
1412 $result['warnings'] = $warnings;
1417 * Returns description of method result value
1419 * @return external_description
1422 public static function view_user_list_returns() {
1423 return new external_single_structure(
1425 'status' => new external_value(PARAM_BOOL
, 'status: true if success'),
1426 'warnings' => new external_warnings()
1432 * Returns description of method parameters
1434 * @return external_function_parameters
1437 public static function view_user_profile_parameters() {
1438 return new external_function_parameters(
1440 'userid' => new external_value(PARAM_INT
, 'id of the user, 0 for current user', VALUE_REQUIRED
),
1441 'courseid' => new external_value(PARAM_INT
, 'id of the course, default site course', VALUE_DEFAULT
, 0)
1447 * Trigger the user profile viewed event.
1449 * @param int $userid id of user
1450 * @param int $courseid id of course
1451 * @return array of warnings and status result
1453 * @throws moodle_exception
1455 public static function view_user_profile($userid, $courseid = 0) {
1457 require_once($CFG->dirroot
. "/user/profile/lib.php");
1459 $params = self
::validate_parameters(self
::view_user_profile_parameters(),
1461 'userid' => $userid,
1462 'courseid' => $courseid
1465 $warnings = array();
1467 if (empty($params['userid'])) {
1468 $params['userid'] = $USER->id
;
1471 if (empty($params['courseid'])) {
1472 $params['courseid'] = SITEID
;
1475 $course = get_course($params['courseid']);
1476 $user = core_user
::get_user($params['userid'], '*', MUST_EXIST
);
1477 core_user
::require_active_user($user);
1479 if ($course->id
== SITEID
) {
1480 $coursecontext = context_system
::instance();;
1482 $coursecontext = context_course
::instance($course->id
);
1484 self
::validate_context($coursecontext);
1486 $currentuser = $USER->id
== $user->id
;
1487 $usercontext = context_user
::instance($user->id
);
1489 if (!$currentuser and
1490 !has_capability('moodle/user:viewdetails', $coursecontext) and
1491 !has_capability('moodle/user:viewdetails', $usercontext)) {
1492 throw new moodle_exception('cannotviewprofile');
1495 // Case like user/profile.php.
1496 if ($course->id
== SITEID
) {
1497 profile_view($user, $usercontext);
1499 // Case like user/view.php.
1500 if (!$currentuser and !can_access_course($course, $user, '', true)) {
1501 throw new moodle_exception('notenrolledprofile');
1504 profile_view($user, $coursecontext, $course);
1508 $result['status'] = true;
1509 $result['warnings'] = $warnings;
1514 * Returns description of method result value
1516 * @return external_description
1519 public static function view_user_profile_returns() {
1520 return new external_single_structure(
1522 'status' => new external_value(PARAM_BOOL
, 'status: true if success'),
1523 'warnings' => new external_warnings()
1529 * Returns description of method parameters
1531 * @return external_function_parameters
1534 public static function get_user_preferences_parameters() {
1535 return new external_function_parameters(
1537 'name' => new external_value(PARAM_RAW
, 'preference name, empty for all', VALUE_DEFAULT
, ''),
1538 'userid' => new external_value(PARAM_INT
, 'id of the user, default to current user', VALUE_DEFAULT
, 0)
1544 * Return user preferences.
1546 * @param string $name preference name, empty for all
1547 * @param int $userid id of the user, 0 for current user
1548 * @return array of warnings and preferences
1550 * @throws moodle_exception
1552 public static function get_user_preferences($name = '', $userid = 0) {
1555 $params = self
::validate_parameters(self
::get_user_preferences_parameters(),
1560 $preferences = array();
1561 $warnings = array();
1563 $context = context_system
::instance();
1564 self
::validate_context($context);
1566 if (empty($params['name'])) {
1569 if (empty($params['userid'])) {
1572 $user = core_user
::get_user($params['userid'], '*', MUST_EXIST
);
1573 core_user
::require_active_user($user);
1574 if ($user->id
!= $USER->id
) {
1575 // Only admins can retrieve other users preferences.
1576 require_capability('moodle/site:config', $context);
1580 $userpreferences = get_user_preferences($name, null, $user);
1581 // Check if we received just one preference.
1582 if (!is_array($userpreferences)) {
1583 $userpreferences = array($name => $userpreferences);
1586 foreach ($userpreferences as $name => $value) {
1587 $preferences[] = array(
1594 $result['preferences'] = $preferences;
1595 $result['warnings'] = $warnings;
1600 * Returns description of method result value
1602 * @return external_description
1605 public static function get_user_preferences_returns() {
1606 return new external_single_structure(
1608 'preferences' => new external_multiple_structure(
1609 new external_single_structure(
1611 'name' => new external_value(PARAM_RAW
, 'The name of the preference'),
1612 'value' => new external_value(PARAM_RAW
, 'The value of the preference'),
1615 'User custom fields (also known as user profile fields)'
1617 'warnings' => new external_warnings()
1623 * Returns description of method parameters
1625 * @return external_function_parameters
1628 public static function update_picture_parameters() {
1629 return new external_function_parameters(
1631 'draftitemid' => new external_value(PARAM_INT
, 'Id of the user draft file to use as image'),
1632 'delete' => new external_value(PARAM_BOOL
, 'If we should delete the user picture', VALUE_DEFAULT
, false),
1633 'userid' => new external_value(PARAM_INT
, 'Id of the user, 0 for current user', VALUE_DEFAULT
, 0)
1639 * Update or delete the user picture in the site
1641 * @param int $draftitemid id of the user draft file to use as image
1642 * @param bool $delete if we should delete the user picture
1643 * @param int $userid id of the user, 0 for current user
1644 * @return array warnings and success status
1646 * @throws moodle_exception
1648 public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1649 global $CFG, $USER, $PAGE;
1651 $params = self
::validate_parameters(
1652 self
::update_picture_parameters(),
1654 'draftitemid' => $draftitemid,
1655 'delete' => $delete,
1660 $context = context_system
::instance();
1661 self
::validate_context($context);
1663 if (!empty($CFG->disableuserimages
)) {
1664 throw new moodle_exception('userimagesdisabled', 'admin');
1667 if (empty($params['userid']) or $params['userid'] == $USER->id
) {
1669 require_capability('moodle/user:editownprofile', $context);
1671 $user = core_user
::get_user($params['userid'], '*', MUST_EXIST
);
1672 core_user
::require_active_user($user);
1673 $personalcontext = context_user
::instance($user->id
);
1675 require_capability('moodle/user:editprofile', $personalcontext);
1676 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
1677 throw new moodle_exception('useradmineditadmin');
1681 // Load the appropriate auth plugin.
1682 $userauth = get_auth_plugin($user->auth
);
1683 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1684 throw new moodle_exception('noprofileedit', 'auth');
1687 $filemanageroptions = array('maxbytes' => $CFG->maxbytes
, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image');
1688 $user->deletepicture
= $params['delete'];
1689 $user->imagefile
= $params['draftitemid'];
1690 $success = core_user
::update_picture($user, $filemanageroptions);
1693 'success' => $success,
1694 'warnings' => array(),
1697 $userpicture = new user_picture(core_user
::get_user($user->id
));
1698 $userpicture->size
= 1; // Size f1.
1699 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1705 * Returns description of method result value
1707 * @return external_description
1710 public static function update_picture_returns() {
1711 return new external_single_structure(
1713 'success' => new external_value(PARAM_BOOL
, 'True if the image was updated, false otherwise.'),
1714 'profileimageurl' => new external_value(PARAM_URL
, 'New profile user image url', VALUE_OPTIONAL
),
1715 'warnings' => new external_warnings()
1721 * Returns description of method parameters
1723 * @return external_function_parameters
1726 public static function set_user_preferences_parameters() {
1727 return new external_function_parameters(
1729 'preferences' => new external_multiple_structure(
1730 new external_single_structure(
1732 'name' => new external_value(PARAM_RAW
, 'The name of the preference'),
1733 'value' => new external_value(PARAM_RAW
, 'The value of the preference'),
1734 'userid' => new external_value(PARAM_INT
, 'Id of the user to set the preference'),
1743 * Set user preferences.
1745 * @param array $preferences list of preferences including name, value and userid
1746 * @return array of warnings and preferences saved
1748 * @throws moodle_exception
1750 public static function set_user_preferences($preferences) {
1753 $params = self
::validate_parameters(self
::set_user_preferences_parameters(), array('preferences' => $preferences));
1754 $warnings = array();
1757 $context = context_system
::instance();
1758 self
::validate_context($context);
1760 $userscache = array();
1761 foreach ($params['preferences'] as $pref) {
1762 // Check to which user set the preference.
1763 if (!empty($userscache[$pref['userid']])) {
1764 $user = $userscache[$pref['userid']];
1767 $user = core_user
::get_user($pref['userid'], '*', MUST_EXIST
);
1768 core_user
::require_active_user($user);
1769 $userscache[$pref['userid']] = $user;
1770 } catch (Exception
$e) {
1771 $warnings[] = array(
1773 'itemid' => $pref['userid'],
1774 'warningcode' => 'invaliduser',
1775 'message' => $e->getMessage()
1782 if (core_user
::can_edit_preference($pref['name'], $user)) {
1783 $value = core_user
::clean_preference($pref['value'], $pref['name']);
1784 set_user_preference($pref['name'], $value, $user->id
);
1786 'name' => $pref['name'],
1787 'userid' => $user->id
,
1790 $warnings[] = array(
1792 'itemid' => $user->id
,
1793 'warningcode' => 'nopermission',
1794 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id
1797 } catch (Exception
$e) {
1798 $warnings[] = array(
1800 'itemid' => $user->id
,
1801 'warningcode' => 'errorsavingpreference',
1802 'message' => $e->getMessage()
1808 $result['saved'] = $saved;
1809 $result['warnings'] = $warnings;
1814 * Returns description of method result value
1816 * @return external_description
1819 public static function set_user_preferences_returns() {
1820 return new external_single_structure(
1822 'saved' => new external_multiple_structure(
1823 new external_single_structure(
1825 'name' => new external_value(PARAM_RAW
, 'The name of the preference'),
1826 'userid' => new external_value(PARAM_INT
, 'The user the preference was set for'),
1828 ), 'Preferences saved'
1830 'warnings' => new external_warnings()
1836 * Returns description of method parameters.
1838 * @return external_function_parameters
1841 public static function agree_site_policy_parameters() {
1842 return new external_function_parameters(array());
1846 * Agree the site policy for the current user.
1848 * @return array of warnings and status result
1850 * @throws moodle_exception
1852 public static function agree_site_policy() {
1853 global $CFG, $DB, $USER;
1855 $warnings = array();
1857 $context = context_system
::instance();
1859 // We expect an exception here since the user didn't agree the site policy yet.
1860 self
::validate_context($context);
1861 } catch (Exception
$e) {
1862 // We are expecting only a sitepolicynotagreed exception.
1863 if (!($e instanceof moodle_exception
) or $e->errorcode
!= 'sitepolicynotagreed') {
1864 // In case we receive a different exception, throw it.
1869 $manager = new \core_privacy\local\sitepolicy\
manager();
1870 if (!empty($USER->policyagreed
)) {
1872 $warnings[] = array(
1874 'itemid' => $USER->id
,
1875 'warningcode' => 'alreadyagreed',
1876 'message' => 'The user already agreed the site policy.'
1878 } else if (!$manager->is_defined()) {
1880 $warnings[] = array(
1882 'itemid' => $USER->id
,
1883 'warningcode' => 'nositepolicy',
1884 'message' => 'The site does not have a site policy configured.'
1887 $status = $manager->accept();
1891 $result['status'] = $status;
1892 $result['warnings'] = $warnings;
1897 * Returns description of method result value.
1899 * @return external_description
1902 public static function agree_site_policy_returns() {
1903 return new external_single_structure(
1905 'status' => new external_value(PARAM_BOOL
, 'Status: true only if we set the policyagreed to 1 for the user'),
1906 'warnings' => new external_warnings()
1912 * Returns description of method parameters.
1914 * @return external_function_parameters
1917 public static function get_private_files_info_parameters() {
1918 return new external_function_parameters(
1920 'userid' => new external_value(PARAM_INT
, 'Id of the user, default to current user.', VALUE_DEFAULT
, 0)
1926 * Returns general information about files in the user private files area.
1928 * @param int $userid Id of the user, default to current user.
1929 * @return array of warnings and file area information
1931 * @throws moodle_exception
1933 public static function get_private_files_info($userid = 0) {
1935 require_once($CFG->libdir
. '/filelib.php');
1937 $params = self
::validate_parameters(self
::get_private_files_info_parameters(), array('userid' => $userid));
1938 $warnings = array();
1940 $context = context_system
::instance();
1941 self
::validate_context($context);
1943 if (empty($params['userid']) ||
$params['userid'] == $USER->id
) {
1944 $usercontext = context_user
::instance($USER->id
);
1945 require_capability('moodle/user:manageownfiles', $usercontext);
1947 $user = core_user
::get_user($params['userid'], '*', MUST_EXIST
);
1948 core_user
::require_active_user($user);
1949 // Only admins can retrieve other users information.
1950 require_capability('moodle/site:config', $context);
1951 $usercontext = context_user
::instance($user->id
);
1954 $fileareainfo = file_get_file_area_info($usercontext->id
, 'user', 'private');
1957 $result['filecount'] = $fileareainfo['filecount'];
1958 $result['foldercount'] = $fileareainfo['foldercount'];
1959 $result['filesize'] = $fileareainfo['filesize'];
1960 $result['filesizewithoutreferences'] = $fileareainfo['filesize_without_references'];
1961 $result['warnings'] = $warnings;
1966 * Returns description of method result value.
1968 * @return external_description
1971 public static function get_private_files_info_returns() {
1972 return new external_single_structure(
1974 'filecount' => new external_value(PARAM_INT
, 'Number of files in the area.'),
1975 'foldercount' => new external_value(PARAM_INT
, 'Number of folders in the area.'),
1976 'filesize' => new external_value(PARAM_INT
, 'Total size of the files in the area.'),
1977 'filesizewithoutreferences' => new external_value(PARAM_INT
, 'Total size of the area excluding file references'),
1978 'warnings' => new external_warnings()