Merge branch 'MDL-60129_master-v2' of git://github.com/markn86/moodle
[moodle.git] / user / externallib.php
blobff0ee8ee75fe40150b46308fc8d1f27e8179ca6d
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_ALPHANUMEXT, '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/profile/lib.php"); // Required for customfields related function.
138 // Ensure the current user is allowed to run this function.
139 $context = context_system::instance();
140 self::validate_context($context);
141 require_capability('moodle/user:create', $context);
143 // Do basic automatic PARAM checks on incoming data, using params description.
144 // If any problems are found then exceptions are thrown with helpful error messages.
145 $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
147 $availableauths = core_component::get_plugin_list('auth');
148 unset($availableauths['mnet']); // These would need mnethostid too.
149 unset($availableauths['webservice']); // We do not want new webservice users for now.
151 $availablethemes = core_component::get_plugin_list('theme');
152 $availablelangs = get_string_manager()->get_list_of_translations();
154 $transaction = $DB->start_delegated_transaction();
156 $userids = array();
157 $createpassword = false;
158 foreach ($params['users'] as $user) {
159 // Make sure that the username doesn't already exist.
160 if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
161 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
164 // Make sure auth is valid.
165 if (empty($availableauths[$user['auth']])) {
166 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
169 // Make sure lang is valid.
170 if (empty($availablelangs[$user['lang']])) {
171 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
174 // Make sure lang is valid.
175 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
176 // so no default value
177 // We need to test if the client sent it
178 // => !empty($user['theme']).
179 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
182 // Make sure we have a password or have to create one.
183 if (empty($user['password']) && empty($user['createpassword'])) {
184 throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
187 $user['confirmed'] = true;
188 $user['mnethostid'] = $CFG->mnet_localhost_id;
190 // Start of user info validation.
191 // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
192 if (!validate_email($user['email'])) {
193 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
194 } else if (empty($CFG->allowaccountssameemail) &&
195 $DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
196 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
198 // End of user info validation.
200 $createpassword = !empty($user['createpassword']);
201 unset($user['createpassword']);
202 if ($createpassword) {
203 $user['password'] = '';
204 $updatepassword = false;
205 } else {
206 $updatepassword = true;
209 // Create the user data now!
210 $user['id'] = user_create_user($user, $updatepassword, false);
212 // Custom fields.
213 if (!empty($user['customfields'])) {
214 foreach ($user['customfields'] as $customfield) {
215 // Profile_save_data() saves profile file it's expecting a user with the correct id,
216 // and custom field to be named profile_field_"shortname".
217 $user["profile_field_".$customfield['type']] = $customfield['value'];
219 profile_save_data((object) $user);
222 if ($createpassword) {
223 $userobject = (object)$user;
224 setnew_password_and_mail($userobject);
225 unset_user_preference('create_password', $userobject);
226 set_user_preference('auth_forcepasswordchange', 1, $userobject);
229 // Trigger event.
230 \core\event\user_created::create_from_userid($user['id'])->trigger();
232 // Preferences.
233 if (!empty($user['preferences'])) {
234 $userpref = (object)$user;
235 foreach ($user['preferences'] as $preference) {
236 $userpref->{'preference_'.$preference['type']} = $preference['value'];
238 useredit_update_user_preference($userpref);
241 $userids[] = array('id' => $user['id'], 'username' => $user['username']);
244 $transaction->allow_commit();
246 return $userids;
250 * Returns description of method result value
252 * @return external_description
253 * @since Moodle 2.2
255 public static function create_users_returns() {
256 return new external_multiple_structure(
257 new external_single_structure(
258 array(
259 'id' => new external_value(core_user::get_property_type('id'), 'user id'),
260 'username' => new external_value(core_user::get_property_type('username'), 'user name'),
268 * Returns description of method parameters
270 * @return external_function_parameters
271 * @since Moodle 2.2
273 public static function delete_users_parameters() {
274 return new external_function_parameters(
275 array(
276 'userids' => new external_multiple_structure(new external_value(core_user::get_property_type('id'), 'user ID')),
282 * Delete users
284 * @throws moodle_exception
285 * @param array $userids
286 * @return null
287 * @since Moodle 2.2
289 public static function delete_users($userids) {
290 global $CFG, $DB, $USER;
291 require_once($CFG->dirroot."/user/lib.php");
293 // Ensure the current user is allowed to run this function.
294 $context = context_system::instance();
295 require_capability('moodle/user:delete', $context);
296 self::validate_context($context);
298 $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
300 $transaction = $DB->start_delegated_transaction();
302 foreach ($params['userids'] as $userid) {
303 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
304 // Must not allow deleting of admins or self!!!
305 if (is_siteadmin($user)) {
306 throw new moodle_exception('useradminodelete', 'error');
308 if ($USER->id == $user->id) {
309 throw new moodle_exception('usernotdeletederror', 'error');
311 user_delete_user($user);
314 $transaction->allow_commit();
316 return null;
320 * Returns description of method result value
322 * @return null
323 * @since Moodle 2.2
325 public static function delete_users_returns() {
326 return null;
330 * Returns description of method parameters.
332 * @return external_function_parameters
333 * @since Moodle 3.2
335 public static function update_user_preferences_parameters() {
336 return new external_function_parameters(
337 array(
338 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
339 'emailstop' => new external_value(core_user::get_property_type('emailstop'),
340 'Enable or disable notifications for this user', VALUE_DEFAULT, null),
341 'preferences' => new external_multiple_structure(
342 new external_single_structure(
343 array(
344 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
345 'value' => new external_value(PARAM_RAW, 'The value of the preference')
347 ), 'User preferences', VALUE_DEFAULT, array()
354 * Update the user's preferences.
356 * @param int $userid
357 * @param bool|null $emailstop
358 * @param array $preferences
359 * @return null
360 * @since Moodle 3.2
362 public static function update_user_preferences($userid, $emailstop = null, $preferences = array()) {
363 global $USER, $CFG;
365 require_once($CFG->dirroot . '/user/lib.php');
366 require_once($CFG->dirroot . '/user/editlib.php');
367 require_once($CFG->dirroot . '/message/lib.php');
369 if (empty($userid)) {
370 $userid = $USER->id;
373 $systemcontext = context_system::instance();
374 self::validate_context($systemcontext);
375 $params = array(
376 'userid' => $userid,
377 'emailstop' => $emailstop,
378 'preferences' => $preferences
380 self::validate_parameters(self::update_user_preferences_parameters(), $params);
382 // Preferences.
383 if (!empty($preferences)) {
384 $userpref = ['id' => $userid];
385 foreach ($preferences as $preference) {
386 $userpref['preference_' . $preference['type']] = $preference['value'];
388 useredit_update_user_preference($userpref);
391 // Check if they want to update the email.
392 if ($emailstop !== null) {
393 $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST);
394 core_user::require_active_user($otheruser);
395 if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) {
396 $user = new stdClass();
397 $user->id = $userid;
398 $user->emailstop = $emailstop;
399 user_update_user($user);
401 // Update the $USER if we should.
402 if ($userid == $USER->id) {
403 $USER->emailstop = $emailstop;
408 return null;
412 * Returns description of method result value
414 * @return null
415 * @since Moodle 3.2
417 public static function update_user_preferences_returns() {
418 return null;
422 * Returns description of method parameters
424 * @return external_function_parameters
425 * @since Moodle 2.2
427 public static function update_users_parameters() {
428 return new external_function_parameters(
429 array(
430 'users' => new external_multiple_structure(
431 new external_single_structure(
432 array(
433 'id' =>
434 new external_value(core_user::get_property_type('id'), 'ID of the user'),
435 'username' =>
436 new external_value(core_user::get_property_type('username'), 'Username policy is defined in Moodle security config.',
437 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
438 'password' =>
439 new external_value(core_user::get_property_type('password'), 'Plain text password consisting of any characters', VALUE_OPTIONAL,
440 '', NULL_NOT_ALLOWED),
441 'firstname' =>
442 new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL, '',
443 NULL_NOT_ALLOWED),
444 'lastname' =>
445 new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
446 'email' =>
447 new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL, '',
448 NULL_NOT_ALLOWED),
449 'auth' =>
450 new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL, '',
451 NULL_NOT_ALLOWED),
452 'suspended' =>
453 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),
454 'idnumber' =>
455 new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution',
456 VALUE_OPTIONAL),
457 'lang' =>
458 new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
459 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
460 'calendartype' =>
461 new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server',
462 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
463 'theme' =>
464 new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server',
465 VALUE_OPTIONAL),
466 'timezone' =>
467 new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default',
468 VALUE_OPTIONAL),
469 'mailformat' =>
470 new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc',
471 VALUE_OPTIONAL),
472 'description' =>
473 new external_value(core_user::get_property_type('description'), 'User profile description, no HTML', VALUE_OPTIONAL),
474 'city' =>
475 new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
476 'country' =>
477 new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
478 'firstnamephonetic' =>
479 new external_value(core_user::get_property_type('firstnamephonetic'), 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
480 'lastnamephonetic' =>
481 new external_value(core_user::get_property_type('lastnamephonetic'), 'The family name phonetically of the user', VALUE_OPTIONAL),
482 'middlename' =>
483 new external_value(core_user::get_property_type('middlename'), 'The middle name of the user', VALUE_OPTIONAL),
484 'alternatename' =>
485 new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user', VALUE_OPTIONAL),
486 'userpicture' =>
487 new external_value(PARAM_INT, 'The itemid where the new user picture '.
488 'has been uploaded to, 0 to delete', VALUE_OPTIONAL),
489 'customfields' => new external_multiple_structure(
490 new external_single_structure(
491 array(
492 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
493 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
495 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
496 'preferences' => new external_multiple_structure(
497 new external_single_structure(
498 array(
499 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
500 'value' => new external_value(PARAM_RAW, 'The value of the preference')
502 ), 'User preferences', VALUE_OPTIONAL),
511 * Update users
513 * @param array $users
514 * @return null
515 * @since Moodle 2.2
517 public static function update_users($users) {
518 global $CFG, $DB, $USER;
519 require_once($CFG->dirroot."/user/lib.php");
520 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
521 require_once($CFG->dirroot.'/user/editlib.php');
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 // First check the user exists.
539 if (!$existinguser = core_user::get_user($user['id'])) {
540 continue;
542 // Check if we are trying to update an admin.
543 if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
544 continue;
546 // Other checks (deleted, remote or guest users).
547 if ($existinguser->deleted or is_mnet_remote_user($existinguser) or isguestuser($existinguser->id)) {
548 continue;
550 user_update_user($user, true, false);
552 // Update user picture if it was specified for this user.
553 if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
554 $userobject = (object)$user;
556 $userobject->deletepicture = null;
558 if ($user['userpicture'] == 0) {
559 $userobject->deletepicture = true;
560 } else {
561 $userobject->imagefile = $user['userpicture'];
564 core_user::update_picture($userobject, $filemanageroptions);
567 // Update user custom fields.
568 if (!empty($user['customfields'])) {
570 foreach ($user['customfields'] as $customfield) {
571 // Profile_save_data() saves profile file it's expecting a user with the correct id,
572 // and custom field to be named profile_field_"shortname".
573 $user["profile_field_".$customfield['type']] = $customfield['value'];
575 profile_save_data((object) $user);
578 // Trigger event.
579 \core\event\user_updated::create_from_userid($user['id'])->trigger();
581 // Preferences.
582 if (!empty($user['preferences'])) {
583 $userpref = clone($existinguser);
584 foreach ($user['preferences'] as $preference) {
585 $userpref->{'preference_'.$preference['type']} = $preference['value'];
587 useredit_update_user_preference($userpref);
589 if (isset($user['suspended']) and $user['suspended']) {
590 \core\session\manager::kill_user_sessions($user['id']);
594 $transaction->allow_commit();
596 return null;
600 * Returns description of method result value
602 * @return null
603 * @since Moodle 2.2
605 public static function update_users_returns() {
606 return null;
610 * Returns description of method parameters
612 * @return external_function_parameters
613 * @since Moodle 2.4
615 public static function get_users_by_field_parameters() {
616 return new external_function_parameters(
617 array(
618 'field' => new external_value(PARAM_ALPHA, 'the search field can be
619 \'id\' or \'idnumber\' or \'username\' or \'email\''),
620 'values' => new external_multiple_structure(
621 new external_value(PARAM_RAW, 'the value to match'))
627 * Get user information for a unique field.
629 * @throws coding_exception
630 * @throws invalid_parameter_exception
631 * @param string $field
632 * @param array $values
633 * @return array An array of arrays containg user profiles.
634 * @since Moodle 2.4
636 public static function get_users_by_field($field, $values) {
637 global $CFG, $USER, $DB;
638 require_once($CFG->dirroot . "/user/lib.php");
640 $params = self::validate_parameters(self::get_users_by_field_parameters(),
641 array('field' => $field, 'values' => $values));
643 // This array will keep all the users that are allowed to be searched,
644 // according to the current user's privileges.
645 $cleanedvalues = array();
647 switch ($field) {
648 case 'id':
649 $paramtype = core_user::get_property_type('id');
650 break;
651 case 'idnumber':
652 $paramtype = core_user::get_property_type('idnumber');
653 break;
654 case 'username':
655 $paramtype = core_user::get_property_type('username');
656 break;
657 case 'email':
658 $paramtype = core_user::get_property_type('email');
659 break;
660 default:
661 throw new coding_exception('invalid field parameter',
662 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
665 // Clean the values.
666 foreach ($values as $value) {
667 $cleanedvalue = clean_param($value, $paramtype);
668 if ( $value != $cleanedvalue) {
669 throw new invalid_parameter_exception('The field \'' . $field .
670 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
672 $cleanedvalues[] = $cleanedvalue;
675 // Retrieve the users.
676 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
678 $context = context_system::instance();
679 self::validate_context($context);
681 // Finally retrieve each users information.
682 $returnedusers = array();
683 foreach ($users as $user) {
684 $userdetails = user_get_user_details_courses($user);
686 // Return the user only if the searched field is returned.
687 // Otherwise it means that the $USER was not allowed to search the returned user.
688 if (!empty($userdetails) and !empty($userdetails[$field])) {
689 $returnedusers[] = $userdetails;
693 return $returnedusers;
697 * Returns description of method result value
699 * @return external_multiple_structure
700 * @since Moodle 2.4
702 public static function get_users_by_field_returns() {
703 return new external_multiple_structure(self::user_description());
708 * Returns description of get_users() parameters.
710 * @return external_function_parameters
711 * @since Moodle 2.5
713 public static function get_users_parameters() {
714 return new external_function_parameters(
715 array(
716 'criteria' => new external_multiple_structure(
717 new external_single_structure(
718 array(
719 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
720 "id" (int) matching user id,
721 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
722 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
723 "idnumber" (string) matching user idnumber,
724 "username" (string) matching user username,
725 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
726 "auth" (string) matching user auth plugin'),
727 'value' => new external_value(PARAM_RAW, 'the value to search')
729 ), 'the key/value pairs to be considered in user search. Values can not be empty.
730 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
731 key occurences are forbidden.
732 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
733 the search is still executed on the valid criterias.
734 You can search without criteria, but the function is not designed for it.
735 It could very slow or timeout. The function is designed to search some specific users.'
742 * Retrieve matching user.
744 * @throws moodle_exception
745 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
746 * @return array An array of arrays containing user profiles.
747 * @since Moodle 2.5
749 public static function get_users($criteria = array()) {
750 global $CFG, $USER, $DB;
752 require_once($CFG->dirroot . "/user/lib.php");
754 $params = self::validate_parameters(self::get_users_parameters(),
755 array('criteria' => $criteria));
757 // Validate the criteria and retrieve the users.
758 $users = array();
759 $warnings = array();
760 $sqlparams = array();
761 $usedkeys = array();
763 // Do not retrieve deleted users.
764 $sql = ' deleted = 0';
766 foreach ($params['criteria'] as $criteriaindex => $criteria) {
768 // Check that the criteria has never been used.
769 if (array_key_exists($criteria['key'], $usedkeys)) {
770 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
771 } else {
772 $usedkeys[$criteria['key']] = true;
775 $invalidcriteria = false;
776 // Clean the parameters.
777 $paramtype = PARAM_RAW;
778 switch ($criteria['key']) {
779 case 'id':
780 $paramtype = core_user::get_property_type('id');
781 break;
782 case 'idnumber':
783 $paramtype = core_user::get_property_type('idnumber');
784 break;
785 case 'username':
786 $paramtype = core_user::get_property_type('username');
787 break;
788 case 'email':
789 // We use PARAM_RAW to allow searches with %.
790 $paramtype = core_user::get_property_type('email');
791 break;
792 case 'auth':
793 $paramtype = core_user::get_property_type('auth');
794 break;
795 case 'lastname':
796 case 'firstname':
797 $paramtype = core_user::get_property_type('firstname');
798 break;
799 default:
800 // Send back a warning that this search key is not supported in this version.
801 // This warning will make the function extandable without breaking clients.
802 $warnings[] = array(
803 'item' => $criteria['key'],
804 'warningcode' => 'invalidfieldparameter',
805 'message' =>
806 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
808 // Do not add this invalid criteria to the created SQL request.
809 $invalidcriteria = true;
810 unset($params['criteria'][$criteriaindex]);
811 break;
814 if (!$invalidcriteria) {
815 $cleanedvalue = clean_param($criteria['value'], $paramtype);
817 $sql .= ' AND ';
819 // Create the SQL.
820 switch ($criteria['key']) {
821 case 'id':
822 case 'idnumber':
823 case 'username':
824 case 'auth':
825 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
826 $sqlparams[$criteria['key']] = $cleanedvalue;
827 break;
828 case 'email':
829 case 'lastname':
830 case 'firstname':
831 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
832 $sqlparams[$criteria['key']] = $cleanedvalue;
833 break;
834 default:
835 break;
840 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
842 // Finally retrieve each users information.
843 $returnedusers = array();
844 foreach ($users as $user) {
845 $userdetails = user_get_user_details_courses($user);
847 // Return the user only if all the searched fields are returned.
848 // Otherwise it means that the $USER was not allowed to search the returned user.
849 if (!empty($userdetails)) {
850 $validuser = true;
852 foreach ($params['criteria'] as $criteria) {
853 if (empty($userdetails[$criteria['key']])) {
854 $validuser = false;
858 if ($validuser) {
859 $returnedusers[] = $userdetails;
864 return array('users' => $returnedusers, 'warnings' => $warnings);
868 * Returns description of get_users result value.
870 * @return external_description
871 * @since Moodle 2.5
873 public static function get_users_returns() {
874 return new external_single_structure(
875 array('users' => new external_multiple_structure(
876 self::user_description()
878 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
884 * Returns description of method parameters
886 * @return external_function_parameters
887 * @since Moodle 2.2
889 public static function get_course_user_profiles_parameters() {
890 return new external_function_parameters(
891 array(
892 'userlist' => new external_multiple_structure(
893 new external_single_structure(
894 array(
895 'userid' => new external_value(core_user::get_property_type('id'), 'userid'),
896 'courseid' => new external_value(PARAM_INT, 'courseid'),
905 * Get course participant's details
907 * @param array $userlist array of user ids and according course ids
908 * @return array An array of arrays describing course participants
909 * @since Moodle 2.2
911 public static function get_course_user_profiles($userlist) {
912 global $CFG, $USER, $DB;
913 require_once($CFG->dirroot . "/user/lib.php");
914 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
916 $userids = array();
917 $courseids = array();
918 foreach ($params['userlist'] as $value) {
919 $userids[] = $value['userid'];
920 $courseids[$value['userid']] = $value['courseid'];
923 // Cache all courses.
924 $courses = array();
925 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
926 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
927 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
928 $params['contextlevel'] = CONTEXT_COURSE;
929 $coursesql = "SELECT c.* $cselect
930 FROM {course} c $cjoin
931 WHERE c.id $sqlcourseids";
932 $rs = $DB->get_recordset_sql($coursesql, $params);
933 foreach ($rs as $course) {
934 // Adding course contexts to cache.
935 context_helper::preload_from_record($course);
936 // Cache courses.
937 $courses[$course->id] = $course;
939 $rs->close();
941 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
942 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
943 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
944 $params['contextlevel'] = CONTEXT_USER;
945 $usersql = "SELECT u.* $uselect
946 FROM {user} u $ujoin
947 WHERE u.id $sqluserids";
948 $users = $DB->get_recordset_sql($usersql, $params);
949 $result = array();
950 foreach ($users as $user) {
951 if (!empty($user->deleted)) {
952 continue;
954 context_helper::preload_from_record($user);
955 $course = $courses[$courseids[$user->id]];
956 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
957 self::validate_context($context);
958 if ($userarray = user_get_user_details($user, $course)) {
959 $result[] = $userarray;
963 $users->close();
965 return $result;
969 * Returns description of method result value
971 * @return external_description
972 * @since Moodle 2.2
974 public static function get_course_user_profiles_returns() {
975 $additionalfields = array(
976 'groups' => new external_multiple_structure(
977 new external_single_structure(
978 array(
979 'id' => new external_value(PARAM_INT, 'group id'),
980 'name' => new external_value(PARAM_RAW, 'group name'),
981 'description' => new external_value(PARAM_RAW, 'group description'),
982 'descriptionformat' => new external_format_value('description'),
984 ), 'user groups', VALUE_OPTIONAL),
985 'roles' => new external_multiple_structure(
986 new external_single_structure(
987 array(
988 'roleid' => new external_value(PARAM_INT, 'role id'),
989 'name' => new external_value(PARAM_RAW, 'role name'),
990 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
991 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
993 ), 'user roles', VALUE_OPTIONAL),
994 'enrolledcourses' => new external_multiple_structure(
995 new external_single_structure(
996 array(
997 'id' => new external_value(PARAM_INT, 'Id of the course'),
998 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
999 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
1001 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
1004 return new external_multiple_structure(self::user_description($additionalfields));
1008 * Create user return value description.
1010 * @param array $additionalfields some additional field
1011 * @return single_structure_description
1013 public static function user_description($additionalfields = array()) {
1014 $userfields = array(
1015 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
1016 'username' => new external_value(core_user::get_property_type('username'), 'The username', VALUE_OPTIONAL),
1017 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL),
1018 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
1019 'fullname' => new external_value(core_user::get_property_type('firstname'), 'The fullname of the user'),
1020 'email' => new external_value(core_user::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
1021 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
1022 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
1023 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
1024 'icq' => new external_value(core_user::get_property_type('icq'), 'icq number', VALUE_OPTIONAL),
1025 'skype' => new external_value(core_user::get_property_type('skype'), 'skype id', VALUE_OPTIONAL),
1026 'yahoo' => new external_value(core_user::get_property_type('yahoo'), 'yahoo id', VALUE_OPTIONAL),
1027 'aim' => new external_value(core_user::get_property_type('aim'), 'aim id', VALUE_OPTIONAL),
1028 'msn' => new external_value(core_user::get_property_type('msn'), 'msn number', VALUE_OPTIONAL),
1029 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
1030 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
1031 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
1032 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
1033 'firstaccess' => new external_value(core_user::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL),
1034 'lastaccess' => new external_value(core_user::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL),
1035 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL),
1036 'suspended' => new external_value(core_user::get_property_type('suspended'), 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
1037 'confirmed' => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
1038 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
1039 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
1040 'theme' => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
1041 'timezone' => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
1042 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
1043 'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL),
1044 'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL),
1045 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
1046 'url' => new external_value(core_user::get_property_type('url'), 'URL of the user', VALUE_OPTIONAL),
1047 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
1048 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
1049 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
1050 'customfields' => new external_multiple_structure(
1051 new external_single_structure(
1052 array(
1053 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
1054 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
1055 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
1056 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
1058 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
1059 'preferences' => new external_multiple_structure(
1060 new external_single_structure(
1061 array(
1062 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
1063 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
1065 ), 'Users preferences', VALUE_OPTIONAL)
1067 if (!empty($additionalfields)) {
1068 $userfields = array_merge($userfields, $additionalfields);
1070 return new external_single_structure($userfields);
1074 * Returns description of method parameters
1076 * @return external_function_parameters
1077 * @since Moodle 2.6
1079 public static function add_user_private_files_parameters() {
1080 return new external_function_parameters(
1081 array(
1082 'draftid' => new external_value(PARAM_INT, 'draft area id')
1088 * Copy files from a draft area to users private files area.
1090 * @throws invalid_parameter_exception
1091 * @param int $draftid Id of a draft area containing files.
1092 * @return array An array of warnings
1093 * @since Moodle 2.6
1095 public static function add_user_private_files($draftid) {
1096 global $CFG, $USER;
1097 require_once($CFG->libdir . "/filelib.php");
1099 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
1101 if (isguestuser()) {
1102 throw new invalid_parameter_exception('Guest users cannot upload files');
1105 $context = context_user::instance($USER->id);
1106 require_capability('moodle/user:manageownfiles', $context);
1108 $maxbytes = $CFG->userquota;
1109 $maxareabytes = $CFG->userquota;
1110 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1111 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1112 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1115 $options = array('subdirs' => 1,
1116 'maxbytes' => $maxbytes,
1117 'maxfiles' => -1,
1118 'areamaxbytes' => $maxareabytes);
1120 file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options);
1122 return null;
1126 * Returns description of method result value
1128 * @return external_description
1129 * @since Moodle 2.2
1131 public static function add_user_private_files_returns() {
1132 return null;
1136 * Returns description of method parameters.
1138 * @return external_function_parameters
1139 * @since Moodle 2.6
1141 public static function add_user_device_parameters() {
1142 return new external_function_parameters(
1143 array(
1144 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1145 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1146 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1147 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1148 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1149 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1150 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1156 * Add a user device in Moodle database (for PUSH notifications usually).
1158 * @throws moodle_exception
1159 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1160 * @param string $name The device name, occam or iPhone etc.
1161 * @param string $model The device model Nexus4 or iPad1.1 etc.
1162 * @param string $platform The device platform iOs or Android etc.
1163 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1164 * @param string $pushid The device PUSH token/key/identifier/registration id.
1165 * @param string $uuid The device UUID.
1166 * @return array List of possible warnings.
1167 * @since Moodle 2.6
1169 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1170 global $CFG, $USER, $DB;
1171 require_once($CFG->dirroot . "/user/lib.php");
1173 $params = self::validate_parameters(self::add_user_device_parameters(),
1174 array('appid' => $appid,
1175 'name' => $name,
1176 'model' => $model,
1177 'platform' => $platform,
1178 'version' => $version,
1179 'pushid' => $pushid,
1180 'uuid' => $uuid
1183 $warnings = array();
1185 // Prevent duplicate keys for users.
1186 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1187 $warnings['warning'][] = array(
1188 'item' => $params['pushid'],
1189 'warningcode' => 'existingkeyforthisuser',
1190 'message' => 'This key is already stored for this user'
1192 return $warnings;
1195 // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1196 // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1197 if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1198 'appid' => $params['appid'], 'userid' => $USER->id))) {
1200 foreach ($userdevices as $userdevice) {
1201 $userdevice->version = $params['version']; // Maybe the user upgraded the device.
1202 $userdevice->pushid = $params['pushid'];
1203 $userdevice->timemodified = time();
1204 $DB->update_record('user_devices', $userdevice);
1207 } else {
1208 $userdevice = new stdclass;
1209 $userdevice->userid = $USER->id;
1210 $userdevice->appid = $params['appid'];
1211 $userdevice->name = $params['name'];
1212 $userdevice->model = $params['model'];
1213 $userdevice->platform = $params['platform'];
1214 $userdevice->version = $params['version'];
1215 $userdevice->pushid = $params['pushid'];
1216 $userdevice->uuid = $params['uuid'];
1217 $userdevice->timecreated = time();
1218 $userdevice->timemodified = $userdevice->timecreated;
1220 if (!$DB->insert_record('user_devices', $userdevice)) {
1221 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1225 return $warnings;
1229 * Returns description of method result value.
1231 * @return external_multiple_structure
1232 * @since Moodle 2.6
1234 public static function add_user_device_returns() {
1235 return new external_multiple_structure(
1236 new external_warnings()
1241 * Returns description of method parameters.
1243 * @return external_function_parameters
1244 * @since Moodle 2.9
1246 public static function remove_user_device_parameters() {
1247 return new external_function_parameters(
1248 array(
1249 'uuid' => new external_value(PARAM_RAW, 'the device UUID'),
1250 'appid' => new external_value(PARAM_NOTAGS,
1251 'the app id, if empty devices matching the UUID for the user will be removed',
1252 VALUE_DEFAULT, ''),
1258 * Remove a user device from the Moodle database (for PUSH notifications usually).
1260 * @param string $uuid The device UUID.
1261 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1262 * @return array List of possible warnings and removal status.
1263 * @since Moodle 2.9
1265 public static function remove_user_device($uuid, $appid = "") {
1266 global $CFG;
1267 require_once($CFG->dirroot . "/user/lib.php");
1269 $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1271 $context = context_system::instance();
1272 self::validate_context($context);
1274 // Warnings array, it can be empty at the end but is mandatory.
1275 $warnings = array();
1277 $removed = user_remove_user_device($params['uuid'], $params['appid']);
1279 if (!$removed) {
1280 $warnings[] = array(
1281 'item' => $params['uuid'],
1282 'warningcode' => 'devicedoesnotexist',
1283 'message' => 'The device doesn\'t exists in the database'
1287 $result = array(
1288 'removed' => $removed,
1289 'warnings' => $warnings
1292 return $result;
1296 * Returns description of method result value.
1298 * @return external_multiple_structure
1299 * @since Moodle 2.9
1301 public static function remove_user_device_returns() {
1302 return new external_single_structure(
1303 array(
1304 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
1305 'warnings' => new external_warnings(),
1311 * Returns description of method parameters
1313 * @return external_function_parameters
1314 * @since Moodle 2.9
1316 public static function view_user_list_parameters() {
1317 return new external_function_parameters(
1318 array(
1319 'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site')
1325 * Trigger the user_list_viewed event.
1327 * @param int $courseid id of course
1328 * @return array of warnings and status result
1329 * @since Moodle 2.9
1330 * @throws moodle_exception
1332 public static function view_user_list($courseid) {
1333 global $CFG;
1334 require_once($CFG->dirroot . "/user/lib.php");
1335 require_once($CFG->dirroot . '/course/lib.php');
1337 $params = self::validate_parameters(self::view_user_list_parameters(),
1338 array(
1339 'courseid' => $courseid
1342 $warnings = array();
1344 if (empty($params['courseid'])) {
1345 $params['courseid'] = SITEID;
1348 $course = get_course($params['courseid']);
1350 if ($course->id == SITEID) {
1351 $context = context_system::instance();
1352 } else {
1353 $context = context_course::instance($course->id);
1355 self::validate_context($context);
1357 course_require_view_participants($context);
1359 user_list_view($course, $context);
1361 $result = array();
1362 $result['status'] = true;
1363 $result['warnings'] = $warnings;
1364 return $result;
1368 * Returns description of method result value
1370 * @return external_description
1371 * @since Moodle 2.9
1373 public static function view_user_list_returns() {
1374 return new external_single_structure(
1375 array(
1376 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1377 'warnings' => new external_warnings()
1383 * Returns description of method parameters
1385 * @return external_function_parameters
1386 * @since Moodle 2.9
1388 public static function view_user_profile_parameters() {
1389 return new external_function_parameters(
1390 array(
1391 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1392 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
1398 * Trigger the user profile viewed event.
1400 * @param int $userid id of user
1401 * @param int $courseid id of course
1402 * @return array of warnings and status result
1403 * @since Moodle 2.9
1404 * @throws moodle_exception
1406 public static function view_user_profile($userid, $courseid = 0) {
1407 global $CFG, $USER;
1408 require_once($CFG->dirroot . "/user/profile/lib.php");
1410 $params = self::validate_parameters(self::view_user_profile_parameters(),
1411 array(
1412 'userid' => $userid,
1413 'courseid' => $courseid
1416 $warnings = array();
1418 if (empty($params['userid'])) {
1419 $params['userid'] = $USER->id;
1422 if (empty($params['courseid'])) {
1423 $params['courseid'] = SITEID;
1426 $course = get_course($params['courseid']);
1427 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1428 core_user::require_active_user($user);
1430 if ($course->id == SITEID) {
1431 $coursecontext = context_system::instance();;
1432 } else {
1433 $coursecontext = context_course::instance($course->id);
1435 self::validate_context($coursecontext);
1437 $currentuser = $USER->id == $user->id;
1438 $usercontext = context_user::instance($user->id);
1440 if (!$currentuser and
1441 !has_capability('moodle/user:viewdetails', $coursecontext) and
1442 !has_capability('moodle/user:viewdetails', $usercontext)) {
1443 throw new moodle_exception('cannotviewprofile');
1446 // Case like user/profile.php.
1447 if ($course->id == SITEID) {
1448 profile_view($user, $usercontext);
1449 } else {
1450 // Case like user/view.php.
1451 if (!$currentuser and !can_access_course($course, $user, '', true)) {
1452 throw new moodle_exception('notenrolledprofile');
1455 profile_view($user, $coursecontext, $course);
1458 $result = array();
1459 $result['status'] = true;
1460 $result['warnings'] = $warnings;
1461 return $result;
1465 * Returns description of method result value
1467 * @return external_description
1468 * @since Moodle 2.9
1470 public static function view_user_profile_returns() {
1471 return new external_single_structure(
1472 array(
1473 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1474 'warnings' => new external_warnings()
1480 * Returns description of method parameters
1482 * @return external_function_parameters
1483 * @since Moodle 3.2
1485 public static function get_user_preferences_parameters() {
1486 return new external_function_parameters(
1487 array(
1488 'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''),
1489 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0)
1495 * Return user preferences.
1497 * @param string $name preference name, empty for all
1498 * @param int $userid id of the user, 0 for current user
1499 * @return array of warnings and preferences
1500 * @since Moodle 3.2
1501 * @throws moodle_exception
1503 public static function get_user_preferences($name = '', $userid = 0) {
1504 global $USER;
1506 $params = self::validate_parameters(self::get_user_preferences_parameters(),
1507 array(
1508 'name' => $name,
1509 'userid' => $userid
1511 $preferences = array();
1512 $warnings = array();
1514 $context = context_system::instance();
1515 self::validate_context($context);
1517 if (empty($params['name'])) {
1518 $name = null;
1520 if (empty($params['userid'])) {
1521 $user = null;
1522 } else {
1523 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1524 core_user::require_active_user($user);
1525 if ($user->id != $USER->id) {
1526 // Only admins can retrieve other users preferences.
1527 require_capability('moodle/site:config', $context);
1531 $userpreferences = get_user_preferences($name, null, $user);
1532 // Check if we received just one preference.
1533 if (!is_array($userpreferences)) {
1534 $userpreferences = array($name => $userpreferences);
1537 foreach ($userpreferences as $name => $value) {
1538 $preferences[] = array(
1539 'name' => $name,
1540 'value' => $value,
1544 $result = array();
1545 $result['preferences'] = $preferences;
1546 $result['warnings'] = $warnings;
1547 return $result;
1551 * Returns description of method result value
1553 * @return external_description
1554 * @since Moodle 3.2
1556 public static function get_user_preferences_returns() {
1557 return new external_single_structure(
1558 array(
1559 'preferences' => new external_multiple_structure(
1560 new external_single_structure(
1561 array(
1562 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1563 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1566 'User custom fields (also known as user profile fields)'
1568 'warnings' => new external_warnings()
1574 * Returns description of method parameters
1576 * @return external_function_parameters
1577 * @since Moodle 3.2
1579 public static function update_picture_parameters() {
1580 return new external_function_parameters(
1581 array(
1582 'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'),
1583 'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false),
1584 'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0)
1590 * Update or delete the user picture in the site
1592 * @param int $draftitemid id of the user draft file to use as image
1593 * @param bool $delete if we should delete the user picture
1594 * @param int $userid id of the user, 0 for current user
1595 * @return array warnings and success status
1596 * @since Moodle 3.2
1597 * @throws moodle_exception
1599 public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1600 global $CFG, $USER, $PAGE;
1602 $params = self::validate_parameters(
1603 self::update_picture_parameters(),
1604 array(
1605 'draftitemid' => $draftitemid,
1606 'delete' => $delete,
1607 'userid' => $userid
1611 $context = context_system::instance();
1612 self::validate_context($context);
1614 if (!empty($CFG->disableuserimages)) {
1615 throw new moodle_exception('userimagesdisabled', 'admin');
1618 if (empty($params['userid']) or $params['userid'] == $USER->id) {
1619 $user = $USER;
1620 require_capability('moodle/user:editownprofile', $context);
1621 } else {
1622 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1623 core_user::require_active_user($user);
1624 $personalcontext = context_user::instance($user->id);
1626 require_capability('moodle/user:editprofile', $personalcontext);
1627 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
1628 throw new moodle_exception('useradmineditadmin');
1632 // Load the appropriate auth plugin.
1633 $userauth = get_auth_plugin($user->auth);
1634 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1635 throw new moodle_exception('noprofileedit', 'auth');
1638 $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image');
1639 $user->deletepicture = $params['delete'];
1640 $user->imagefile = $params['draftitemid'];
1641 $success = core_user::update_picture($user, $filemanageroptions);
1643 $result = array(
1644 'success' => $success,
1645 'warnings' => array(),
1647 if ($success) {
1648 $userpicture = new user_picture(core_user::get_user($user->id));
1649 $userpicture->size = 1; // Size f1.
1650 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1652 return $result;
1656 * Returns description of method result value
1658 * @return external_description
1659 * @since Moodle 3.2
1661 public static function update_picture_returns() {
1662 return new external_single_structure(
1663 array(
1664 'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'),
1665 'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL),
1666 'warnings' => new external_warnings()
1672 * Returns description of method parameters
1674 * @return external_function_parameters
1675 * @since Moodle 3.2
1677 public static function set_user_preferences_parameters() {
1678 return new external_function_parameters(
1679 array(
1680 'preferences' => new external_multiple_structure(
1681 new external_single_structure(
1682 array(
1683 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1684 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1685 'userid' => new external_value(PARAM_INT, 'Id of the user to set the preference'),
1694 * Set user preferences.
1696 * @param array $preferences list of preferences including name, value and userid
1697 * @return array of warnings and preferences saved
1698 * @since Moodle 3.2
1699 * @throws moodle_exception
1701 public static function set_user_preferences($preferences) {
1702 global $USER;
1704 $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
1705 $warnings = array();
1706 $saved = array();
1708 $context = context_system::instance();
1709 self::validate_context($context);
1711 $userscache = array();
1712 foreach ($params['preferences'] as $pref) {
1713 // Check to which user set the preference.
1714 if (!empty($userscache[$pref['userid']])) {
1715 $user = $userscache[$pref['userid']];
1716 } else {
1717 try {
1718 $user = core_user::get_user($pref['userid'], '*', MUST_EXIST);
1719 core_user::require_active_user($user);
1720 $userscache[$pref['userid']] = $user;
1721 } catch (Exception $e) {
1722 $warnings[] = array(
1723 'item' => 'user',
1724 'itemid' => $pref['userid'],
1725 'warningcode' => 'invaliduser',
1726 'message' => $e->getMessage()
1728 continue;
1732 try {
1733 if (core_user::can_edit_preference($pref['name'], $user)) {
1734 $value = core_user::clean_preference($pref['value'], $pref['name']);
1735 set_user_preference($pref['name'], $value, $user->id);
1736 $saved[] = array(
1737 'name' => $pref['name'],
1738 'userid' => $user->id,
1740 } else {
1741 $warnings[] = array(
1742 'item' => 'user',
1743 'itemid' => $user->id,
1744 'warningcode' => 'nopermission',
1745 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id
1748 } catch (Exception $e) {
1749 $warnings[] = array(
1750 'item' => 'user',
1751 'itemid' => $user->id,
1752 'warningcode' => 'errorsavingpreference',
1753 'message' => $e->getMessage()
1758 $result = array();
1759 $result['saved'] = $saved;
1760 $result['warnings'] = $warnings;
1761 return $result;
1765 * Returns description of method result value
1767 * @return external_description
1768 * @since Moodle 3.2
1770 public static function set_user_preferences_returns() {
1771 return new external_single_structure(
1772 array(
1773 'saved' => new external_multiple_structure(
1774 new external_single_structure(
1775 array(
1776 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1777 'userid' => new external_value(PARAM_INT, 'The user the preference was set for'),
1779 ), 'Preferences saved'
1781 'warnings' => new external_warnings()
1787 * Returns description of method parameters.
1789 * @return external_function_parameters
1790 * @since Moodle 3.2
1792 public static function agree_site_policy_parameters() {
1793 return new external_function_parameters(array());
1797 * Agree the site policy for the current user.
1799 * @return array of warnings and status result
1800 * @since Moodle 3.2
1801 * @throws moodle_exception
1803 public static function agree_site_policy() {
1804 global $CFG, $DB, $USER;
1806 $warnings = array();
1808 $context = context_system::instance();
1809 try {
1810 // We expect an exception here since the user didn't agree the site policy yet.
1811 self::validate_context($context);
1812 } catch (Exception $e) {
1813 // We are expecting only a sitepolicynotagreed exception.
1814 if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
1815 // In case we receive a different exception, throw it.
1816 throw $e;
1820 if (empty($CFG->sitepolicy)) {
1821 $status = false;
1822 $warnings[] = array(
1823 'item' => 'user',
1824 'itemid' => $USER->id,
1825 'warningcode' => 'nositepolicy',
1826 'message' => 'The site does not have a site policy configured.'
1828 } else if (!empty($USER->policyagreed)) {
1829 $status = false;
1830 $warnings[] = array(
1831 'item' => 'user',
1832 'itemid' => $USER->id,
1833 'warningcode' => 'alreadyagreed',
1834 'message' => 'The user already agreed the site policy.'
1836 } else {
1837 $DB->set_field('user', 'policyagreed', 1, array('id' => $USER->id));
1838 $USER->policyagreed = 1;
1839 $status = true;
1842 $result = array();
1843 $result['status'] = $status;
1844 $result['warnings'] = $warnings;
1845 return $result;
1849 * Returns description of method result value.
1851 * @return external_description
1852 * @since Moodle 3.2
1854 public static function agree_site_policy_returns() {
1855 return new external_single_structure(
1856 array(
1857 'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'),
1858 'warnings' => new external_warnings()
1864 * Returns description of method parameters.
1866 * @return external_function_parameters
1867 * @since Moodle 3.4
1869 public static function get_private_files_info_parameters() {
1870 return new external_function_parameters(
1871 array(
1872 'userid' => new external_value(PARAM_INT, 'Id of the user, default to current user.', VALUE_DEFAULT, 0)
1878 * Returns general information about files in the user private files area.
1880 * @param int $userid Id of the user, default to current user.
1881 * @return array of warnings and file area information
1882 * @since Moodle 3.4
1883 * @throws moodle_exception
1885 public static function get_private_files_info($userid = 0) {
1886 global $CFG, $USER;
1887 require_once($CFG->libdir . '/filelib.php');
1889 $params = self::validate_parameters(self::get_private_files_info_parameters(), array('userid' => $userid));
1890 $warnings = array();
1892 $context = context_system::instance();
1893 self::validate_context($context);
1895 if (empty($params['userid']) || $params['userid'] == $USER->id) {
1896 $usercontext = context_user::instance($USER->id);
1897 require_capability('moodle/user:manageownfiles', $usercontext);
1898 } else {
1899 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1900 core_user::require_active_user($user);
1901 // Only admins can retrieve other users information.
1902 require_capability('moodle/site:config', $context);
1903 $usercontext = context_user::instance($user->id);
1906 $fileareainfo = file_get_file_area_info($usercontext->id, 'user', 'private');
1908 $result = array();
1909 $result['filecount'] = $fileareainfo['filecount'];
1910 $result['foldercount'] = $fileareainfo['foldercount'];
1911 $result['filesize'] = $fileareainfo['filesize'];
1912 $result['filesizewithoutreferences'] = $fileareainfo['filesize_without_references'];
1913 $result['warnings'] = $warnings;
1914 return $result;
1918 * Returns description of method result value.
1920 * @return external_description
1921 * @since Moodle 3.4
1923 public static function get_private_files_info_returns() {
1924 return new external_single_structure(
1925 array(
1926 'filecount' => new external_value(PARAM_INT, 'Number of files in the area.'),
1927 'foldercount' => new external_value(PARAM_INT, 'Number of folders in the area.'),
1928 'filesize' => new external_value(PARAM_INT, 'Total size of the files in the area.'),
1929 'filesizewithoutreferences' => new external_value(PARAM_INT, 'Total size of the area excluding file references'),
1930 'warnings' => new external_warnings()