MDL-63020 tests: ensure that searching for is null values also works ok
[moodle.git] / user / externallib.php
blob4ba0f6b4278bc45c91cbcbafea6c8c0ffca54ff8
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * External user API
20 * @package core_user
21 * @category external
22 * @copyright 2009 Petr Skodak
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 require_once("$CFG->libdir/externallib.php");
30 /**
31 * User external functions
33 * @package core_user
34 * @category external
35 * @copyright 2011 Jerome Mouneyrac
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 * @since Moodle 2.2
39 class core_user_external extends external_api {
41 /**
42 * Returns description of method parameters
44 * @return external_function_parameters
45 * @since Moodle 2.2
47 public static function create_users_parameters() {
48 global $CFG;
50 return new external_function_parameters(
51 array(
52 'users' => new external_multiple_structure(
53 new external_single_structure(
54 array(
55 'username' =>
56 new external_value(core_user::get_property_type('username'), 'Username policy is defined in Moodle security config.'),
57 'password' =>
58 new external_value(core_user::get_property_type('password'), 'Plain text password consisting of any characters', VALUE_OPTIONAL),
59 'createpassword' =>
60 new external_value(PARAM_BOOL, 'True if password should be created and mailed to user.',
61 VALUE_OPTIONAL),
62 'firstname' =>
63 new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user'),
64 'lastname' =>
65 new external_value(core_user::get_property_type('lastname'), 'The family name of the user'),
66 'email' =>
67 new external_value(core_user::get_property_type('email'), 'A valid and unique email address'),
68 'auth' =>
69 new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_DEFAULT,
70 'manual', core_user::get_property_null('auth')),
71 'idnumber' =>
72 new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution',
73 VALUE_DEFAULT, ''),
74 'lang' =>
75 new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_DEFAULT,
76 core_user::get_property_default('lang'), core_user::get_property_null('lang')),
77 'calendartype' =>
78 new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server',
79 VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
80 'theme' =>
81 new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server',
82 VALUE_OPTIONAL),
83 'timezone' =>
84 new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default',
85 VALUE_OPTIONAL),
86 'mailformat' =>
87 new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc',
88 VALUE_OPTIONAL),
89 'description' =>
90 new external_value(core_user::get_property_type('description'), 'User profile description, no HTML', VALUE_OPTIONAL),
91 'city' =>
92 new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
93 'country' =>
94 new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
95 'firstnamephonetic' =>
96 new external_value(core_user::get_property_type('firstnamephonetic'), 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
97 'lastnamephonetic' =>
98 new external_value(core_user::get_property_type('lastnamephonetic'), 'The family name phonetically of the user', VALUE_OPTIONAL),
99 'middlename' =>
100 new external_value(core_user::get_property_type('middlename'), 'The middle name of the user', VALUE_OPTIONAL),
101 'alternatename' =>
102 new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user', VALUE_OPTIONAL),
103 'preferences' => new external_multiple_structure(
104 new external_single_structure(
105 array(
106 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
107 'value' => new external_value(PARAM_RAW, 'The value of the preference')
109 ), 'User preferences', VALUE_OPTIONAL),
110 'customfields' => new external_multiple_structure(
111 new external_single_structure(
112 array(
113 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
114 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
116 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
125 * Create one or more users.
127 * @throws invalid_parameter_exception
128 * @param array $users An array of users to create.
129 * @return array An array of arrays
130 * @since Moodle 2.2
132 public static function create_users($users) {
133 global $CFG, $DB;
134 require_once($CFG->dirroot."/lib/weblib.php");
135 require_once($CFG->dirroot."/user/lib.php");
136 require_once($CFG->dirroot."/user/editlib.php");
137 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
139 // Ensure the current user is allowed to run this function.
140 $context = context_system::instance();
141 self::validate_context($context);
142 require_capability('moodle/user:create', $context);
144 // Do basic automatic PARAM checks on incoming data, using params description.
145 // If any problems are found then exceptions are thrown with helpful error messages.
146 $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
148 $availableauths = core_component::get_plugin_list('auth');
149 unset($availableauths['mnet']); // These would need mnethostid too.
150 unset($availableauths['webservice']); // We do not want new webservice users for now.
152 $availablethemes = core_component::get_plugin_list('theme');
153 $availablelangs = get_string_manager()->get_list_of_translations();
155 $transaction = $DB->start_delegated_transaction();
157 $userids = array();
158 $createpassword = false;
159 foreach ($params['users'] as $user) {
160 // Make sure that the username, firstname and lastname are not blank.
161 foreach (array('username', 'firstname', 'lastname') as $fieldname) {
162 if (trim($user[$fieldname]) === '') {
163 throw new invalid_parameter_exception('The field '.$fieldname.' cannot be blank');
167 // Make sure that the username doesn't already exist.
168 if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
169 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
172 // Make sure auth is valid.
173 if (empty($availableauths[$user['auth']])) {
174 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
177 // Make sure lang is valid.
178 if (empty($availablelangs[$user['lang']])) {
179 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
182 // Make sure lang is valid.
183 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
184 // so no default value
185 // We need to test if the client sent it
186 // => !empty($user['theme']).
187 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
190 // Make sure we have a password or have to create one.
191 if (empty($user['password']) && empty($user['createpassword'])) {
192 throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
195 $user['confirmed'] = true;
196 $user['mnethostid'] = $CFG->mnet_localhost_id;
198 // Start of user info validation.
199 // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
200 if (!validate_email($user['email'])) {
201 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
202 } else if (empty($CFG->allowaccountssameemail) &&
203 $DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
204 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
206 // End of user info validation.
208 $createpassword = !empty($user['createpassword']);
209 unset($user['createpassword']);
210 if ($createpassword) {
211 $user['password'] = '';
212 $updatepassword = false;
213 } else {
214 $updatepassword = true;
217 // Create the user data now!
218 $user['id'] = user_create_user($user, $updatepassword, false);
220 // Custom fields.
221 if (!empty($user['customfields'])) {
222 foreach ($user['customfields'] as $customfield) {
223 // Profile_save_data() saves profile file it's expecting a user with the correct id,
224 // and custom field to be named profile_field_"shortname".
225 $user["profile_field_".$customfield['type']] = $customfield['value'];
227 profile_save_data((object) $user);
230 if ($createpassword) {
231 $userobject = (object)$user;
232 setnew_password_and_mail($userobject);
233 unset_user_preference('create_password', $userobject);
234 set_user_preference('auth_forcepasswordchange', 1, $userobject);
237 // Trigger event.
238 \core\event\user_created::create_from_userid($user['id'])->trigger();
240 // Preferences.
241 if (!empty($user['preferences'])) {
242 $userpref = (object)$user;
243 foreach ($user['preferences'] as $preference) {
244 $userpref->{'preference_'.$preference['type']} = $preference['value'];
246 useredit_update_user_preference($userpref);
249 $userids[] = array('id' => $user['id'], 'username' => $user['username']);
252 $transaction->allow_commit();
254 return $userids;
258 * Returns description of method result value
260 * @return external_description
261 * @since Moodle 2.2
263 public static function create_users_returns() {
264 return new external_multiple_structure(
265 new external_single_structure(
266 array(
267 'id' => new external_value(core_user::get_property_type('id'), 'user id'),
268 'username' => new external_value(core_user::get_property_type('username'), 'user name'),
276 * Returns description of method parameters
278 * @return external_function_parameters
279 * @since Moodle 2.2
281 public static function delete_users_parameters() {
282 return new external_function_parameters(
283 array(
284 'userids' => new external_multiple_structure(new external_value(core_user::get_property_type('id'), 'user ID')),
290 * Delete users
292 * @throws moodle_exception
293 * @param array $userids
294 * @return null
295 * @since Moodle 2.2
297 public static function delete_users($userids) {
298 global $CFG, $DB, $USER;
299 require_once($CFG->dirroot."/user/lib.php");
301 // Ensure the current user is allowed to run this function.
302 $context = context_system::instance();
303 require_capability('moodle/user:delete', $context);
304 self::validate_context($context);
306 $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
308 $transaction = $DB->start_delegated_transaction();
310 foreach ($params['userids'] as $userid) {
311 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
312 // Must not allow deleting of admins or self!!!
313 if (is_siteadmin($user)) {
314 throw new moodle_exception('useradminodelete', 'error');
316 if ($USER->id == $user->id) {
317 throw new moodle_exception('usernotdeletederror', 'error');
319 user_delete_user($user);
322 $transaction->allow_commit();
324 return null;
328 * Returns description of method result value
330 * @return null
331 * @since Moodle 2.2
333 public static function delete_users_returns() {
334 return null;
338 * Returns description of method parameters.
340 * @return external_function_parameters
341 * @since Moodle 3.2
343 public static function update_user_preferences_parameters() {
344 return new external_function_parameters(
345 array(
346 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
347 'emailstop' => new external_value(core_user::get_property_type('emailstop'),
348 'Enable or disable notifications for this user', VALUE_DEFAULT, null),
349 'preferences' => new external_multiple_structure(
350 new external_single_structure(
351 array(
352 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
353 'value' => new external_value(PARAM_RAW, 'The value of the preference')
355 ), 'User preferences', VALUE_DEFAULT, array()
362 * Update the user's preferences.
364 * @param int $userid
365 * @param bool|null $emailstop
366 * @param array $preferences
367 * @return null
368 * @since Moodle 3.2
370 public static function update_user_preferences($userid, $emailstop = null, $preferences = array()) {
371 global $USER, $CFG;
373 require_once($CFG->dirroot . '/user/lib.php');
374 require_once($CFG->dirroot . '/user/editlib.php');
375 require_once($CFG->dirroot . '/message/lib.php');
377 if (empty($userid)) {
378 $userid = $USER->id;
381 $systemcontext = context_system::instance();
382 self::validate_context($systemcontext);
383 $params = array(
384 'userid' => $userid,
385 'emailstop' => $emailstop,
386 'preferences' => $preferences
388 self::validate_parameters(self::update_user_preferences_parameters(), $params);
390 // Preferences.
391 if (!empty($preferences)) {
392 $userpref = ['id' => $userid];
393 foreach ($preferences as $preference) {
394 $userpref['preference_' . $preference['type']] = $preference['value'];
396 useredit_update_user_preference($userpref);
399 // Check if they want to update the email.
400 if ($emailstop !== null) {
401 $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST);
402 core_user::require_active_user($otheruser);
403 if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) {
404 $user = new stdClass();
405 $user->id = $userid;
406 $user->emailstop = $emailstop;
407 user_update_user($user);
409 // Update the $USER if we should.
410 if ($userid == $USER->id) {
411 $USER->emailstop = $emailstop;
416 return null;
420 * Returns description of method result value
422 * @return null
423 * @since Moodle 3.2
425 public static function update_user_preferences_returns() {
426 return null;
430 * Returns description of method parameters
432 * @return external_function_parameters
433 * @since Moodle 2.2
435 public static function update_users_parameters() {
436 return new external_function_parameters(
437 array(
438 'users' => new external_multiple_structure(
439 new external_single_structure(
440 array(
441 'id' =>
442 new external_value(core_user::get_property_type('id'), 'ID of the user'),
443 'username' =>
444 new external_value(core_user::get_property_type('username'), 'Username policy is defined in Moodle security config.',
445 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
446 'password' =>
447 new external_value(core_user::get_property_type('password'), 'Plain text password consisting of any characters', VALUE_OPTIONAL,
448 '', NULL_NOT_ALLOWED),
449 'firstname' =>
450 new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL, '',
451 NULL_NOT_ALLOWED),
452 'lastname' =>
453 new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
454 'email' =>
455 new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL, '',
456 NULL_NOT_ALLOWED),
457 'auth' =>
458 new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL, '',
459 NULL_NOT_ALLOWED),
460 'suspended' =>
461 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),
462 'idnumber' =>
463 new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution',
464 VALUE_OPTIONAL),
465 'lang' =>
466 new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
467 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
468 'calendartype' =>
469 new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server',
470 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
471 'theme' =>
472 new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server',
473 VALUE_OPTIONAL),
474 'timezone' =>
475 new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default',
476 VALUE_OPTIONAL),
477 'mailformat' =>
478 new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc',
479 VALUE_OPTIONAL),
480 'description' =>
481 new external_value(core_user::get_property_type('description'), 'User profile description, no HTML', VALUE_OPTIONAL),
482 'city' =>
483 new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
484 'country' =>
485 new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
486 'firstnamephonetic' =>
487 new external_value(core_user::get_property_type('firstnamephonetic'), 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
488 'lastnamephonetic' =>
489 new external_value(core_user::get_property_type('lastnamephonetic'), 'The family name phonetically of the user', VALUE_OPTIONAL),
490 'middlename' =>
491 new external_value(core_user::get_property_type('middlename'), 'The middle name of the user', VALUE_OPTIONAL),
492 'alternatename' =>
493 new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user', VALUE_OPTIONAL),
494 'userpicture' =>
495 new external_value(PARAM_INT, 'The itemid where the new user picture '.
496 'has been uploaded to, 0 to delete', VALUE_OPTIONAL),
497 'customfields' => new external_multiple_structure(
498 new external_single_structure(
499 array(
500 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
501 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
503 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
504 'preferences' => new external_multiple_structure(
505 new external_single_structure(
506 array(
507 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
508 'value' => new external_value(PARAM_RAW, 'The value of the preference')
510 ), 'User preferences', VALUE_OPTIONAL),
519 * Update users
521 * @param array $users
522 * @return null
523 * @since Moodle 2.2
525 public static function update_users($users) {
526 global $CFG, $DB, $USER;
527 require_once($CFG->dirroot."/user/lib.php");
528 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
529 require_once($CFG->dirroot.'/user/editlib.php');
531 // Ensure the current user is allowed to run this function.
532 $context = context_system::instance();
533 require_capability('moodle/user:update', $context);
534 self::validate_context($context);
536 $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
538 $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
539 'subdirs' => 0,
540 'maxfiles' => 1,
541 'accepted_types' => 'web_image');
543 $transaction = $DB->start_delegated_transaction();
545 foreach ($params['users'] as $user) {
546 // First check the user exists.
547 if (!$existinguser = core_user::get_user($user['id'])) {
548 continue;
550 // Check if we are trying to update an admin.
551 if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
552 continue;
554 // Other checks (deleted, remote or guest users).
555 if ($existinguser->deleted or is_mnet_remote_user($existinguser) or isguestuser($existinguser->id)) {
556 continue;
558 // Check duplicated emails.
559 if (isset($user['email']) && $user['email'] !== $existinguser->email) {
560 if (!validate_email($user['email'])) {
561 continue;
562 } else if (empty($CFG->allowaccountssameemail) &&
563 $DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $CFG->mnet_localhost_id))) {
564 continue;
568 user_update_user($user, true, false);
570 // Update user picture if it was specified for this user.
571 if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
572 $userobject = (object)$user;
574 $userobject->deletepicture = null;
576 if ($user['userpicture'] == 0) {
577 $userobject->deletepicture = true;
578 } else {
579 $userobject->imagefile = $user['userpicture'];
582 core_user::update_picture($userobject, $filemanageroptions);
585 // Update user custom fields.
586 if (!empty($user['customfields'])) {
588 foreach ($user['customfields'] as $customfield) {
589 // Profile_save_data() saves profile file it's expecting a user with the correct id,
590 // and custom field to be named profile_field_"shortname".
591 $user["profile_field_".$customfield['type']] = $customfield['value'];
593 profile_save_data((object) $user);
596 // Trigger event.
597 \core\event\user_updated::create_from_userid($user['id'])->trigger();
599 // Preferences.
600 if (!empty($user['preferences'])) {
601 $userpref = clone($existinguser);
602 foreach ($user['preferences'] as $preference) {
603 $userpref->{'preference_'.$preference['type']} = $preference['value'];
605 useredit_update_user_preference($userpref);
607 if (isset($user['suspended']) and $user['suspended']) {
608 \core\session\manager::kill_user_sessions($user['id']);
612 $transaction->allow_commit();
614 return null;
618 * Returns description of method result value
620 * @return null
621 * @since Moodle 2.2
623 public static function update_users_returns() {
624 return null;
628 * Returns description of method parameters
630 * @return external_function_parameters
631 * @since Moodle 2.4
633 public static function get_users_by_field_parameters() {
634 return new external_function_parameters(
635 array(
636 'field' => new external_value(PARAM_ALPHA, 'the search field can be
637 \'id\' or \'idnumber\' or \'username\' or \'email\''),
638 'values' => new external_multiple_structure(
639 new external_value(PARAM_RAW, 'the value to match'))
645 * Get user information for a unique field.
647 * @throws coding_exception
648 * @throws invalid_parameter_exception
649 * @param string $field
650 * @param array $values
651 * @return array An array of arrays containg user profiles.
652 * @since Moodle 2.4
654 public static function get_users_by_field($field, $values) {
655 global $CFG, $USER, $DB;
656 require_once($CFG->dirroot . "/user/lib.php");
658 $params = self::validate_parameters(self::get_users_by_field_parameters(),
659 array('field' => $field, 'values' => $values));
661 // This array will keep all the users that are allowed to be searched,
662 // according to the current user's privileges.
663 $cleanedvalues = array();
665 switch ($field) {
666 case 'id':
667 $paramtype = core_user::get_property_type('id');
668 break;
669 case 'idnumber':
670 $paramtype = core_user::get_property_type('idnumber');
671 break;
672 case 'username':
673 $paramtype = core_user::get_property_type('username');
674 break;
675 case 'email':
676 $paramtype = core_user::get_property_type('email');
677 break;
678 default:
679 throw new coding_exception('invalid field parameter',
680 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
683 // Clean the values.
684 foreach ($values as $value) {
685 $cleanedvalue = clean_param($value, $paramtype);
686 if ( $value != $cleanedvalue) {
687 throw new invalid_parameter_exception('The field \'' . $field .
688 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
690 $cleanedvalues[] = $cleanedvalue;
693 // Retrieve the users.
694 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
696 $context = context_system::instance();
697 self::validate_context($context);
699 // Finally retrieve each users information.
700 $returnedusers = array();
701 foreach ($users as $user) {
702 $userdetails = user_get_user_details_courses($user);
704 // Return the user only if the searched field is returned.
705 // Otherwise it means that the $USER was not allowed to search the returned user.
706 if (!empty($userdetails) and !empty($userdetails[$field])) {
707 $returnedusers[] = $userdetails;
711 return $returnedusers;
715 * Returns description of method result value
717 * @return external_multiple_structure
718 * @since Moodle 2.4
720 public static function get_users_by_field_returns() {
721 return new external_multiple_structure(self::user_description());
726 * Returns description of get_users() parameters.
728 * @return external_function_parameters
729 * @since Moodle 2.5
731 public static function get_users_parameters() {
732 return new external_function_parameters(
733 array(
734 'criteria' => new external_multiple_structure(
735 new external_single_structure(
736 array(
737 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
738 "id" (int) matching user id,
739 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
740 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
741 "idnumber" (string) matching user idnumber,
742 "username" (string) matching user username,
743 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
744 "auth" (string) matching user auth plugin'),
745 'value' => new external_value(PARAM_RAW, 'the value to search')
747 ), 'the key/value pairs to be considered in user search. Values can not be empty.
748 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
749 key occurences are forbidden.
750 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
751 the search is still executed on the valid criterias.
752 You can search without criteria, but the function is not designed for it.
753 It could very slow or timeout. The function is designed to search some specific users.'
760 * Retrieve matching user.
762 * @throws moodle_exception
763 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
764 * @return array An array of arrays containing user profiles.
765 * @since Moodle 2.5
767 public static function get_users($criteria = array()) {
768 global $CFG, $USER, $DB;
770 require_once($CFG->dirroot . "/user/lib.php");
772 $params = self::validate_parameters(self::get_users_parameters(),
773 array('criteria' => $criteria));
775 // Validate the criteria and retrieve the users.
776 $users = array();
777 $warnings = array();
778 $sqlparams = array();
779 $usedkeys = array();
781 // Do not retrieve deleted users.
782 $sql = ' deleted = 0';
784 foreach ($params['criteria'] as $criteriaindex => $criteria) {
786 // Check that the criteria has never been used.
787 if (array_key_exists($criteria['key'], $usedkeys)) {
788 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
789 } else {
790 $usedkeys[$criteria['key']] = true;
793 $invalidcriteria = false;
794 // Clean the parameters.
795 $paramtype = PARAM_RAW;
796 switch ($criteria['key']) {
797 case 'id':
798 $paramtype = core_user::get_property_type('id');
799 break;
800 case 'idnumber':
801 $paramtype = core_user::get_property_type('idnumber');
802 break;
803 case 'username':
804 $paramtype = core_user::get_property_type('username');
805 break;
806 case 'email':
807 // We use PARAM_RAW to allow searches with %.
808 $paramtype = core_user::get_property_type('email');
809 break;
810 case 'auth':
811 $paramtype = core_user::get_property_type('auth');
812 break;
813 case 'lastname':
814 case 'firstname':
815 $paramtype = core_user::get_property_type('firstname');
816 break;
817 default:
818 // Send back a warning that this search key is not supported in this version.
819 // This warning will make the function extandable without breaking clients.
820 $warnings[] = array(
821 'item' => $criteria['key'],
822 'warningcode' => 'invalidfieldparameter',
823 'message' =>
824 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
826 // Do not add this invalid criteria to the created SQL request.
827 $invalidcriteria = true;
828 unset($params['criteria'][$criteriaindex]);
829 break;
832 if (!$invalidcriteria) {
833 $cleanedvalue = clean_param($criteria['value'], $paramtype);
835 $sql .= ' AND ';
837 // Create the SQL.
838 switch ($criteria['key']) {
839 case 'id':
840 case 'idnumber':
841 case 'username':
842 case 'auth':
843 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
844 $sqlparams[$criteria['key']] = $cleanedvalue;
845 break;
846 case 'email':
847 case 'lastname':
848 case 'firstname':
849 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
850 $sqlparams[$criteria['key']] = $cleanedvalue;
851 break;
852 default:
853 break;
858 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
860 // Finally retrieve each users information.
861 $returnedusers = array();
862 foreach ($users as $user) {
863 $userdetails = user_get_user_details_courses($user);
865 // Return the user only if all the searched fields are returned.
866 // Otherwise it means that the $USER was not allowed to search the returned user.
867 if (!empty($userdetails)) {
868 $validuser = true;
870 foreach ($params['criteria'] as $criteria) {
871 if (empty($userdetails[$criteria['key']])) {
872 $validuser = false;
876 if ($validuser) {
877 $returnedusers[] = $userdetails;
882 return array('users' => $returnedusers, 'warnings' => $warnings);
886 * Returns description of get_users result value.
888 * @return external_description
889 * @since Moodle 2.5
891 public static function get_users_returns() {
892 return new external_single_structure(
893 array('users' => new external_multiple_structure(
894 self::user_description()
896 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
902 * Returns description of method parameters
904 * @return external_function_parameters
905 * @since Moodle 2.2
907 public static function get_course_user_profiles_parameters() {
908 return new external_function_parameters(
909 array(
910 'userlist' => new external_multiple_structure(
911 new external_single_structure(
912 array(
913 'userid' => new external_value(core_user::get_property_type('id'), 'userid'),
914 'courseid' => new external_value(PARAM_INT, 'courseid'),
923 * Get course participant's details
925 * @param array $userlist array of user ids and according course ids
926 * @return array An array of arrays describing course participants
927 * @since Moodle 2.2
929 public static function get_course_user_profiles($userlist) {
930 global $CFG, $USER, $DB;
931 require_once($CFG->dirroot . "/user/lib.php");
932 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
934 $userids = array();
935 $courseids = array();
936 foreach ($params['userlist'] as $value) {
937 $userids[] = $value['userid'];
938 $courseids[$value['userid']] = $value['courseid'];
941 // Cache all courses.
942 $courses = array();
943 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
944 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
945 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
946 $params['contextlevel'] = CONTEXT_COURSE;
947 $coursesql = "SELECT c.* $cselect
948 FROM {course} c $cjoin
949 WHERE c.id $sqlcourseids";
950 $rs = $DB->get_recordset_sql($coursesql, $params);
951 foreach ($rs as $course) {
952 // Adding course contexts to cache.
953 context_helper::preload_from_record($course);
954 // Cache courses.
955 $courses[$course->id] = $course;
957 $rs->close();
959 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
960 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
961 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
962 $params['contextlevel'] = CONTEXT_USER;
963 $usersql = "SELECT u.* $uselect
964 FROM {user} u $ujoin
965 WHERE u.id $sqluserids";
966 $users = $DB->get_recordset_sql($usersql, $params);
967 $result = array();
968 foreach ($users as $user) {
969 if (!empty($user->deleted)) {
970 continue;
972 context_helper::preload_from_record($user);
973 $course = $courses[$courseids[$user->id]];
974 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
975 self::validate_context($context);
976 if ($userarray = user_get_user_details($user, $course)) {
977 $result[] = $userarray;
981 $users->close();
983 return $result;
987 * Returns description of method result value
989 * @return external_description
990 * @since Moodle 2.2
992 public static function get_course_user_profiles_returns() {
993 $additionalfields = array(
994 'groups' => new external_multiple_structure(
995 new external_single_structure(
996 array(
997 'id' => new external_value(PARAM_INT, 'group id'),
998 'name' => new external_value(PARAM_RAW, 'group name'),
999 'description' => new external_value(PARAM_RAW, 'group description'),
1000 'descriptionformat' => new external_format_value('description'),
1002 ), 'user groups', VALUE_OPTIONAL),
1003 'roles' => new external_multiple_structure(
1004 new external_single_structure(
1005 array(
1006 'roleid' => new external_value(PARAM_INT, 'role id'),
1007 'name' => new external_value(PARAM_RAW, 'role name'),
1008 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
1009 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
1011 ), 'user roles', VALUE_OPTIONAL),
1012 'enrolledcourses' => new external_multiple_structure(
1013 new external_single_structure(
1014 array(
1015 'id' => new external_value(PARAM_INT, 'Id of the course'),
1016 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
1017 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
1019 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
1022 return new external_multiple_structure(self::user_description($additionalfields));
1026 * Create user return value description.
1028 * @param array $additionalfields some additional field
1029 * @return single_structure_description
1031 public static function user_description($additionalfields = array()) {
1032 $userfields = array(
1033 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
1034 'username' => new external_value(core_user::get_property_type('username'), 'The username', VALUE_OPTIONAL),
1035 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL),
1036 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
1037 'fullname' => new external_value(core_user::get_property_type('firstname'), 'The fullname of the user'),
1038 'email' => new external_value(core_user::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
1039 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
1040 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
1041 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
1042 'icq' => new external_value(core_user::get_property_type('icq'), 'icq number', VALUE_OPTIONAL),
1043 'skype' => new external_value(core_user::get_property_type('skype'), 'skype id', VALUE_OPTIONAL),
1044 'yahoo' => new external_value(core_user::get_property_type('yahoo'), 'yahoo id', VALUE_OPTIONAL),
1045 'aim' => new external_value(core_user::get_property_type('aim'), 'aim id', VALUE_OPTIONAL),
1046 'msn' => new external_value(core_user::get_property_type('msn'), 'msn number', VALUE_OPTIONAL),
1047 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
1048 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
1049 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
1050 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
1051 'firstaccess' => new external_value(core_user::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL),
1052 'lastaccess' => new external_value(core_user::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL),
1053 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL),
1054 '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),
1055 'confirmed' => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
1056 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
1057 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
1058 'theme' => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
1059 'timezone' => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
1060 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
1061 'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL),
1062 'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL),
1063 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
1064 'url' => new external_value(core_user::get_property_type('url'), 'URL of the user', VALUE_OPTIONAL),
1065 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
1066 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
1067 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
1068 'customfields' => new external_multiple_structure(
1069 new external_single_structure(
1070 array(
1071 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
1072 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
1073 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
1074 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
1076 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
1077 'preferences' => new external_multiple_structure(
1078 new external_single_structure(
1079 array(
1080 'name' => new external_value(PARAM_RAW, 'The name of the preferences'),
1081 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1083 ), 'Users preferences', VALUE_OPTIONAL)
1085 if (!empty($additionalfields)) {
1086 $userfields = array_merge($userfields, $additionalfields);
1088 return new external_single_structure($userfields);
1092 * Returns description of method parameters
1094 * @return external_function_parameters
1095 * @since Moodle 2.6
1097 public static function add_user_private_files_parameters() {
1098 return new external_function_parameters(
1099 array(
1100 'draftid' => new external_value(PARAM_INT, 'draft area id')
1106 * Copy files from a draft area to users private files area.
1108 * @throws invalid_parameter_exception
1109 * @param int $draftid Id of a draft area containing files.
1110 * @return array An array of warnings
1111 * @since Moodle 2.6
1113 public static function add_user_private_files($draftid) {
1114 global $CFG, $USER;
1115 require_once($CFG->libdir . "/filelib.php");
1117 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
1119 if (isguestuser()) {
1120 throw new invalid_parameter_exception('Guest users cannot upload files');
1123 $context = context_user::instance($USER->id);
1124 require_capability('moodle/user:manageownfiles', $context);
1126 $maxbytes = $CFG->userquota;
1127 $maxareabytes = $CFG->userquota;
1128 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1129 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1130 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1133 $options = array('subdirs' => 1,
1134 'maxbytes' => $maxbytes,
1135 'maxfiles' => -1,
1136 'areamaxbytes' => $maxareabytes);
1138 file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options);
1140 return null;
1144 * Returns description of method result value
1146 * @return external_description
1147 * @since Moodle 2.2
1149 public static function add_user_private_files_returns() {
1150 return null;
1154 * Returns description of method parameters.
1156 * @return external_function_parameters
1157 * @since Moodle 2.6
1159 public static function add_user_device_parameters() {
1160 return new external_function_parameters(
1161 array(
1162 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1163 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1164 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1165 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1166 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1167 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1168 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1174 * Add a user device in Moodle database (for PUSH notifications usually).
1176 * @throws moodle_exception
1177 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1178 * @param string $name The device name, occam or iPhone etc.
1179 * @param string $model The device model Nexus4 or iPad1.1 etc.
1180 * @param string $platform The device platform iOs or Android etc.
1181 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1182 * @param string $pushid The device PUSH token/key/identifier/registration id.
1183 * @param string $uuid The device UUID.
1184 * @return array List of possible warnings.
1185 * @since Moodle 2.6
1187 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1188 global $CFG, $USER, $DB;
1189 require_once($CFG->dirroot . "/user/lib.php");
1191 $params = self::validate_parameters(self::add_user_device_parameters(),
1192 array('appid' => $appid,
1193 'name' => $name,
1194 'model' => $model,
1195 'platform' => $platform,
1196 'version' => $version,
1197 'pushid' => $pushid,
1198 'uuid' => $uuid
1201 $warnings = array();
1203 // Prevent duplicate keys for users.
1204 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1205 $warnings['warning'][] = array(
1206 'item' => $params['pushid'],
1207 'warningcode' => 'existingkeyforthisuser',
1208 'message' => 'This key is already stored for this user'
1210 return $warnings;
1213 // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1214 // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1215 if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1216 'appid' => $params['appid'], 'userid' => $USER->id))) {
1218 foreach ($userdevices as $userdevice) {
1219 $userdevice->version = $params['version']; // Maybe the user upgraded the device.
1220 $userdevice->pushid = $params['pushid'];
1221 $userdevice->timemodified = time();
1222 $DB->update_record('user_devices', $userdevice);
1225 } else {
1226 $userdevice = new stdclass;
1227 $userdevice->userid = $USER->id;
1228 $userdevice->appid = $params['appid'];
1229 $userdevice->name = $params['name'];
1230 $userdevice->model = $params['model'];
1231 $userdevice->platform = $params['platform'];
1232 $userdevice->version = $params['version'];
1233 $userdevice->pushid = $params['pushid'];
1234 $userdevice->uuid = $params['uuid'];
1235 $userdevice->timecreated = time();
1236 $userdevice->timemodified = $userdevice->timecreated;
1238 if (!$DB->insert_record('user_devices', $userdevice)) {
1239 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1243 return $warnings;
1247 * Returns description of method result value.
1249 * @return external_multiple_structure
1250 * @since Moodle 2.6
1252 public static function add_user_device_returns() {
1253 return new external_multiple_structure(
1254 new external_warnings()
1259 * Returns description of method parameters.
1261 * @return external_function_parameters
1262 * @since Moodle 2.9
1264 public static function remove_user_device_parameters() {
1265 return new external_function_parameters(
1266 array(
1267 'uuid' => new external_value(PARAM_RAW, 'the device UUID'),
1268 'appid' => new external_value(PARAM_NOTAGS,
1269 'the app id, if empty devices matching the UUID for the user will be removed',
1270 VALUE_DEFAULT, ''),
1276 * Remove a user device from the Moodle database (for PUSH notifications usually).
1278 * @param string $uuid The device UUID.
1279 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1280 * @return array List of possible warnings and removal status.
1281 * @since Moodle 2.9
1283 public static function remove_user_device($uuid, $appid = "") {
1284 global $CFG;
1285 require_once($CFG->dirroot . "/user/lib.php");
1287 $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1289 $context = context_system::instance();
1290 self::validate_context($context);
1292 // Warnings array, it can be empty at the end but is mandatory.
1293 $warnings = array();
1295 $removed = user_remove_user_device($params['uuid'], $params['appid']);
1297 if (!$removed) {
1298 $warnings[] = array(
1299 'item' => $params['uuid'],
1300 'warningcode' => 'devicedoesnotexist',
1301 'message' => 'The device doesn\'t exists in the database'
1305 $result = array(
1306 'removed' => $removed,
1307 'warnings' => $warnings
1310 return $result;
1314 * Returns description of method result value.
1316 * @return external_multiple_structure
1317 * @since Moodle 2.9
1319 public static function remove_user_device_returns() {
1320 return new external_single_structure(
1321 array(
1322 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
1323 'warnings' => new external_warnings(),
1329 * Returns description of method parameters
1331 * @return external_function_parameters
1332 * @since Moodle 2.9
1334 public static function view_user_list_parameters() {
1335 return new external_function_parameters(
1336 array(
1337 'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site')
1343 * Trigger the user_list_viewed event.
1345 * @param int $courseid id of course
1346 * @return array of warnings and status result
1347 * @since Moodle 2.9
1348 * @throws moodle_exception
1350 public static function view_user_list($courseid) {
1351 global $CFG;
1352 require_once($CFG->dirroot . "/user/lib.php");
1353 require_once($CFG->dirroot . '/course/lib.php');
1355 $params = self::validate_parameters(self::view_user_list_parameters(),
1356 array(
1357 'courseid' => $courseid
1360 $warnings = array();
1362 if (empty($params['courseid'])) {
1363 $params['courseid'] = SITEID;
1366 $course = get_course($params['courseid']);
1368 if ($course->id == SITEID) {
1369 $context = context_system::instance();
1370 } else {
1371 $context = context_course::instance($course->id);
1373 self::validate_context($context);
1375 course_require_view_participants($context);
1377 user_list_view($course, $context);
1379 $result = array();
1380 $result['status'] = true;
1381 $result['warnings'] = $warnings;
1382 return $result;
1386 * Returns description of method result value
1388 * @return external_description
1389 * @since Moodle 2.9
1391 public static function view_user_list_returns() {
1392 return new external_single_structure(
1393 array(
1394 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1395 'warnings' => new external_warnings()
1401 * Returns description of method parameters
1403 * @return external_function_parameters
1404 * @since Moodle 2.9
1406 public static function view_user_profile_parameters() {
1407 return new external_function_parameters(
1408 array(
1409 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1410 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
1416 * Trigger the user profile viewed event.
1418 * @param int $userid id of user
1419 * @param int $courseid id of course
1420 * @return array of warnings and status result
1421 * @since Moodle 2.9
1422 * @throws moodle_exception
1424 public static function view_user_profile($userid, $courseid = 0) {
1425 global $CFG, $USER;
1426 require_once($CFG->dirroot . "/user/profile/lib.php");
1428 $params = self::validate_parameters(self::view_user_profile_parameters(),
1429 array(
1430 'userid' => $userid,
1431 'courseid' => $courseid
1434 $warnings = array();
1436 if (empty($params['userid'])) {
1437 $params['userid'] = $USER->id;
1440 if (empty($params['courseid'])) {
1441 $params['courseid'] = SITEID;
1444 $course = get_course($params['courseid']);
1445 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1446 core_user::require_active_user($user);
1448 if ($course->id == SITEID) {
1449 $coursecontext = context_system::instance();;
1450 } else {
1451 $coursecontext = context_course::instance($course->id);
1453 self::validate_context($coursecontext);
1455 $currentuser = $USER->id == $user->id;
1456 $usercontext = context_user::instance($user->id);
1458 if (!$currentuser and
1459 !has_capability('moodle/user:viewdetails', $coursecontext) and
1460 !has_capability('moodle/user:viewdetails', $usercontext)) {
1461 throw new moodle_exception('cannotviewprofile');
1464 // Case like user/profile.php.
1465 if ($course->id == SITEID) {
1466 profile_view($user, $usercontext);
1467 } else {
1468 // Case like user/view.php.
1469 if (!$currentuser and !can_access_course($course, $user, '', true)) {
1470 throw new moodle_exception('notenrolledprofile');
1473 profile_view($user, $coursecontext, $course);
1476 $result = array();
1477 $result['status'] = true;
1478 $result['warnings'] = $warnings;
1479 return $result;
1483 * Returns description of method result value
1485 * @return external_description
1486 * @since Moodle 2.9
1488 public static function view_user_profile_returns() {
1489 return new external_single_structure(
1490 array(
1491 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1492 'warnings' => new external_warnings()
1498 * Returns description of method parameters
1500 * @return external_function_parameters
1501 * @since Moodle 3.2
1503 public static function get_user_preferences_parameters() {
1504 return new external_function_parameters(
1505 array(
1506 'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''),
1507 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0)
1513 * Return user preferences.
1515 * @param string $name preference name, empty for all
1516 * @param int $userid id of the user, 0 for current user
1517 * @return array of warnings and preferences
1518 * @since Moodle 3.2
1519 * @throws moodle_exception
1521 public static function get_user_preferences($name = '', $userid = 0) {
1522 global $USER;
1524 $params = self::validate_parameters(self::get_user_preferences_parameters(),
1525 array(
1526 'name' => $name,
1527 'userid' => $userid
1529 $preferences = array();
1530 $warnings = array();
1532 $context = context_system::instance();
1533 self::validate_context($context);
1535 if (empty($params['name'])) {
1536 $name = null;
1538 if (empty($params['userid'])) {
1539 $user = null;
1540 } else {
1541 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1542 core_user::require_active_user($user);
1543 if ($user->id != $USER->id) {
1544 // Only admins can retrieve other users preferences.
1545 require_capability('moodle/site:config', $context);
1549 $userpreferences = get_user_preferences($name, null, $user);
1550 // Check if we received just one preference.
1551 if (!is_array($userpreferences)) {
1552 $userpreferences = array($name => $userpreferences);
1555 foreach ($userpreferences as $name => $value) {
1556 $preferences[] = array(
1557 'name' => $name,
1558 'value' => $value,
1562 $result = array();
1563 $result['preferences'] = $preferences;
1564 $result['warnings'] = $warnings;
1565 return $result;
1569 * Returns description of method result value
1571 * @return external_description
1572 * @since Moodle 3.2
1574 public static function get_user_preferences_returns() {
1575 return new external_single_structure(
1576 array(
1577 'preferences' => new external_multiple_structure(
1578 new external_single_structure(
1579 array(
1580 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1581 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1584 'User custom fields (also known as user profile fields)'
1586 'warnings' => new external_warnings()
1592 * Returns description of method parameters
1594 * @return external_function_parameters
1595 * @since Moodle 3.2
1597 public static function update_picture_parameters() {
1598 return new external_function_parameters(
1599 array(
1600 'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'),
1601 'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false),
1602 'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0)
1608 * Update or delete the user picture in the site
1610 * @param int $draftitemid id of the user draft file to use as image
1611 * @param bool $delete if we should delete the user picture
1612 * @param int $userid id of the user, 0 for current user
1613 * @return array warnings and success status
1614 * @since Moodle 3.2
1615 * @throws moodle_exception
1617 public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1618 global $CFG, $USER, $PAGE;
1620 $params = self::validate_parameters(
1621 self::update_picture_parameters(),
1622 array(
1623 'draftitemid' => $draftitemid,
1624 'delete' => $delete,
1625 'userid' => $userid
1629 $context = context_system::instance();
1630 self::validate_context($context);
1632 if (!empty($CFG->disableuserimages)) {
1633 throw new moodle_exception('userimagesdisabled', 'admin');
1636 if (empty($params['userid']) or $params['userid'] == $USER->id) {
1637 $user = $USER;
1638 require_capability('moodle/user:editownprofile', $context);
1639 } else {
1640 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1641 core_user::require_active_user($user);
1642 $personalcontext = context_user::instance($user->id);
1644 require_capability('moodle/user:editprofile', $personalcontext);
1645 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
1646 throw new moodle_exception('useradmineditadmin');
1650 // Load the appropriate auth plugin.
1651 $userauth = get_auth_plugin($user->auth);
1652 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1653 throw new moodle_exception('noprofileedit', 'auth');
1656 $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image');
1657 $user->deletepicture = $params['delete'];
1658 $user->imagefile = $params['draftitemid'];
1659 $success = core_user::update_picture($user, $filemanageroptions);
1661 $result = array(
1662 'success' => $success,
1663 'warnings' => array(),
1665 if ($success) {
1666 $userpicture = new user_picture(core_user::get_user($user->id));
1667 $userpicture->size = 1; // Size f1.
1668 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1670 return $result;
1674 * Returns description of method result value
1676 * @return external_description
1677 * @since Moodle 3.2
1679 public static function update_picture_returns() {
1680 return new external_single_structure(
1681 array(
1682 'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'),
1683 'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL),
1684 'warnings' => new external_warnings()
1690 * Returns description of method parameters
1692 * @return external_function_parameters
1693 * @since Moodle 3.2
1695 public static function set_user_preferences_parameters() {
1696 return new external_function_parameters(
1697 array(
1698 'preferences' => new external_multiple_structure(
1699 new external_single_structure(
1700 array(
1701 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1702 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1703 'userid' => new external_value(PARAM_INT, 'Id of the user to set the preference'),
1712 * Set user preferences.
1714 * @param array $preferences list of preferences including name, value and userid
1715 * @return array of warnings and preferences saved
1716 * @since Moodle 3.2
1717 * @throws moodle_exception
1719 public static function set_user_preferences($preferences) {
1720 global $USER;
1722 $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
1723 $warnings = array();
1724 $saved = array();
1726 $context = context_system::instance();
1727 self::validate_context($context);
1729 $userscache = array();
1730 foreach ($params['preferences'] as $pref) {
1731 // Check to which user set the preference.
1732 if (!empty($userscache[$pref['userid']])) {
1733 $user = $userscache[$pref['userid']];
1734 } else {
1735 try {
1736 $user = core_user::get_user($pref['userid'], '*', MUST_EXIST);
1737 core_user::require_active_user($user);
1738 $userscache[$pref['userid']] = $user;
1739 } catch (Exception $e) {
1740 $warnings[] = array(
1741 'item' => 'user',
1742 'itemid' => $pref['userid'],
1743 'warningcode' => 'invaliduser',
1744 'message' => $e->getMessage()
1746 continue;
1750 try {
1751 if (core_user::can_edit_preference($pref['name'], $user)) {
1752 $value = core_user::clean_preference($pref['value'], $pref['name']);
1753 set_user_preference($pref['name'], $value, $user->id);
1754 $saved[] = array(
1755 'name' => $pref['name'],
1756 'userid' => $user->id,
1758 } else {
1759 $warnings[] = array(
1760 'item' => 'user',
1761 'itemid' => $user->id,
1762 'warningcode' => 'nopermission',
1763 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id
1766 } catch (Exception $e) {
1767 $warnings[] = array(
1768 'item' => 'user',
1769 'itemid' => $user->id,
1770 'warningcode' => 'errorsavingpreference',
1771 'message' => $e->getMessage()
1776 $result = array();
1777 $result['saved'] = $saved;
1778 $result['warnings'] = $warnings;
1779 return $result;
1783 * Returns description of method result value
1785 * @return external_description
1786 * @since Moodle 3.2
1788 public static function set_user_preferences_returns() {
1789 return new external_single_structure(
1790 array(
1791 'saved' => new external_multiple_structure(
1792 new external_single_structure(
1793 array(
1794 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1795 'userid' => new external_value(PARAM_INT, 'The user the preference was set for'),
1797 ), 'Preferences saved'
1799 'warnings' => new external_warnings()
1805 * Returns description of method parameters.
1807 * @return external_function_parameters
1808 * @since Moodle 3.2
1810 public static function agree_site_policy_parameters() {
1811 return new external_function_parameters(array());
1815 * Agree the site policy for the current user.
1817 * @return array of warnings and status result
1818 * @since Moodle 3.2
1819 * @throws moodle_exception
1821 public static function agree_site_policy() {
1822 global $CFG, $DB, $USER;
1824 $warnings = array();
1826 $context = context_system::instance();
1827 try {
1828 // We expect an exception here since the user didn't agree the site policy yet.
1829 self::validate_context($context);
1830 } catch (Exception $e) {
1831 // We are expecting only a sitepolicynotagreed exception.
1832 if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
1833 // In case we receive a different exception, throw it.
1834 throw $e;
1838 $manager = new \core_privacy\local\sitepolicy\manager();
1839 if (!empty($USER->policyagreed)) {
1840 $status = false;
1841 $warnings[] = array(
1842 'item' => 'user',
1843 'itemid' => $USER->id,
1844 'warningcode' => 'alreadyagreed',
1845 'message' => 'The user already agreed the site policy.'
1847 } else if (!$manager->is_defined()) {
1848 $status = false;
1849 $warnings[] = array(
1850 'item' => 'user',
1851 'itemid' => $USER->id,
1852 'warningcode' => 'nositepolicy',
1853 'message' => 'The site does not have a site policy configured.'
1855 } else {
1856 $status = $manager->accept();
1859 $result = array();
1860 $result['status'] = $status;
1861 $result['warnings'] = $warnings;
1862 return $result;
1866 * Returns description of method result value.
1868 * @return external_description
1869 * @since Moodle 3.2
1871 public static function agree_site_policy_returns() {
1872 return new external_single_structure(
1873 array(
1874 'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'),
1875 'warnings' => new external_warnings()
1881 * Returns description of method parameters.
1883 * @return external_function_parameters
1884 * @since Moodle 3.4
1886 public static function get_private_files_info_parameters() {
1887 return new external_function_parameters(
1888 array(
1889 'userid' => new external_value(PARAM_INT, 'Id of the user, default to current user.', VALUE_DEFAULT, 0)
1895 * Returns general information about files in the user private files area.
1897 * @param int $userid Id of the user, default to current user.
1898 * @return array of warnings and file area information
1899 * @since Moodle 3.4
1900 * @throws moodle_exception
1902 public static function get_private_files_info($userid = 0) {
1903 global $CFG, $USER;
1904 require_once($CFG->libdir . '/filelib.php');
1906 $params = self::validate_parameters(self::get_private_files_info_parameters(), array('userid' => $userid));
1907 $warnings = array();
1909 $context = context_system::instance();
1910 self::validate_context($context);
1912 if (empty($params['userid']) || $params['userid'] == $USER->id) {
1913 $usercontext = context_user::instance($USER->id);
1914 require_capability('moodle/user:manageownfiles', $usercontext);
1915 } else {
1916 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1917 core_user::require_active_user($user);
1918 // Only admins can retrieve other users information.
1919 require_capability('moodle/site:config', $context);
1920 $usercontext = context_user::instance($user->id);
1923 $fileareainfo = file_get_file_area_info($usercontext->id, 'user', 'private');
1925 $result = array();
1926 $result['filecount'] = $fileareainfo['filecount'];
1927 $result['foldercount'] = $fileareainfo['foldercount'];
1928 $result['filesize'] = $fileareainfo['filesize'];
1929 $result['filesizewithoutreferences'] = $fileareainfo['filesize_without_references'];
1930 $result['warnings'] = $warnings;
1931 return $result;
1935 * Returns description of method result value.
1937 * @return external_description
1938 * @since Moodle 3.4
1940 public static function get_private_files_info_returns() {
1941 return new external_single_structure(
1942 array(
1943 'filecount' => new external_value(PARAM_INT, 'Number of files in the area.'),
1944 'foldercount' => new external_value(PARAM_INT, 'Number of folders in the area.'),
1945 'filesize' => new external_value(PARAM_INT, 'Total size of the files in the area.'),
1946 'filesizewithoutreferences' => new external_value(PARAM_INT, 'Total size of the area excluding file references'),
1947 'warnings' => new external_warnings()