MDL-55522 behat: Commented failing transformations
[moodle.git] / user / externallib.php
blob2d2ddd64426e17852adbcd488c43d8e51bfbbdd0
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 require_once("$CFG->libdir/externallib.php");
28 /**
29 * User external functions
31 * @package core_user
32 * @category external
33 * @copyright 2011 Jerome Mouneyrac
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 * @since Moodle 2.2
37 class core_user_external extends external_api {
39 /**
40 * Returns description of method parameters
42 * @return external_function_parameters
43 * @since Moodle 2.2
45 public static function create_users_parameters() {
46 global $CFG;
48 return new external_function_parameters(
49 array(
50 'users' => new external_multiple_structure(
51 new external_single_structure(
52 array(
53 'username' =>
54 new external_value(core_user::get_property_type('username'), 'Username policy is defined in Moodle security config.'),
55 'password' =>
56 new external_value(core_user::get_property_type('password'), 'Plain text password consisting of any characters', VALUE_OPTIONAL),
57 'createpassword' =>
58 new external_value(PARAM_BOOL, 'True if password should be created and mailed to user.',
59 VALUE_OPTIONAL),
60 'firstname' =>
61 new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user'),
62 'lastname' =>
63 new external_value(core_user::get_property_type('lastname'), 'The family name of the user'),
64 'email' =>
65 new external_value(core_user::get_property_type('email'), 'A valid and unique email address'),
66 'auth' =>
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')),
69 'idnumber' =>
70 new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution',
71 VALUE_DEFAULT, ''),
72 'lang' =>
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')),
75 'calendartype' =>
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),
78 'theme' =>
79 new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server',
80 VALUE_OPTIONAL),
81 'timezone' =>
82 new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default',
83 VALUE_OPTIONAL),
84 'mailformat' =>
85 new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc',
86 VALUE_OPTIONAL),
87 'description' =>
88 new external_value(core_user::get_property_type('description'), 'User profile description, no HTML', VALUE_OPTIONAL),
89 'city' =>
90 new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
91 'country' =>
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),
95 'lastnamephonetic' =>
96 new external_value(core_user::get_property_type('lastnamephonetic'), 'The family name phonetically of the user', VALUE_OPTIONAL),
97 'middlename' =>
98 new external_value(core_user::get_property_type('middlename'), 'The middle name of the user', VALUE_OPTIONAL),
99 'alternatename' =>
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(
103 array(
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(
110 array(
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
128 * @since Moodle 2.2
130 public static function create_users($users) {
131 global $CFG, $DB;
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();
154 $userids = array();
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;
203 } else {
204 $updatepassword = true;
207 // Create the user data now!
208 $user['id'] = user_create_user($user, $updatepassword, false);
210 // Custom fields.
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);
227 // Trigger event.
228 \core\event\user_created::create_from_userid($user['id'])->trigger();
230 // Preferences.
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();
242 return $userids;
246 * Returns description of method result value
248 * @return external_description
249 * @since Moodle 2.2
251 public static function create_users_returns() {
252 return new external_multiple_structure(
253 new external_single_structure(
254 array(
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
267 * @since Moodle 2.2
269 public static function delete_users_parameters() {
270 return new external_function_parameters(
271 array(
272 'userids' => new external_multiple_structure(new external_value(core_user::get_property_type('id'), 'user ID')),
278 * Delete users
280 * @throws moodle_exception
281 * @param array $userids
282 * @return null
283 * @since Moodle 2.2
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();
312 return null;
316 * Returns description of method result value
318 * @return null
319 * @since Moodle 2.2
321 public static function delete_users_returns() {
322 return null;
326 * Returns description of method parameters.
328 * @return external_function_parameters
329 * @since Moodle 3.2
331 public static function update_user_preferences_parameters() {
332 return new external_function_parameters(
333 array(
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(
339 array(
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.
352 * @param int $userid
353 * @param bool|null $emailstop
354 * @param array $preferences
355 * @return null
356 * @since Moodle 3.2
358 public static function update_user_preferences($userid, $emailstop = null, $preferences = array()) {
359 global $USER, $CFG;
361 require_once($CFG->dirroot . '/user/lib.php');
363 if (empty($userid)) {
364 $userid = $USER->id;
367 $systemcontext = context_system::instance();
368 self::validate_context($systemcontext);
369 $params = array(
370 'userid' => $userid,
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);
378 } else {
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');
391 // Preferences.
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();
401 $user->id = $userid;
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;
411 return null;
415 * Returns description of method result value
417 * @return null
418 * @since Moodle 3.2
420 public static function update_user_preferences_returns() {
421 return null;
425 * Returns description of method parameters
427 * @return external_function_parameters
428 * @since Moodle 2.2
430 public static function update_users_parameters() {
431 return new external_function_parameters(
432 array(
433 'users' => new external_multiple_structure(
434 new external_single_structure(
435 array(
436 'id' =>
437 new external_value(core_user::get_property_type('id'), 'ID of the user'),
438 'username' =>
439 new external_value(core_user::get_property_type('username'), 'Username policy is defined in Moodle security config.',
440 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
441 'password' =>
442 new external_value(core_user::get_property_type('password'), 'Plain text password consisting of any characters', VALUE_OPTIONAL,
443 '', NULL_NOT_ALLOWED),
444 'firstname' =>
445 new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL, '',
446 NULL_NOT_ALLOWED),
447 'lastname' =>
448 new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
449 'email' =>
450 new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL, '',
451 NULL_NOT_ALLOWED),
452 'auth' =>
453 new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL, '',
454 NULL_NOT_ALLOWED),
455 'idnumber' =>
456 new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution',
457 VALUE_OPTIONAL),
458 'lang' =>
459 new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
460 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
461 'calendartype' =>
462 new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server',
463 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
464 'theme' =>
465 new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server',
466 VALUE_OPTIONAL),
467 'timezone' =>
468 new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default',
469 VALUE_OPTIONAL),
470 'mailformat' =>
471 new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc',
472 VALUE_OPTIONAL),
473 'description' =>
474 new external_value(core_user::get_property_type('description'), 'User profile description, no HTML', VALUE_OPTIONAL),
475 'city' =>
476 new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
477 'country' =>
478 new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
479 'firstnamephonetic' =>
480 new external_value(core_user::get_property_type('firstnamephonetic'), 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
481 'lastnamephonetic' =>
482 new external_value(core_user::get_property_type('lastnamephonetic'), 'The family name phonetically of the user', VALUE_OPTIONAL),
483 'middlename' =>
484 new external_value(core_user::get_property_type('middlename'), 'The middle name of the user', VALUE_OPTIONAL),
485 'alternatename' =>
486 new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user', VALUE_OPTIONAL),
487 'userpicture' =>
488 new external_value(PARAM_INT, 'The itemid where the new user picture '.
489 'has been uploaded to, 0 to delete', VALUE_OPTIONAL),
490 'customfields' => new external_multiple_structure(
491 new external_single_structure(
492 array(
493 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
494 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
496 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
497 'preferences' => new external_multiple_structure(
498 new external_single_structure(
499 array(
500 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
501 'value' => new external_value(PARAM_RAW, 'The value of the preference')
503 ), 'User preferences', VALUE_OPTIONAL),
512 * Update users
514 * @param array $users
515 * @return null
516 * @since Moodle 2.2
518 public static function update_users($users) {
519 global $CFG, $DB;
520 require_once($CFG->dirroot."/user/lib.php");
521 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
523 // Ensure the current user is allowed to run this function.
524 $context = context_system::instance();
525 require_capability('moodle/user:update', $context);
526 self::validate_context($context);
528 $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
530 $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
531 'subdirs' => 0,
532 'maxfiles' => 1,
533 'accepted_types' => 'web_image');
535 $transaction = $DB->start_delegated_transaction();
537 foreach ($params['users'] as $user) {
538 user_update_user($user, true, false);
540 // Update user picture if it was specified for this user.
541 if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
542 $userobject = (object)$user;
544 $userobject->deletepicture = null;
546 if ($user['userpicture'] == 0) {
547 $userobject->deletepicture = true;
548 } else {
549 $userobject->imagefile = $user['userpicture'];
552 core_user::update_picture($userobject, $filemanageroptions);
555 // Update user custom fields.
556 if (!empty($user['customfields'])) {
558 foreach ($user['customfields'] as $customfield) {
559 // Profile_save_data() saves profile file it's expecting a user with the correct id,
560 // and custom field to be named profile_field_"shortname".
561 $user["profile_field_".$customfield['type']] = $customfield['value'];
563 profile_save_data((object) $user);
566 // Trigger event.
567 \core\event\user_updated::create_from_userid($user['id'])->trigger();
569 // Preferences.
570 if (!empty($user['preferences'])) {
571 foreach ($user['preferences'] as $preference) {
572 set_user_preference($preference['type'], $preference['value'], $user['id']);
577 $transaction->allow_commit();
579 return null;
583 * Returns description of method result value
585 * @return null
586 * @since Moodle 2.2
588 public static function update_users_returns() {
589 return null;
593 * Returns description of method parameters
595 * @return external_function_parameters
596 * @since Moodle 2.4
598 public static function get_users_by_field_parameters() {
599 return new external_function_parameters(
600 array(
601 'field' => new external_value(PARAM_ALPHA, 'the search field can be
602 \'id\' or \'idnumber\' or \'username\' or \'email\''),
603 'values' => new external_multiple_structure(
604 new external_value(PARAM_RAW, 'the value to match'))
610 * Get user information for a unique field.
612 * @throws coding_exception
613 * @throws invalid_parameter_exception
614 * @param string $field
615 * @param array $values
616 * @return array An array of arrays containg user profiles.
617 * @since Moodle 2.4
619 public static function get_users_by_field($field, $values) {
620 global $CFG, $USER, $DB;
621 require_once($CFG->dirroot . "/user/lib.php");
623 $params = self::validate_parameters(self::get_users_by_field_parameters(),
624 array('field' => $field, 'values' => $values));
626 // This array will keep all the users that are allowed to be searched,
627 // according to the current user's privileges.
628 $cleanedvalues = array();
630 switch ($field) {
631 case 'id':
632 $paramtype = core_user::get_property_type('id');
633 break;
634 case 'idnumber':
635 $paramtype = core_user::get_property_type('idnumber');
636 break;
637 case 'username':
638 $paramtype = core_user::get_property_type('username');
639 break;
640 case 'email':
641 $paramtype = core_user::get_property_type('email');
642 break;
643 default:
644 throw new coding_exception('invalid field parameter',
645 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
648 // Clean the values.
649 foreach ($values as $value) {
650 $cleanedvalue = clean_param($value, $paramtype);
651 if ( $value != $cleanedvalue) {
652 throw new invalid_parameter_exception('The field \'' . $field .
653 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
655 $cleanedvalues[] = $cleanedvalue;
658 // Retrieve the users.
659 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
661 $context = context_system::instance();
662 self::validate_context($context);
664 // Finally retrieve each users information.
665 $returnedusers = array();
666 foreach ($users as $user) {
667 $userdetails = user_get_user_details_courses($user);
669 // Return the user only if the searched field is returned.
670 // Otherwise it means that the $USER was not allowed to search the returned user.
671 if (!empty($userdetails) and !empty($userdetails[$field])) {
672 $returnedusers[] = $userdetails;
676 return $returnedusers;
680 * Returns description of method result value
682 * @return external_multiple_structure
683 * @since Moodle 2.4
685 public static function get_users_by_field_returns() {
686 return new external_multiple_structure(self::user_description());
691 * Returns description of get_users() parameters.
693 * @return external_function_parameters
694 * @since Moodle 2.5
696 public static function get_users_parameters() {
697 return new external_function_parameters(
698 array(
699 'criteria' => new external_multiple_structure(
700 new external_single_structure(
701 array(
702 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
703 "id" (int) matching user id,
704 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
705 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
706 "idnumber" (string) matching user idnumber,
707 "username" (string) matching user username,
708 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
709 "auth" (string) matching user auth plugin'),
710 'value' => new external_value(PARAM_RAW, 'the value to search')
712 ), 'the key/value pairs to be considered in user search. Values can not be empty.
713 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
714 key occurences are forbidden.
715 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
716 the search is still executed on the valid criterias.
717 You can search without criteria, but the function is not designed for it.
718 It could very slow or timeout. The function is designed to search some specific users.'
725 * Retrieve matching user.
727 * @throws moodle_exception
728 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
729 * @return array An array of arrays containing user profiles.
730 * @since Moodle 2.5
732 public static function get_users($criteria = array()) {
733 global $CFG, $USER, $DB;
735 require_once($CFG->dirroot . "/user/lib.php");
737 $params = self::validate_parameters(self::get_users_parameters(),
738 array('criteria' => $criteria));
740 // Validate the criteria and retrieve the users.
741 $users = array();
742 $warnings = array();
743 $sqlparams = array();
744 $usedkeys = array();
746 // Do not retrieve deleted users.
747 $sql = ' deleted = 0';
749 foreach ($params['criteria'] as $criteriaindex => $criteria) {
751 // Check that the criteria has never been used.
752 if (array_key_exists($criteria['key'], $usedkeys)) {
753 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
754 } else {
755 $usedkeys[$criteria['key']] = true;
758 $invalidcriteria = false;
759 // Clean the parameters.
760 $paramtype = PARAM_RAW;
761 switch ($criteria['key']) {
762 case 'id':
763 $paramtype = core_user::get_property_type('id');
764 break;
765 case 'idnumber':
766 $paramtype = core_user::get_property_type('idnumber');
767 break;
768 case 'username':
769 $paramtype = core_user::get_property_type('username');
770 break;
771 case 'email':
772 // We use PARAM_RAW to allow searches with %.
773 $paramtype = core_user::get_property_type('email');
774 break;
775 case 'auth':
776 $paramtype = core_user::get_property_type('auth');
777 break;
778 case 'lastname':
779 case 'firstname':
780 $paramtype = core_user::get_property_type('firstname');
781 break;
782 default:
783 // Send back a warning that this search key is not supported in this version.
784 // This warning will make the function extandable without breaking clients.
785 $warnings[] = array(
786 'item' => $criteria['key'],
787 'warningcode' => 'invalidfieldparameter',
788 'message' =>
789 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
791 // Do not add this invalid criteria to the created SQL request.
792 $invalidcriteria = true;
793 unset($params['criteria'][$criteriaindex]);
794 break;
797 if (!$invalidcriteria) {
798 $cleanedvalue = clean_param($criteria['value'], $paramtype);
800 $sql .= ' AND ';
802 // Create the SQL.
803 switch ($criteria['key']) {
804 case 'id':
805 case 'idnumber':
806 case 'username':
807 case 'auth':
808 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
809 $sqlparams[$criteria['key']] = $cleanedvalue;
810 break;
811 case 'email':
812 case 'lastname':
813 case 'firstname':
814 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
815 $sqlparams[$criteria['key']] = $cleanedvalue;
816 break;
817 default:
818 break;
823 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
825 // Finally retrieve each users information.
826 $returnedusers = array();
827 foreach ($users as $user) {
828 $userdetails = user_get_user_details_courses($user);
830 // Return the user only if all the searched fields are returned.
831 // Otherwise it means that the $USER was not allowed to search the returned user.
832 if (!empty($userdetails)) {
833 $validuser = true;
835 foreach ($params['criteria'] as $criteria) {
836 if (empty($userdetails[$criteria['key']])) {
837 $validuser = false;
841 if ($validuser) {
842 $returnedusers[] = $userdetails;
847 return array('users' => $returnedusers, 'warnings' => $warnings);
851 * Returns description of get_users result value.
853 * @return external_description
854 * @since Moodle 2.5
856 public static function get_users_returns() {
857 return new external_single_structure(
858 array('users' => new external_multiple_structure(
859 self::user_description()
861 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
867 * Returns description of method parameters
869 * @return external_function_parameters
870 * @since Moodle 2.2
872 public static function get_course_user_profiles_parameters() {
873 return new external_function_parameters(
874 array(
875 'userlist' => new external_multiple_structure(
876 new external_single_structure(
877 array(
878 'userid' => new external_value(core_user::get_property_type('id'), 'userid'),
879 'courseid' => new external_value(PARAM_INT, 'courseid'),
888 * Get course participant's details
890 * @param array $userlist array of user ids and according course ids
891 * @return array An array of arrays describing course participants
892 * @since Moodle 2.2
894 public static function get_course_user_profiles($userlist) {
895 global $CFG, $USER, $DB;
896 require_once($CFG->dirroot . "/user/lib.php");
897 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
899 $userids = array();
900 $courseids = array();
901 foreach ($params['userlist'] as $value) {
902 $userids[] = $value['userid'];
903 $courseids[$value['userid']] = $value['courseid'];
906 // Cache all courses.
907 $courses = array();
908 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
909 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
910 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
911 $params['contextlevel'] = CONTEXT_COURSE;
912 $coursesql = "SELECT c.* $cselect
913 FROM {course} c $cjoin
914 WHERE c.id $sqlcourseids";
915 $rs = $DB->get_recordset_sql($coursesql, $params);
916 foreach ($rs as $course) {
917 // Adding course contexts to cache.
918 context_helper::preload_from_record($course);
919 // Cache courses.
920 $courses[$course->id] = $course;
922 $rs->close();
924 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
925 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
926 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
927 $params['contextlevel'] = CONTEXT_USER;
928 $usersql = "SELECT u.* $uselect
929 FROM {user} u $ujoin
930 WHERE u.id $sqluserids";
931 $users = $DB->get_recordset_sql($usersql, $params);
932 $result = array();
933 foreach ($users as $user) {
934 if (!empty($user->deleted)) {
935 continue;
937 context_helper::preload_from_record($user);
938 $course = $courses[$courseids[$user->id]];
939 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
940 self::validate_context($context);
941 if ($userarray = user_get_user_details($user, $course)) {
942 $result[] = $userarray;
946 $users->close();
948 return $result;
952 * Returns description of method result value
954 * @return external_description
955 * @since Moodle 2.2
957 public static function get_course_user_profiles_returns() {
958 $additionalfields = array(
959 'groups' => new external_multiple_structure(
960 new external_single_structure(
961 array(
962 'id' => new external_value(PARAM_INT, 'group id'),
963 'name' => new external_value(PARAM_RAW, 'group name'),
964 'description' => new external_value(PARAM_RAW, 'group description'),
965 'descriptionformat' => new external_format_value('description'),
967 ), 'user groups', VALUE_OPTIONAL),
968 'roles' => new external_multiple_structure(
969 new external_single_structure(
970 array(
971 'roleid' => new external_value(PARAM_INT, 'role id'),
972 'name' => new external_value(PARAM_RAW, 'role name'),
973 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
974 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
976 ), 'user roles', VALUE_OPTIONAL),
977 'enrolledcourses' => new external_multiple_structure(
978 new external_single_structure(
979 array(
980 'id' => new external_value(PARAM_INT, 'Id of the course'),
981 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
982 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
984 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
987 return new external_multiple_structure(self::user_description($additionalfields));
991 * Create user return value description.
993 * @param array $additionalfields some additional field
994 * @return single_structure_description
996 public static function user_description($additionalfields = array()) {
997 $userfields = array(
998 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
999 'username' => new external_value(core_user::get_property_type('username'), 'The username', VALUE_OPTIONAL),
1000 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL),
1001 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
1002 'fullname' => new external_value(core_user::get_property_type('firstname'), 'The fullname of the user'),
1003 'email' => new external_value(core_user::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
1004 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
1005 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
1006 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
1007 'icq' => new external_value(core_user::get_property_type('icq'), 'icq number', VALUE_OPTIONAL),
1008 'skype' => new external_value(core_user::get_property_type('skype'), 'skype id', VALUE_OPTIONAL),
1009 'yahoo' => new external_value(core_user::get_property_type('yahoo'), 'yahoo id', VALUE_OPTIONAL),
1010 'aim' => new external_value(core_user::get_property_type('aim'), 'aim id', VALUE_OPTIONAL),
1011 'msn' => new external_value(core_user::get_property_type('msn'), 'msn number', VALUE_OPTIONAL),
1012 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
1013 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
1014 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
1015 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
1016 'firstaccess' => new external_value(core_user::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL),
1017 'lastaccess' => new external_value(core_user::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL),
1018 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
1019 'confirmed' => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
1020 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
1021 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
1022 'theme' => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
1023 'timezone' => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
1024 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
1025 'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL),
1026 'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL),
1027 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
1028 'url' => new external_value(core_user::get_property_type('url'), 'URL of the user', VALUE_OPTIONAL),
1029 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
1030 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
1031 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
1032 'customfields' => new external_multiple_structure(
1033 new external_single_structure(
1034 array(
1035 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
1036 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
1037 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
1038 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
1040 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
1041 'preferences' => new external_multiple_structure(
1042 new external_single_structure(
1043 array(
1044 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
1045 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
1047 ), 'Users preferences', VALUE_OPTIONAL)
1049 if (!empty($additionalfields)) {
1050 $userfields = array_merge($userfields, $additionalfields);
1052 return new external_single_structure($userfields);
1056 * Returns description of method parameters
1058 * @return external_function_parameters
1059 * @since Moodle 2.6
1061 public static function add_user_private_files_parameters() {
1062 return new external_function_parameters(
1063 array(
1064 'draftid' => new external_value(PARAM_INT, 'draft area id')
1070 * Copy files from a draft area to users private files area.
1072 * @throws invalid_parameter_exception
1073 * @param int $draftid Id of a draft area containing files.
1074 * @return array An array of warnings
1075 * @since Moodle 2.6
1077 public static function add_user_private_files($draftid) {
1078 global $CFG, $USER;
1079 require_once($CFG->libdir . "/filelib.php");
1081 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
1083 if (isguestuser()) {
1084 throw new invalid_parameter_exception('Guest users cannot upload files');
1087 $context = context_user::instance($USER->id);
1088 require_capability('moodle/user:manageownfiles', $context);
1090 $maxbytes = $CFG->userquota;
1091 $maxareabytes = $CFG->userquota;
1092 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1093 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1094 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1097 $options = array('subdirs' => 1,
1098 'maxbytes' => $maxbytes,
1099 'maxfiles' => -1,
1100 'areamaxbytes' => $maxareabytes);
1102 file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options);
1104 return null;
1108 * Returns description of method result value
1110 * @return external_description
1111 * @since Moodle 2.2
1113 public static function add_user_private_files_returns() {
1114 return null;
1118 * Returns description of method parameters.
1120 * @return external_function_parameters
1121 * @since Moodle 2.6
1123 public static function add_user_device_parameters() {
1124 return new external_function_parameters(
1125 array(
1126 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1127 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1128 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1129 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1130 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1131 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1132 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1138 * Add a user device in Moodle database (for PUSH notifications usually).
1140 * @throws moodle_exception
1141 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1142 * @param string $name The device name, occam or iPhone etc.
1143 * @param string $model The device model Nexus4 or iPad1.1 etc.
1144 * @param string $platform The device platform iOs or Android etc.
1145 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1146 * @param string $pushid The device PUSH token/key/identifier/registration id.
1147 * @param string $uuid The device UUID.
1148 * @return array List of possible warnings.
1149 * @since Moodle 2.6
1151 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1152 global $CFG, $USER, $DB;
1153 require_once($CFG->dirroot . "/user/lib.php");
1155 $params = self::validate_parameters(self::add_user_device_parameters(),
1156 array('appid' => $appid,
1157 'name' => $name,
1158 'model' => $model,
1159 'platform' => $platform,
1160 'version' => $version,
1161 'pushid' => $pushid,
1162 'uuid' => $uuid
1165 $warnings = array();
1167 // Prevent duplicate keys for users.
1168 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1169 $warnings['warning'][] = array(
1170 'item' => $params['pushid'],
1171 'warningcode' => 'existingkeyforthisuser',
1172 'message' => 'This key is already stored for this user'
1174 return $warnings;
1177 // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1178 // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1179 if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1180 'appid' => $params['appid'], 'userid' => $USER->id))) {
1182 foreach ($userdevices as $userdevice) {
1183 $userdevice->version = $params['version']; // Maybe the user upgraded the device.
1184 $userdevice->pushid = $params['pushid'];
1185 $userdevice->timemodified = time();
1186 $DB->update_record('user_devices', $userdevice);
1189 } else {
1190 $userdevice = new stdclass;
1191 $userdevice->userid = $USER->id;
1192 $userdevice->appid = $params['appid'];
1193 $userdevice->name = $params['name'];
1194 $userdevice->model = $params['model'];
1195 $userdevice->platform = $params['platform'];
1196 $userdevice->version = $params['version'];
1197 $userdevice->pushid = $params['pushid'];
1198 $userdevice->uuid = $params['uuid'];
1199 $userdevice->timecreated = time();
1200 $userdevice->timemodified = $userdevice->timecreated;
1202 if (!$DB->insert_record('user_devices', $userdevice)) {
1203 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1207 return $warnings;
1211 * Returns description of method result value.
1213 * @return external_multiple_structure
1214 * @since Moodle 2.6
1216 public static function add_user_device_returns() {
1217 return new external_multiple_structure(
1218 new external_warnings()
1223 * Returns description of method parameters.
1225 * @return external_function_parameters
1226 * @since Moodle 2.9
1228 public static function remove_user_device_parameters() {
1229 return new external_function_parameters(
1230 array(
1231 'uuid' => new external_value(PARAM_RAW, 'the device UUID'),
1232 'appid' => new external_value(PARAM_NOTAGS,
1233 'the app id, if empty devices matching the UUID for the user will be removed',
1234 VALUE_DEFAULT, ''),
1240 * Remove a user device from the Moodle database (for PUSH notifications usually).
1242 * @param string $uuid The device UUID.
1243 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1244 * @return array List of possible warnings and removal status.
1245 * @since Moodle 2.9
1247 public static function remove_user_device($uuid, $appid = "") {
1248 global $CFG;
1249 require_once($CFG->dirroot . "/user/lib.php");
1251 $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1253 $context = context_system::instance();
1254 self::validate_context($context);
1256 // Warnings array, it can be empty at the end but is mandatory.
1257 $warnings = array();
1259 $removed = user_remove_user_device($params['uuid'], $params['appid']);
1261 if (!$removed) {
1262 $warnings[] = array(
1263 'item' => $params['uuid'],
1264 'warningcode' => 'devicedoesnotexist',
1265 'message' => 'The device doesn\'t exists in the database'
1269 $result = array(
1270 'removed' => $removed,
1271 'warnings' => $warnings
1274 return $result;
1278 * Returns description of method result value.
1280 * @return external_multiple_structure
1281 * @since Moodle 2.9
1283 public static function remove_user_device_returns() {
1284 return new external_single_structure(
1285 array(
1286 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
1287 'warnings' => new external_warnings(),
1293 * Returns description of method parameters
1295 * @return external_function_parameters
1296 * @since Moodle 2.9
1298 public static function view_user_list_parameters() {
1299 return new external_function_parameters(
1300 array(
1301 'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site')
1307 * Trigger the user_list_viewed event.
1309 * @param int $courseid id of course
1310 * @return array of warnings and status result
1311 * @since Moodle 2.9
1312 * @throws moodle_exception
1314 public static function view_user_list($courseid) {
1315 global $CFG;
1316 require_once($CFG->dirroot . "/user/lib.php");
1318 $params = self::validate_parameters(self::view_user_list_parameters(),
1319 array(
1320 'courseid' => $courseid
1323 $warnings = array();
1325 if (empty($params['courseid'])) {
1326 $params['courseid'] = SITEID;
1329 $course = get_course($params['courseid']);
1331 if ($course->id == SITEID) {
1332 $context = context_system::instance();
1333 } else {
1334 $context = context_course::instance($course->id);
1336 self::validate_context($context);
1338 if ($course->id == SITEID) {
1339 require_capability('moodle/site:viewparticipants', $context);
1340 } else {
1341 require_capability('moodle/course:viewparticipants', $context);
1344 user_list_view($course, $context);
1346 $result = array();
1347 $result['status'] = true;
1348 $result['warnings'] = $warnings;
1349 return $result;
1353 * Returns description of method result value
1355 * @return external_description
1356 * @since Moodle 2.9
1358 public static function view_user_list_returns() {
1359 return new external_single_structure(
1360 array(
1361 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1362 'warnings' => new external_warnings()
1368 * Returns description of method parameters
1370 * @return external_function_parameters
1371 * @since Moodle 2.9
1373 public static function view_user_profile_parameters() {
1374 return new external_function_parameters(
1375 array(
1376 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1377 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
1383 * Trigger the user profile viewed event.
1385 * @param int $userid id of user
1386 * @param int $courseid id of course
1387 * @return array of warnings and status result
1388 * @since Moodle 2.9
1389 * @throws moodle_exception
1391 public static function view_user_profile($userid, $courseid = 0) {
1392 global $CFG, $USER;
1393 require_once($CFG->dirroot . "/user/profile/lib.php");
1395 $params = self::validate_parameters(self::view_user_profile_parameters(),
1396 array(
1397 'userid' => $userid,
1398 'courseid' => $courseid
1401 $warnings = array();
1403 if (empty($params['userid'])) {
1404 $params['userid'] = $USER->id;
1407 if (empty($params['courseid'])) {
1408 $params['courseid'] = SITEID;
1411 $course = get_course($params['courseid']);
1412 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1413 core_user::require_active_user($user);
1415 if ($course->id == SITEID) {
1416 $coursecontext = context_system::instance();;
1417 } else {
1418 $coursecontext = context_course::instance($course->id);
1420 self::validate_context($coursecontext);
1422 $currentuser = $USER->id == $user->id;
1423 $usercontext = context_user::instance($user->id);
1425 if (!$currentuser and
1426 !has_capability('moodle/user:viewdetails', $coursecontext) and
1427 !has_capability('moodle/user:viewdetails', $usercontext)) {
1428 throw new moodle_exception('cannotviewprofile');
1431 // Case like user/profile.php.
1432 if ($course->id == SITEID) {
1433 profile_view($user, $usercontext);
1434 } else {
1435 // Case like user/view.php.
1436 if (!$currentuser and !can_access_course($course, $user, '', true)) {
1437 throw new moodle_exception('notenrolledprofile');
1440 profile_view($user, $coursecontext, $course);
1443 $result = array();
1444 $result['status'] = true;
1445 $result['warnings'] = $warnings;
1446 return $result;
1450 * Returns description of method result value
1452 * @return external_description
1453 * @since Moodle 2.9
1455 public static function view_user_profile_returns() {
1456 return new external_single_structure(
1457 array(
1458 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1459 'warnings' => new external_warnings()
1465 * Returns description of method parameters
1467 * @return external_function_parameters
1468 * @since Moodle 3.2
1470 public static function get_user_preferences_parameters() {
1471 return new external_function_parameters(
1472 array(
1473 'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''),
1474 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0)
1480 * Return user preferences.
1482 * @param string $name preference name, empty for all
1483 * @param int $userid id of the user, 0 for current user
1484 * @return array of warnings and preferences
1485 * @since Moodle 3.2
1486 * @throws moodle_exception
1488 public static function get_user_preferences($name = '', $userid = 0) {
1489 global $USER;
1491 $params = self::validate_parameters(self::get_user_preferences_parameters(),
1492 array(
1493 'name' => $name,
1494 'userid' => $userid
1496 $preferences = array();
1497 $warnings = array();
1499 $context = context_system::instance();
1500 self::validate_context($context);
1502 if (empty($params['name'])) {
1503 $name = null;
1505 if (empty($params['userid'])) {
1506 $user = null;
1507 } else {
1508 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1509 core_user::require_active_user($user);
1510 if ($user->id != $USER->id) {
1511 // Only admins can retrieve other users preferences.
1512 require_capability('moodle/site:config', $context);
1516 $userpreferences = get_user_preferences($name, null, $user);
1517 // Check if we received just one preference.
1518 if (!is_array($userpreferences)) {
1519 $userpreferences = array($name => $userpreferences);
1522 foreach ($userpreferences as $name => $value) {
1523 $preferences[] = array(
1524 'name' => $name,
1525 'value' => $value,
1529 $result = array();
1530 $result['preferences'] = $preferences;
1531 $result['warnings'] = $warnings;
1532 return $result;
1536 * Returns description of method result value
1538 * @return external_description
1539 * @since Moodle 3.2
1541 public static function get_user_preferences_returns() {
1542 return new external_single_structure(
1543 array(
1544 'preferences' => new external_multiple_structure(
1545 new external_single_structure(
1546 array(
1547 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1548 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1551 'User custom fields (also known as user profile fields)'
1553 'warnings' => new external_warnings()
1559 * Returns description of method parameters
1561 * @return external_function_parameters
1562 * @since Moodle 3.2
1564 public static function update_picture_parameters() {
1565 return new external_function_parameters(
1566 array(
1567 'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'),
1568 'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false),
1569 'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0)
1575 * Update or delete the user picture in the site
1577 * @param int $draftitemid id of the user draft file to use as image
1578 * @param bool $delete if we should delete the user picture
1579 * @param int $userid id of the user, 0 for current user
1580 * @return array warnings and success status
1581 * @since Moodle 3.2
1582 * @throws moodle_exception
1584 public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1585 global $CFG, $USER, $PAGE;
1587 $params = self::validate_parameters(
1588 self::update_picture_parameters(),
1589 array(
1590 'draftitemid' => $draftitemid,
1591 'delete' => $delete,
1592 'userid' => $userid
1596 $context = context_system::instance();
1597 self::validate_context($context);
1599 if (!empty($CFG->disableuserimages)) {
1600 throw new moodle_exception('userimagesdisabled', 'admin');
1603 if (empty($params['userid']) or $params['userid'] == $USER->id) {
1604 $user = $USER;
1605 require_capability('moodle/user:editownprofile', $context);
1606 } else {
1607 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1608 core_user::require_active_user($user);
1609 $personalcontext = context_user::instance($user->id);
1611 require_capability('moodle/user:editprofile', $personalcontext);
1612 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
1613 throw new moodle_exception('useradmineditadmin');
1617 // Load the appropriate auth plugin.
1618 $userauth = get_auth_plugin($user->auth);
1619 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1620 throw new moodle_exception('noprofileedit', 'auth');
1623 $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image');
1624 $user->deletepicture = $params['delete'];
1625 $user->imagefile = $params['draftitemid'];
1626 $success = core_user::update_picture($user, $filemanageroptions);
1628 $result = array(
1629 'success' => $success,
1630 'warnings' => array(),
1632 if ($success) {
1633 $userpicture = new user_picture(core_user::get_user($user->id));
1634 $userpicture->size = 1; // Size f1.
1635 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1637 return $result;
1641 * Returns description of method result value
1643 * @return external_description
1644 * @since Moodle 3.2
1646 public static function update_picture_returns() {
1647 return new external_single_structure(
1648 array(
1649 'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'),
1650 'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL),
1651 'warnings' => new external_warnings()
1657 * Returns description of method parameters
1659 * @return external_function_parameters
1660 * @since Moodle 3.2
1662 public static function set_user_preferences_parameters() {
1663 return new external_function_parameters(
1664 array(
1665 'preferences' => new external_multiple_structure(
1666 new external_single_structure(
1667 array(
1668 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1669 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1670 'userid' => new external_value(PARAM_INT, 'Id of the user to set the preference'),
1679 * Set user preferences.
1681 * @param array $preferences list of preferences including name, value and userid
1682 * @return array of warnings and preferences saved
1683 * @since Moodle 3.2
1684 * @throws moodle_exception
1686 public static function set_user_preferences($preferences) {
1687 global $USER;
1689 $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
1690 $warnings = array();
1691 $saved = array();
1693 $context = context_system::instance();
1694 self::validate_context($context);
1695 require_capability('moodle/site:config', $context);
1697 $userscache = array();
1698 foreach ($params['preferences'] as $pref) {
1699 // Check to which user set the preference.
1700 if (!empty($userscache[$pref['userid']])) {
1701 $user = $userscache[$pref['userid']];
1702 } else {
1703 try {
1704 $user = core_user::get_user($pref['userid'], '*', MUST_EXIST);
1705 core_user::require_active_user($user);
1706 $userscache[$pref['userid']] = $user;
1707 } catch (Exception $e) {
1708 $warnings[] = array(
1709 'item' => 'user',
1710 'itemid' => $pref['userid'],
1711 'warningcode' => 'invaliduser',
1712 'message' => $e->getMessage()
1714 continue;
1718 try {
1719 set_user_preference($pref['name'], $pref['value'], $user);
1720 $saved[] = array(
1721 'name' => $pref['name'],
1722 'userid' => $user->id,
1724 } catch (Exception $e) {
1725 $warnings[] = array(
1726 'item' => 'user',
1727 'itemid' => $user->id,
1728 'warningcode' => 'errorsavingpreference',
1729 'message' => $e->getMessage()
1734 $result = array();
1735 $result['saved'] = $saved;
1736 $result['warnings'] = $warnings;
1737 return $result;
1741 * Returns description of method result value
1743 * @return external_description
1744 * @since Moodle 3.2
1746 public static function set_user_preferences_returns() {
1747 return new external_single_structure(
1748 array(
1749 'saved' => new external_multiple_structure(
1750 new external_single_structure(
1751 array(
1752 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1753 'userid' => new external_value(PARAM_INT, 'The user the preference was set for'),
1755 ), 'Preferences saved'
1757 'warnings' => new external_warnings()
1763 * Returns description of method parameters.
1765 * @return external_function_parameters
1766 * @since Moodle 3.2
1768 public static function agree_site_policy_parameters() {
1769 return new external_function_parameters(array());
1773 * Agree the site policy for the current user.
1775 * @return array of warnings and status result
1776 * @since Moodle 3.2
1777 * @throws moodle_exception
1779 public static function agree_site_policy() {
1780 global $CFG, $DB, $USER;
1782 $warnings = array();
1784 $context = context_system::instance();
1785 try {
1786 // We expect an exception here since the user didn't agree the site policy yet.
1787 self::validate_context($context);
1788 } catch (Exception $e) {
1789 // We are expecting only a sitepolicynotagreed exception.
1790 if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
1791 // In case we receive a different exception, throw it.
1792 throw $e;
1796 if (empty($CFG->sitepolicy)) {
1797 $status = false;
1798 $warnings[] = array(
1799 'item' => 'user',
1800 'itemid' => $USER->id,
1801 'warningcode' => 'nositepolicy',
1802 'message' => 'The site does not have a site policy configured.'
1804 } else if (!empty($USER->policyagreed)) {
1805 $status = false;
1806 $warnings[] = array(
1807 'item' => 'user',
1808 'itemid' => $USER->id,
1809 'warningcode' => 'alreadyagreed',
1810 'message' => 'The user already agreed the site policy.'
1812 } else {
1813 $DB->set_field('user', 'policyagreed', 1, array('id' => $USER->id));
1814 $USER->policyagreed = 1;
1815 $status = true;
1818 $result = array();
1819 $result['status'] = $status;
1820 $result['warnings'] = $warnings;
1821 return $result;
1825 * Returns description of method result value.
1827 * @return external_description
1828 * @since Moodle 3.2
1830 public static function agree_site_policy_returns() {
1831 return new external_single_structure(
1832 array(
1833 'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'),
1834 'warnings' => new external_warnings()