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 require_once("$CFG->libdir/externallib.php");
29 * User external functions
33 * @copyright 2011 Jerome Mouneyrac
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class core_user_external
extends external_api
{
40 * Returns description of method parameters
42 * @return external_function_parameters
45 public static function create_users_parameters() {
48 return new external_function_parameters(
50 'users' => new external_multiple_structure(
51 new external_single_structure(
54 new external_value(core_user
::get_property_type('username'), 'Username policy is defined in Moodle security config.'),
56 new external_value(core_user
::get_property_type('password'), 'Plain text password consisting of any characters', VALUE_OPTIONAL
),
58 new external_value(PARAM_BOOL
, 'True if password should be created and mailed to user.',
61 new external_value(core_user
::get_property_type('firstname'), 'The first name(s) of the user'),
63 new external_value(core_user
::get_property_type('lastname'), 'The family name of the user'),
65 new external_value(core_user
::get_property_type('email'), 'A valid and unique email address'),
67 new external_value(core_user
::get_property_type('auth'), 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT
,
68 'manual', core_user
::get_property_null('auth')),
70 new external_value(core_user
::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution',
73 new external_value(core_user
::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_DEFAULT
,
74 core_user
::get_property_default('lang'), core_user
::get_property_null('lang')),
76 new external_value(core_user
::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server',
77 VALUE_DEFAULT
, $CFG->calendartype
, VALUE_OPTIONAL
),
79 new external_value(core_user
::get_property_type('theme'), 'Theme name such as "standard", must exist on server',
82 new external_value(core_user
::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default',
85 new external_value(core_user
::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc',
88 new external_value(core_user
::get_property_type('description'), 'User profile description, no HTML', VALUE_OPTIONAL
),
90 new external_value(core_user
::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL
),
92 new external_value(core_user
::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
93 'firstnamephonetic' =>
94 new external_value(core_user
::get_property_type('firstnamephonetic'), 'The first name(s) phonetically of the user', VALUE_OPTIONAL
),
96 new external_value(core_user
::get_property_type('lastnamephonetic'), 'The family name phonetically of the user', VALUE_OPTIONAL
),
98 new external_value(core_user
::get_property_type('middlename'), 'The middle name of the user', VALUE_OPTIONAL
),
100 new external_value(core_user
::get_property_type('alternatename'), 'The alternate name of the user', VALUE_OPTIONAL
),
101 'preferences' => new external_multiple_structure(
102 new external_single_structure(
104 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the preference'),
105 'value' => new external_value(PARAM_RAW
, 'The value of the preference')
107 ), 'User preferences', VALUE_OPTIONAL
),
108 'customfields' => new external_multiple_structure(
109 new external_single_structure(
111 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the custom field'),
112 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')
114 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL
)
123 * Create one or more users.
125 * @throws invalid_parameter_exception
126 * @param array $users An array of users to create.
127 * @return array An array of arrays
130 public static function create_users($users) {
132 require_once($CFG->dirroot
."/lib/weblib.php");
133 require_once($CFG->dirroot
."/user/lib.php");
134 require_once($CFG->dirroot
."/user/profile/lib.php"); // Required for customfields related function.
136 // Ensure the current user is allowed to run this function.
137 $context = context_system
::instance();
138 self
::validate_context($context);
139 require_capability('moodle/user:create', $context);
141 // Do basic automatic PARAM checks on incoming data, using params description.
142 // If any problems are found then exceptions are thrown with helpful error messages.
143 $params = self
::validate_parameters(self
::create_users_parameters(), array('users' => $users));
145 $availableauths = core_component
::get_plugin_list('auth');
146 unset($availableauths['mnet']); // These would need mnethostid too.
147 unset($availableauths['webservice']); // We do not want new webservice users for now.
149 $availablethemes = core_component
::get_plugin_list('theme');
150 $availablelangs = get_string_manager()->get_list_of_translations();
152 $transaction = $DB->start_delegated_transaction();
155 $createpassword = false;
156 foreach ($params['users'] as $user) {
157 // Make sure that the username doesn't already exist.
158 if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id
))) {
159 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
162 // Make sure auth is valid.
163 if (empty($availableauths[$user['auth']])) {
164 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
167 // Make sure lang is valid.
168 if (empty($availablelangs[$user['lang']])) {
169 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
172 // Make sure lang is valid.
173 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
174 // so no default value
175 // We need to test if the client sent it
176 // => !empty($user['theme']).
177 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
180 // Make sure we have a password or have to create one.
181 if (empty($user['password']) && empty($user['createpassword'])) {
182 throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
185 $user['confirmed'] = true;
186 $user['mnethostid'] = $CFG->mnet_localhost_id
;
188 // Start of user info validation.
189 // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
190 if (!validate_email($user['email'])) {
191 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
192 } else if (empty($CFG->allowaccountssameemail
) &&
193 $DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
194 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
196 // End of user info validation.
198 $createpassword = !empty($user['createpassword']);
199 unset($user['createpassword']);
200 if ($createpassword) {
201 $user['password'] = '';
202 $updatepassword = false;
204 $updatepassword = true;
207 // Create the user data now!
208 $user['id'] = user_create_user($user, $updatepassword, false);
211 if (!empty($user['customfields'])) {
212 foreach ($user['customfields'] as $customfield) {
213 // Profile_save_data() saves profile file it's expecting a user with the correct id,
214 // and custom field to be named profile_field_"shortname".
215 $user["profile_field_".$customfield['type']] = $customfield['value'];
217 profile_save_data((object) $user);
220 if ($createpassword) {
221 $userobject = (object)$user;
222 setnew_password_and_mail($userobject);
223 unset_user_preference('create_password', $userobject);
224 set_user_preference('auth_forcepasswordchange', 1, $userobject);
228 \core\event\user_created
::create_from_userid($user['id'])->trigger();
231 if (!empty($user['preferences'])) {
232 foreach ($user['preferences'] as $preference) {
233 set_user_preference($preference['type'], $preference['value'], $user['id']);
237 $userids[] = array('id' => $user['id'], 'username' => $user['username']);
240 $transaction->allow_commit();
246 * Returns description of method result value
248 * @return external_description
251 public static function create_users_returns() {
252 return new external_multiple_structure(
253 new external_single_structure(
255 'id' => new external_value(core_user
::get_property_type('id'), 'user id'),
256 'username' => new external_value(core_user
::get_property_type('username'), 'user name'),
264 * Returns description of method parameters
266 * @return external_function_parameters
269 public static function delete_users_parameters() {
270 return new external_function_parameters(
272 'userids' => new external_multiple_structure(new external_value(core_user
::get_property_type('id'), 'user ID')),
280 * @throws moodle_exception
281 * @param array $userids
285 public static function delete_users($userids) {
286 global $CFG, $DB, $USER;
287 require_once($CFG->dirroot
."/user/lib.php");
289 // Ensure the current user is allowed to run this function.
290 $context = context_system
::instance();
291 require_capability('moodle/user:delete', $context);
292 self
::validate_context($context);
294 $params = self
::validate_parameters(self
::delete_users_parameters(), array('userids' => $userids));
296 $transaction = $DB->start_delegated_transaction();
298 foreach ($params['userids'] as $userid) {
299 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST
);
300 // Must not allow deleting of admins or self!!!
301 if (is_siteadmin($user)) {
302 throw new moodle_exception('useradminodelete', 'error');
304 if ($USER->id
== $user->id
) {
305 throw new moodle_exception('usernotdeletederror', 'error');
307 user_delete_user($user);
310 $transaction->allow_commit();
316 * Returns description of method result value
321 public static function delete_users_returns() {
326 * Returns description of method parameters.
328 * @return external_function_parameters
331 public static function update_user_preferences_parameters() {
332 return new external_function_parameters(
334 'userid' => new external_value(PARAM_INT
, 'id of the user, default to current user', VALUE_DEFAULT
, 0),
335 'emailstop' => new external_value(core_user
::get_property_type('emailstop'),
336 'Enable or disable notifications for this user', VALUE_DEFAULT
, null),
337 'preferences' => new external_multiple_structure(
338 new external_single_structure(
340 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the preference'),
341 'value' => new external_value(PARAM_RAW
, 'The value of the preference')
343 ), 'User preferences', VALUE_DEFAULT
, array()
350 * Update the user's preferences.
353 * @param bool|null $emailstop
354 * @param array $preferences
358 public static function update_user_preferences($userid, $emailstop = null, $preferences = array()) {
361 require_once($CFG->dirroot
. '/user/lib.php');
363 if (empty($userid)) {
367 $systemcontext = context_system
::instance();
368 self
::validate_context($systemcontext);
371 'emailstop' => $emailstop,
372 'preferences' => $preferences
374 self
::validate_parameters(self
::update_user_preferences_parameters(), $params);
376 if ($userid == $USER->id
) {
377 require_capability('moodle/user:editownmessageprofile', $systemcontext);
379 $personalcontext = context_user
::instance($userid);
380 require_capability('moodle/user:editmessageprofile', $personalcontext);
381 // No editing of guest user account.
382 if (isguestuser($userid)) {
383 print_error('guestnoeditmessageother', 'message');
385 // No editing of admins by non-admins.
386 if (is_siteadmin($userid) and !is_siteadmin($USER)) {
387 print_error('useradmineditadmin');
392 if (!empty($preferences)) {
393 foreach ($preferences as $preference) {
394 set_user_preference($preference['type'], $preference['value'], $userid);
398 // Check if they want to update the email.
399 if ($emailstop !== null) {
400 $user = new stdClass();
402 $user->emailstop
= $emailstop;
403 user_update_user($user);
405 // Update the $USER if we should.
406 if ($userid == $USER->id
) {
407 $USER->emailstop
= $emailstop;
415 * Returns description of method result value
420 public static function update_user_preferences_returns() {
425 * Returns description of method parameters
427 * @return external_function_parameters
430 public static function update_users_parameters() {
431 return new external_function_parameters(
433 'users' => new external_multiple_structure(
434 new external_single_structure(
437 new external_value(core_user
::get_property_type('id'), 'ID of the user'),
439 new external_value(core_user
::get_property_type('username'), 'Username policy is defined in Moodle security config.',
440 VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
442 new external_value(core_user
::get_property_type('password'), 'Plain text password consisting of any characters', VALUE_OPTIONAL
,
443 '', NULL_NOT_ALLOWED
),
445 new external_value(core_user
::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL
, '',
448 new external_value(core_user
::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL
),
450 new external_value(core_user
::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL
, '',
453 new external_value(core_user
::get_property_type('auth'), 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL
, '',
456 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
),
458 new external_value(core_user
::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution',
461 new external_value(core_user
::get_property_type('lang'), 'Language code such as "en", must exist on server',
462 VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
464 new external_value(core_user
::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server',
465 VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
467 new external_value(core_user
::get_property_type('theme'), 'Theme name such as "standard", must exist on server',
470 new external_value(core_user
::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default',
473 new external_value(core_user
::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc',
476 new external_value(core_user
::get_property_type('description'), 'User profile description, no HTML', VALUE_OPTIONAL
),
478 new external_value(core_user
::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL
),
480 new external_value(core_user
::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
481 'firstnamephonetic' =>
482 new external_value(core_user
::get_property_type('firstnamephonetic'), 'The first name(s) phonetically of the user', VALUE_OPTIONAL
),
483 'lastnamephonetic' =>
484 new external_value(core_user
::get_property_type('lastnamephonetic'), 'The family name phonetically of the user', VALUE_OPTIONAL
),
486 new external_value(core_user
::get_property_type('middlename'), 'The middle name of the user', VALUE_OPTIONAL
),
488 new external_value(core_user
::get_property_type('alternatename'), 'The alternate name of the user', VALUE_OPTIONAL
),
490 new external_value(PARAM_INT
, 'The itemid where the new user picture '.
491 'has been uploaded to, 0 to delete', VALUE_OPTIONAL
),
492 'customfields' => new external_multiple_structure(
493 new external_single_structure(
495 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the custom field'),
496 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')
498 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL
),
499 'preferences' => new external_multiple_structure(
500 new external_single_structure(
502 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the preference'),
503 'value' => new external_value(PARAM_RAW
, 'The value of the preference')
505 ), 'User preferences', VALUE_OPTIONAL
),
516 * @param array $users
520 public static function update_users($users) {
521 global $CFG, $DB, $USER;
522 require_once($CFG->dirroot
."/user/lib.php");
523 require_once($CFG->dirroot
."/user/profile/lib.php"); // Required for customfields related function.
525 // Ensure the current user is allowed to run this function.
526 $context = context_system
::instance();
527 require_capability('moodle/user:update', $context);
528 self
::validate_context($context);
530 $params = self
::validate_parameters(self
::update_users_parameters(), array('users' => $users));
532 $filemanageroptions = array('maxbytes' => $CFG->maxbytes
,
535 'accepted_types' => 'web_image');
537 $transaction = $DB->start_delegated_transaction();
539 foreach ($params['users'] as $user) {
540 // First check the user exists.
541 if (!$existinguser = core_user
::get_user($user['id'])) {
544 // Check if we are trying to update an admin.
545 if ($existinguser->id
!= $USER->id
and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
548 // Other checks (deleted, remote or guest users).
549 if ($existinguser->deleted
or is_mnet_remote_user($existinguser) or isguestuser($existinguser->id
)) {
552 user_update_user($user, true, false);
554 // Update user picture if it was specified for this user.
555 if (empty($CFG->disableuserimages
) && isset($user['userpicture'])) {
556 $userobject = (object)$user;
558 $userobject->deletepicture
= null;
560 if ($user['userpicture'] == 0) {
561 $userobject->deletepicture
= true;
563 $userobject->imagefile
= $user['userpicture'];
566 core_user
::update_picture($userobject, $filemanageroptions);
569 // Update user custom fields.
570 if (!empty($user['customfields'])) {
572 foreach ($user['customfields'] as $customfield) {
573 // Profile_save_data() saves profile file it's expecting a user with the correct id,
574 // and custom field to be named profile_field_"shortname".
575 $user["profile_field_".$customfield['type']] = $customfield['value'];
577 profile_save_data((object) $user);
581 \core\event\user_updated
::create_from_userid($user['id'])->trigger();
584 if (!empty($user['preferences'])) {
585 foreach ($user['preferences'] as $preference) {
586 set_user_preference($preference['type'], $preference['value'], $user['id']);
589 if (isset($user['suspended']) and $user['suspended']) {
590 \core\session\manager
::kill_user_sessions($user['id']);
594 $transaction->allow_commit();
600 * Returns description of method result value
605 public static function update_users_returns() {
610 * Returns description of method parameters
612 * @return external_function_parameters
615 public static function get_users_by_field_parameters() {
616 return new external_function_parameters(
618 'field' => new external_value(PARAM_ALPHA
, 'the search field can be
619 \'id\' or \'idnumber\' or \'username\' or \'email\''),
620 'values' => new external_multiple_structure(
621 new external_value(PARAM_RAW
, 'the value to match'))
627 * Get user information for a unique field.
629 * @throws coding_exception
630 * @throws invalid_parameter_exception
631 * @param string $field
632 * @param array $values
633 * @return array An array of arrays containg user profiles.
636 public static function get_users_by_field($field, $values) {
637 global $CFG, $USER, $DB;
638 require_once($CFG->dirroot
. "/user/lib.php");
640 $params = self
::validate_parameters(self
::get_users_by_field_parameters(),
641 array('field' => $field, 'values' => $values));
643 // This array will keep all the users that are allowed to be searched,
644 // according to the current user's privileges.
645 $cleanedvalues = array();
649 $paramtype = core_user
::get_property_type('id');
652 $paramtype = core_user
::get_property_type('idnumber');
655 $paramtype = core_user
::get_property_type('username');
658 $paramtype = core_user
::get_property_type('email');
661 throw new coding_exception('invalid field parameter',
662 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
666 foreach ($values as $value) {
667 $cleanedvalue = clean_param($value, $paramtype);
668 if ( $value != $cleanedvalue) {
669 throw new invalid_parameter_exception('The field \'' . $field .
670 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
672 $cleanedvalues[] = $cleanedvalue;
675 // Retrieve the users.
676 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
678 $context = context_system
::instance();
679 self
::validate_context($context);
681 // Finally retrieve each users information.
682 $returnedusers = array();
683 foreach ($users as $user) {
684 $userdetails = user_get_user_details_courses($user);
686 // Return the user only if the searched field is returned.
687 // Otherwise it means that the $USER was not allowed to search the returned user.
688 if (!empty($userdetails) and !empty($userdetails[$field])) {
689 $returnedusers[] = $userdetails;
693 return $returnedusers;
697 * Returns description of method result value
699 * @return external_multiple_structure
702 public static function get_users_by_field_returns() {
703 return new external_multiple_structure(self
::user_description());
708 * Returns description of get_users() parameters.
710 * @return external_function_parameters
713 public static function get_users_parameters() {
714 return new external_function_parameters(
716 'criteria' => new external_multiple_structure(
717 new external_single_structure(
719 'key' => new external_value(PARAM_ALPHA
, 'the user column to search, expected keys (value format) are:
720 "id" (int) matching user id,
721 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
722 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
723 "idnumber" (string) matching user idnumber,
724 "username" (string) matching user username,
725 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
726 "auth" (string) matching user auth plugin'),
727 'value' => new external_value(PARAM_RAW
, 'the value to search')
729 ), 'the key/value pairs to be considered in user search. Values can not be empty.
730 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
731 key occurences are forbidden.
732 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
733 the search is still executed on the valid criterias.
734 You can search without criteria, but the function is not designed for it.
735 It could very slow or timeout. The function is designed to search some specific users.'
742 * Retrieve matching user.
744 * @throws moodle_exception
745 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
746 * @return array An array of arrays containing user profiles.
749 public static function get_users($criteria = array()) {
750 global $CFG, $USER, $DB;
752 require_once($CFG->dirroot
. "/user/lib.php");
754 $params = self
::validate_parameters(self
::get_users_parameters(),
755 array('criteria' => $criteria));
757 // Validate the criteria and retrieve the users.
760 $sqlparams = array();
763 // Do not retrieve deleted users.
764 $sql = ' deleted = 0';
766 foreach ($params['criteria'] as $criteriaindex => $criteria) {
768 // Check that the criteria has never been used.
769 if (array_key_exists($criteria['key'], $usedkeys)) {
770 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
772 $usedkeys[$criteria['key']] = true;
775 $invalidcriteria = false;
776 // Clean the parameters.
777 $paramtype = PARAM_RAW
;
778 switch ($criteria['key']) {
780 $paramtype = core_user
::get_property_type('id');
783 $paramtype = core_user
::get_property_type('idnumber');
786 $paramtype = core_user
::get_property_type('username');
789 // We use PARAM_RAW to allow searches with %.
790 $paramtype = core_user
::get_property_type('email');
793 $paramtype = core_user
::get_property_type('auth');
797 $paramtype = core_user
::get_property_type('firstname');
800 // Send back a warning that this search key is not supported in this version.
801 // This warning will make the function extandable without breaking clients.
803 'item' => $criteria['key'],
804 'warningcode' => 'invalidfieldparameter',
806 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
808 // Do not add this invalid criteria to the created SQL request.
809 $invalidcriteria = true;
810 unset($params['criteria'][$criteriaindex]);
814 if (!$invalidcriteria) {
815 $cleanedvalue = clean_param($criteria['value'], $paramtype);
820 switch ($criteria['key']) {
825 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
826 $sqlparams[$criteria['key']] = $cleanedvalue;
831 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
832 $sqlparams[$criteria['key']] = $cleanedvalue;
840 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
842 // Finally retrieve each users information.
843 $returnedusers = array();
844 foreach ($users as $user) {
845 $userdetails = user_get_user_details_courses($user);
847 // Return the user only if all the searched fields are returned.
848 // Otherwise it means that the $USER was not allowed to search the returned user.
849 if (!empty($userdetails)) {
852 foreach ($params['criteria'] as $criteria) {
853 if (empty($userdetails[$criteria['key']])) {
859 $returnedusers[] = $userdetails;
864 return array('users' => $returnedusers, 'warnings' => $warnings);
868 * Returns description of get_users result value.
870 * @return external_description
873 public static function get_users_returns() {
874 return new external_single_structure(
875 array('users' => new external_multiple_structure(
876 self
::user_description()
878 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
884 * Returns description of method parameters
886 * @return external_function_parameters
889 public static function get_course_user_profiles_parameters() {
890 return new external_function_parameters(
892 'userlist' => new external_multiple_structure(
893 new external_single_structure(
895 'userid' => new external_value(core_user
::get_property_type('id'), 'userid'),
896 'courseid' => new external_value(PARAM_INT
, 'courseid'),
905 * Get course participant's details
907 * @param array $userlist array of user ids and according course ids
908 * @return array An array of arrays describing course participants
911 public static function get_course_user_profiles($userlist) {
912 global $CFG, $USER, $DB;
913 require_once($CFG->dirroot
. "/user/lib.php");
914 $params = self
::validate_parameters(self
::get_course_user_profiles_parameters(), array('userlist' => $userlist));
917 $courseids = array();
918 foreach ($params['userlist'] as $value) {
919 $userids[] = $value['userid'];
920 $courseids[$value['userid']] = $value['courseid'];
923 // Cache all courses.
925 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED
);
926 $cselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
927 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
928 $params['contextlevel'] = CONTEXT_COURSE
;
929 $coursesql = "SELECT c.* $cselect
930 FROM {course} c $cjoin
931 WHERE c.id $sqlcourseids";
932 $rs = $DB->get_recordset_sql($coursesql, $params);
933 foreach ($rs as $course) {
934 // Adding course contexts to cache.
935 context_helper
::preload_from_record($course);
937 $courses[$course->id
] = $course;
941 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
);
942 $uselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
943 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
944 $params['contextlevel'] = CONTEXT_USER
;
945 $usersql = "SELECT u.* $uselect
947 WHERE u.id $sqluserids";
948 $users = $DB->get_recordset_sql($usersql, $params);
950 foreach ($users as $user) {
951 if (!empty($user->deleted
)) {
954 context_helper
::preload_from_record($user);
955 $course = $courses[$courseids[$user->id
]];
956 $context = context_course
::instance($courseids[$user->id
], IGNORE_MISSING
);
957 self
::validate_context($context);
958 if ($userarray = user_get_user_details($user, $course)) {
959 $result[] = $userarray;
969 * Returns description of method result value
971 * @return external_description
974 public static function get_course_user_profiles_returns() {
975 $additionalfields = array(
976 'groups' => new external_multiple_structure(
977 new external_single_structure(
979 'id' => new external_value(PARAM_INT
, 'group id'),
980 'name' => new external_value(PARAM_RAW
, 'group name'),
981 'description' => new external_value(PARAM_RAW
, 'group description'),
982 'descriptionformat' => new external_format_value('description'),
984 ), 'user groups', VALUE_OPTIONAL
),
985 'roles' => new external_multiple_structure(
986 new external_single_structure(
988 'roleid' => new external_value(PARAM_INT
, 'role id'),
989 'name' => new external_value(PARAM_RAW
, 'role name'),
990 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'role shortname'),
991 'sortorder' => new external_value(PARAM_INT
, 'role sortorder')
993 ), 'user roles', VALUE_OPTIONAL
),
994 'enrolledcourses' => new external_multiple_structure(
995 new external_single_structure(
997 'id' => new external_value(PARAM_INT
, 'Id of the course'),
998 'fullname' => new external_value(PARAM_RAW
, 'Fullname of the course'),
999 'shortname' => new external_value(PARAM_RAW
, 'Shortname of the course')
1001 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
)
1004 return new external_multiple_structure(self
::user_description($additionalfields));
1008 * Create user return value description.
1010 * @param array $additionalfields some additional field
1011 * @return single_structure_description
1013 public static function user_description($additionalfields = array()) {
1014 $userfields = array(
1015 'id' => new external_value(core_user
::get_property_type('id'), 'ID of the user'),
1016 'username' => new external_value(core_user
::get_property_type('username'), 'The username', VALUE_OPTIONAL
),
1017 'firstname' => new external_value(core_user
::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL
),
1018 'lastname' => new external_value(core_user
::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL
),
1019 'fullname' => new external_value(core_user
::get_property_type('firstname'), 'The fullname of the user'),
1020 'email' => new external_value(core_user
::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL
),
1021 'address' => new external_value(core_user
::get_property_type('address'), 'Postal address', VALUE_OPTIONAL
),
1022 'phone1' => new external_value(core_user
::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL
),
1023 'phone2' => new external_value(core_user
::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL
),
1024 'icq' => new external_value(core_user
::get_property_type('icq'), 'icq number', VALUE_OPTIONAL
),
1025 'skype' => new external_value(core_user
::get_property_type('skype'), 'skype id', VALUE_OPTIONAL
),
1026 'yahoo' => new external_value(core_user
::get_property_type('yahoo'), 'yahoo id', VALUE_OPTIONAL
),
1027 'aim' => new external_value(core_user
::get_property_type('aim'), 'aim id', VALUE_OPTIONAL
),
1028 'msn' => new external_value(core_user
::get_property_type('msn'), 'msn number', VALUE_OPTIONAL
),
1029 'department' => new external_value(core_user
::get_property_type('department'), 'department', VALUE_OPTIONAL
),
1030 'institution' => new external_value(core_user
::get_property_type('institution'), 'institution', VALUE_OPTIONAL
),
1031 'idnumber' => new external_value(core_user
::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL
),
1032 'interests' => new external_value(PARAM_TEXT
, 'user interests (separated by commas)', VALUE_OPTIONAL
),
1033 'firstaccess' => new external_value(core_user
::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL
),
1034 'lastaccess' => new external_value(core_user
::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL
),
1035 'auth' => new external_value(core_user
::get_property_type('auth'), 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL
),
1036 '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
),
1037 'confirmed' => new external_value(core_user
::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL
),
1038 'lang' => new external_value(core_user
::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL
),
1039 'calendartype' => new external_value(core_user
::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL
),
1040 'theme' => new external_value(core_user
::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL
),
1041 'timezone' => new external_value(core_user
::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL
),
1042 'mailformat' => new external_value(core_user
::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL
),
1043 'description' => new external_value(core_user
::get_property_type('description'), 'User profile description', VALUE_OPTIONAL
),
1044 'descriptionformat' => new external_format_value(core_user
::get_property_type('descriptionformat'), VALUE_OPTIONAL
),
1045 'city' => new external_value(core_user
::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL
),
1046 'url' => new external_value(core_user
::get_property_type('url'), 'URL of the user', VALUE_OPTIONAL
),
1047 'country' => new external_value(core_user
::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
1048 'profileimageurlsmall' => new external_value(PARAM_URL
, 'User image profile URL - small version'),
1049 'profileimageurl' => new external_value(PARAM_URL
, 'User image profile URL - big version'),
1050 'customfields' => new external_multiple_structure(
1051 new external_single_structure(
1053 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The type of the custom field - text field, checkbox...'),
1054 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
1055 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
1056 'shortname' => new external_value(PARAM_RAW
, 'The shortname of the custom field - to be able to build the field class in the code'),
1058 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL
),
1059 'preferences' => new external_multiple_structure(
1060 new external_single_structure(
1062 'name' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the preferences'),
1063 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
1065 ), 'Users preferences', VALUE_OPTIONAL
)
1067 if (!empty($additionalfields)) {
1068 $userfields = array_merge($userfields, $additionalfields);
1070 return new external_single_structure($userfields);
1074 * Returns description of method parameters
1076 * @return external_function_parameters
1079 public static function add_user_private_files_parameters() {
1080 return new external_function_parameters(
1082 'draftid' => new external_value(PARAM_INT
, 'draft area id')
1088 * Copy files from a draft area to users private files area.
1090 * @throws invalid_parameter_exception
1091 * @param int $draftid Id of a draft area containing files.
1092 * @return array An array of warnings
1095 public static function add_user_private_files($draftid) {
1097 require_once($CFG->libdir
. "/filelib.php");
1099 $params = self
::validate_parameters(self
::add_user_private_files_parameters(), array('draftid' => $draftid));
1101 if (isguestuser()) {
1102 throw new invalid_parameter_exception('Guest users cannot upload files');
1105 $context = context_user
::instance($USER->id
);
1106 require_capability('moodle/user:manageownfiles', $context);
1108 $maxbytes = $CFG->userquota
;
1109 $maxareabytes = $CFG->userquota
;
1110 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1111 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
1112 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED
;
1115 $options = array('subdirs' => 1,
1116 'maxbytes' => $maxbytes,
1118 'areamaxbytes' => $maxareabytes);
1120 file_merge_files_from_draft_area_into_filearea($draftid, $context->id
, 'user', 'private', 0, $options);
1126 * Returns description of method result value
1128 * @return external_description
1131 public static function add_user_private_files_returns() {
1136 * Returns description of method parameters.
1138 * @return external_function_parameters
1141 public static function add_user_device_parameters() {
1142 return new external_function_parameters(
1144 'appid' => new external_value(PARAM_NOTAGS
, 'the app id, usually something like com.moodle.moodlemobile'),
1145 'name' => new external_value(PARAM_NOTAGS
, 'the device name, \'occam\' or \'iPhone\' etc.'),
1146 'model' => new external_value(PARAM_NOTAGS
, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1147 'platform' => new external_value(PARAM_NOTAGS
, 'the device platform \'iOS\' or \'Android\' etc.'),
1148 'version' => new external_value(PARAM_NOTAGS
, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1149 'pushid' => new external_value(PARAM_RAW
, 'the device PUSH token/key/identifier/registration id'),
1150 'uuid' => new external_value(PARAM_RAW
, 'the device UUID')
1156 * Add a user device in Moodle database (for PUSH notifications usually).
1158 * @throws moodle_exception
1159 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1160 * @param string $name The device name, occam or iPhone etc.
1161 * @param string $model The device model Nexus4 or iPad1.1 etc.
1162 * @param string $platform The device platform iOs or Android etc.
1163 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1164 * @param string $pushid The device PUSH token/key/identifier/registration id.
1165 * @param string $uuid The device UUID.
1166 * @return array List of possible warnings.
1169 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1170 global $CFG, $USER, $DB;
1171 require_once($CFG->dirroot
. "/user/lib.php");
1173 $params = self
::validate_parameters(self
::add_user_device_parameters(),
1174 array('appid' => $appid,
1177 'platform' => $platform,
1178 'version' => $version,
1179 'pushid' => $pushid,
1183 $warnings = array();
1185 // Prevent duplicate keys for users.
1186 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id
))) {
1187 $warnings['warning'][] = array(
1188 'item' => $params['pushid'],
1189 'warningcode' => 'existingkeyforthisuser',
1190 'message' => 'This key is already stored for this user'
1195 // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1196 // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1197 if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1198 'appid' => $params['appid'], 'userid' => $USER->id
))) {
1200 foreach ($userdevices as $userdevice) {
1201 $userdevice->version
= $params['version']; // Maybe the user upgraded the device.
1202 $userdevice->pushid
= $params['pushid'];
1203 $userdevice->timemodified
= time();
1204 $DB->update_record('user_devices', $userdevice);
1208 $userdevice = new stdclass
;
1209 $userdevice->userid
= $USER->id
;
1210 $userdevice->appid
= $params['appid'];
1211 $userdevice->name
= $params['name'];
1212 $userdevice->model
= $params['model'];
1213 $userdevice->platform
= $params['platform'];
1214 $userdevice->version
= $params['version'];
1215 $userdevice->pushid
= $params['pushid'];
1216 $userdevice->uuid
= $params['uuid'];
1217 $userdevice->timecreated
= time();
1218 $userdevice->timemodified
= $userdevice->timecreated
;
1220 if (!$DB->insert_record('user_devices', $userdevice)) {
1221 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1229 * Returns description of method result value.
1231 * @return external_multiple_structure
1234 public static function add_user_device_returns() {
1235 return new external_multiple_structure(
1236 new external_warnings()
1241 * Returns description of method parameters.
1243 * @return external_function_parameters
1246 public static function remove_user_device_parameters() {
1247 return new external_function_parameters(
1249 'uuid' => new external_value(PARAM_RAW
, 'the device UUID'),
1250 'appid' => new external_value(PARAM_NOTAGS
,
1251 'the app id, if empty devices matching the UUID for the user will be removed',
1258 * Remove a user device from the Moodle database (for PUSH notifications usually).
1260 * @param string $uuid The device UUID.
1261 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1262 * @return array List of possible warnings and removal status.
1265 public static function remove_user_device($uuid, $appid = "") {
1267 require_once($CFG->dirroot
. "/user/lib.php");
1269 $params = self
::validate_parameters(self
::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1271 $context = context_system
::instance();
1272 self
::validate_context($context);
1274 // Warnings array, it can be empty at the end but is mandatory.
1275 $warnings = array();
1277 $removed = user_remove_user_device($params['uuid'], $params['appid']);
1280 $warnings[] = array(
1281 'item' => $params['uuid'],
1282 'warningcode' => 'devicedoesnotexist',
1283 'message' => 'The device doesn\'t exists in the database'
1288 'removed' => $removed,
1289 'warnings' => $warnings
1296 * Returns description of method result value.
1298 * @return external_multiple_structure
1301 public static function remove_user_device_returns() {
1302 return new external_single_structure(
1304 'removed' => new external_value(PARAM_BOOL
, 'True if removed, false if not removed because it doesn\'t exists'),
1305 'warnings' => new external_warnings(),
1311 * Returns description of method parameters
1313 * @return external_function_parameters
1316 public static function view_user_list_parameters() {
1317 return new external_function_parameters(
1319 'courseid' => new external_value(PARAM_INT
, 'id of the course, 0 for site')
1325 * Trigger the user_list_viewed event.
1327 * @param int $courseid id of course
1328 * @return array of warnings and status result
1330 * @throws moodle_exception
1332 public static function view_user_list($courseid) {
1334 require_once($CFG->dirroot
. "/user/lib.php");
1336 $params = self
::validate_parameters(self
::view_user_list_parameters(),
1338 'courseid' => $courseid
1341 $warnings = array();
1343 if (empty($params['courseid'])) {
1344 $params['courseid'] = SITEID
;
1347 $course = get_course($params['courseid']);
1349 if ($course->id
== SITEID
) {
1350 $context = context_system
::instance();
1352 $context = context_course
::instance($course->id
);
1354 self
::validate_context($context);
1356 if ($course->id
== SITEID
) {
1357 require_capability('moodle/site:viewparticipants', $context);
1359 require_capability('moodle/course:viewparticipants', $context);
1362 user_list_view($course, $context);
1365 $result['status'] = true;
1366 $result['warnings'] = $warnings;
1371 * Returns description of method result value
1373 * @return external_description
1376 public static function view_user_list_returns() {
1377 return new external_single_structure(
1379 'status' => new external_value(PARAM_BOOL
, 'status: true if success'),
1380 'warnings' => new external_warnings()
1386 * Returns description of method parameters
1388 * @return external_function_parameters
1391 public static function view_user_profile_parameters() {
1392 return new external_function_parameters(
1394 'userid' => new external_value(PARAM_INT
, 'id of the user, 0 for current user', VALUE_REQUIRED
),
1395 'courseid' => new external_value(PARAM_INT
, 'id of the course, default site course', VALUE_DEFAULT
, 0)
1401 * Trigger the user profile viewed event.
1403 * @param int $userid id of user
1404 * @param int $courseid id of course
1405 * @return array of warnings and status result
1407 * @throws moodle_exception
1409 public static function view_user_profile($userid, $courseid = 0) {
1411 require_once($CFG->dirroot
. "/user/profile/lib.php");
1413 $params = self
::validate_parameters(self
::view_user_profile_parameters(),
1415 'userid' => $userid,
1416 'courseid' => $courseid
1419 $warnings = array();
1421 if (empty($params['userid'])) {
1422 $params['userid'] = $USER->id
;
1425 if (empty($params['courseid'])) {
1426 $params['courseid'] = SITEID
;
1429 $course = get_course($params['courseid']);
1430 $user = core_user
::get_user($params['userid'], '*', MUST_EXIST
);
1431 core_user
::require_active_user($user);
1433 if ($course->id
== SITEID
) {
1434 $coursecontext = context_system
::instance();;
1436 $coursecontext = context_course
::instance($course->id
);
1438 self
::validate_context($coursecontext);
1440 $currentuser = $USER->id
== $user->id
;
1441 $usercontext = context_user
::instance($user->id
);
1443 if (!$currentuser and
1444 !has_capability('moodle/user:viewdetails', $coursecontext) and
1445 !has_capability('moodle/user:viewdetails', $usercontext)) {
1446 throw new moodle_exception('cannotviewprofile');
1449 // Case like user/profile.php.
1450 if ($course->id
== SITEID
) {
1451 profile_view($user, $usercontext);
1453 // Case like user/view.php.
1454 if (!$currentuser and !can_access_course($course, $user, '', true)) {
1455 throw new moodle_exception('notenrolledprofile');
1458 profile_view($user, $coursecontext, $course);
1462 $result['status'] = true;
1463 $result['warnings'] = $warnings;
1468 * Returns description of method result value
1470 * @return external_description
1473 public static function view_user_profile_returns() {
1474 return new external_single_structure(
1476 'status' => new external_value(PARAM_BOOL
, 'status: true if success'),
1477 'warnings' => new external_warnings()
1483 * Returns description of method parameters
1485 * @return external_function_parameters
1488 public static function get_user_preferences_parameters() {
1489 return new external_function_parameters(
1491 'name' => new external_value(PARAM_RAW
, 'preference name, empty for all', VALUE_DEFAULT
, ''),
1492 'userid' => new external_value(PARAM_INT
, 'id of the user, default to current user', VALUE_DEFAULT
, 0)
1498 * Return user preferences.
1500 * @param string $name preference name, empty for all
1501 * @param int $userid id of the user, 0 for current user
1502 * @return array of warnings and preferences
1504 * @throws moodle_exception
1506 public static function get_user_preferences($name = '', $userid = 0) {
1509 $params = self
::validate_parameters(self
::get_user_preferences_parameters(),
1514 $preferences = array();
1515 $warnings = array();
1517 $context = context_system
::instance();
1518 self
::validate_context($context);
1520 if (empty($params['name'])) {
1523 if (empty($params['userid'])) {
1526 $user = core_user
::get_user($params['userid'], '*', MUST_EXIST
);
1527 core_user
::require_active_user($user);
1528 if ($user->id
!= $USER->id
) {
1529 // Only admins can retrieve other users preferences.
1530 require_capability('moodle/site:config', $context);
1534 $userpreferences = get_user_preferences($name, null, $user);
1535 // Check if we received just one preference.
1536 if (!is_array($userpreferences)) {
1537 $userpreferences = array($name => $userpreferences);
1540 foreach ($userpreferences as $name => $value) {
1541 $preferences[] = array(
1548 $result['preferences'] = $preferences;
1549 $result['warnings'] = $warnings;
1554 * Returns description of method result value
1556 * @return external_description
1559 public static function get_user_preferences_returns() {
1560 return new external_single_structure(
1562 'preferences' => new external_multiple_structure(
1563 new external_single_structure(
1565 'name' => new external_value(PARAM_RAW
, 'The name of the preference'),
1566 'value' => new external_value(PARAM_RAW
, 'The value of the preference'),
1569 'User custom fields (also known as user profile fields)'
1571 'warnings' => new external_warnings()
1577 * Returns description of method parameters
1579 * @return external_function_parameters
1582 public static function update_picture_parameters() {
1583 return new external_function_parameters(
1585 'draftitemid' => new external_value(PARAM_INT
, 'Id of the user draft file to use as image'),
1586 'delete' => new external_value(PARAM_BOOL
, 'If we should delete the user picture', VALUE_DEFAULT
, false),
1587 'userid' => new external_value(PARAM_INT
, 'Id of the user, 0 for current user', VALUE_DEFAULT
, 0)
1593 * Update or delete the user picture in the site
1595 * @param int $draftitemid id of the user draft file to use as image
1596 * @param bool $delete if we should delete the user picture
1597 * @param int $userid id of the user, 0 for current user
1598 * @return array warnings and success status
1600 * @throws moodle_exception
1602 public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1603 global $CFG, $USER, $PAGE;
1605 $params = self
::validate_parameters(
1606 self
::update_picture_parameters(),
1608 'draftitemid' => $draftitemid,
1609 'delete' => $delete,
1614 $context = context_system
::instance();
1615 self
::validate_context($context);
1617 if (!empty($CFG->disableuserimages
)) {
1618 throw new moodle_exception('userimagesdisabled', 'admin');
1621 if (empty($params['userid']) or $params['userid'] == $USER->id
) {
1623 require_capability('moodle/user:editownprofile', $context);
1625 $user = core_user
::get_user($params['userid'], '*', MUST_EXIST
);
1626 core_user
::require_active_user($user);
1627 $personalcontext = context_user
::instance($user->id
);
1629 require_capability('moodle/user:editprofile', $personalcontext);
1630 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
1631 throw new moodle_exception('useradmineditadmin');
1635 // Load the appropriate auth plugin.
1636 $userauth = get_auth_plugin($user->auth
);
1637 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1638 throw new moodle_exception('noprofileedit', 'auth');
1641 $filemanageroptions = array('maxbytes' => $CFG->maxbytes
, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image');
1642 $user->deletepicture
= $params['delete'];
1643 $user->imagefile
= $params['draftitemid'];
1644 $success = core_user
::update_picture($user, $filemanageroptions);
1647 'success' => $success,
1648 'warnings' => array(),
1651 $userpicture = new user_picture(core_user
::get_user($user->id
));
1652 $userpicture->size
= 1; // Size f1.
1653 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1659 * Returns description of method result value
1661 * @return external_description
1664 public static function update_picture_returns() {
1665 return new external_single_structure(
1667 'success' => new external_value(PARAM_BOOL
, 'True if the image was updated, false otherwise.'),
1668 'profileimageurl' => new external_value(PARAM_URL
, 'New profile user image url', VALUE_OPTIONAL
),
1669 'warnings' => new external_warnings()
1675 * Returns description of method parameters
1677 * @return external_function_parameters
1680 public static function set_user_preferences_parameters() {
1681 return new external_function_parameters(
1683 'preferences' => new external_multiple_structure(
1684 new external_single_structure(
1686 'name' => new external_value(PARAM_RAW
, 'The name of the preference'),
1687 'value' => new external_value(PARAM_RAW
, 'The value of the preference'),
1688 'userid' => new external_value(PARAM_INT
, 'Id of the user to set the preference'),
1697 * Set user preferences.
1699 * @param array $preferences list of preferences including name, value and userid
1700 * @return array of warnings and preferences saved
1702 * @throws moodle_exception
1704 public static function set_user_preferences($preferences) {
1707 $params = self
::validate_parameters(self
::set_user_preferences_parameters(), array('preferences' => $preferences));
1708 $warnings = array();
1711 $context = context_system
::instance();
1712 self
::validate_context($context);
1713 require_capability('moodle/site:config', $context);
1715 $userscache = array();
1716 foreach ($params['preferences'] as $pref) {
1717 // Check to which user set the preference.
1718 if (!empty($userscache[$pref['userid']])) {
1719 $user = $userscache[$pref['userid']];
1722 $user = core_user
::get_user($pref['userid'], '*', MUST_EXIST
);
1723 core_user
::require_active_user($user);
1724 $userscache[$pref['userid']] = $user;
1725 } catch (Exception
$e) {
1726 $warnings[] = array(
1728 'itemid' => $pref['userid'],
1729 'warningcode' => 'invaliduser',
1730 'message' => $e->getMessage()
1737 set_user_preference($pref['name'], $pref['value'], $user);
1739 'name' => $pref['name'],
1740 'userid' => $user->id
,
1742 } catch (Exception
$e) {
1743 $warnings[] = array(
1745 'itemid' => $user->id
,
1746 'warningcode' => 'errorsavingpreference',
1747 'message' => $e->getMessage()
1753 $result['saved'] = $saved;
1754 $result['warnings'] = $warnings;
1759 * Returns description of method result value
1761 * @return external_description
1764 public static function set_user_preferences_returns() {
1765 return new external_single_structure(
1767 'saved' => new external_multiple_structure(
1768 new external_single_structure(
1770 'name' => new external_value(PARAM_RAW
, 'The name of the preference'),
1771 'userid' => new external_value(PARAM_INT
, 'The user the preference was set for'),
1773 ), 'Preferences saved'
1775 'warnings' => new external_warnings()
1781 * Returns description of method parameters.
1783 * @return external_function_parameters
1786 public static function agree_site_policy_parameters() {
1787 return new external_function_parameters(array());
1791 * Agree the site policy for the current user.
1793 * @return array of warnings and status result
1795 * @throws moodle_exception
1797 public static function agree_site_policy() {
1798 global $CFG, $DB, $USER;
1800 $warnings = array();
1802 $context = context_system
::instance();
1804 // We expect an exception here since the user didn't agree the site policy yet.
1805 self
::validate_context($context);
1806 } catch (Exception
$e) {
1807 // We are expecting only a sitepolicynotagreed exception.
1808 if (!($e instanceof moodle_exception
) or $e->errorcode
!= 'sitepolicynotagreed') {
1809 // In case we receive a different exception, throw it.
1814 if (empty($CFG->sitepolicy
)) {
1816 $warnings[] = array(
1818 'itemid' => $USER->id
,
1819 'warningcode' => 'nositepolicy',
1820 'message' => 'The site does not have a site policy configured.'
1822 } else if (!empty($USER->policyagreed
)) {
1824 $warnings[] = array(
1826 'itemid' => $USER->id
,
1827 'warningcode' => 'alreadyagreed',
1828 'message' => 'The user already agreed the site policy.'
1831 $DB->set_field('user', 'policyagreed', 1, array('id' => $USER->id
));
1832 $USER->policyagreed
= 1;
1837 $result['status'] = $status;
1838 $result['warnings'] = $warnings;
1843 * Returns description of method result value.
1845 * @return external_description
1848 public static function agree_site_policy_returns() {
1849 return new external_single_structure(
1851 'status' => new external_value(PARAM_BOOL
, 'Status: true only if we set the policyagreed to 1 for the user'),
1852 'warnings' => new external_warnings()