Merge branch 'wip-mdl-57245' of https://github.com/rajeshtaneja/moodle
[moodle.git] / user / externallib.php
bloba32605c31893115c03d0f7f71f6f4fe444c17bf3
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 'suspended' =>
456 new external_value(core_user::get_property_type('suspended'), 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
457 'idnumber' =>
458 new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution',
459 VALUE_OPTIONAL),
460 'lang' =>
461 new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
462 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
463 'calendartype' =>
464 new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server',
465 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
466 'theme' =>
467 new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server',
468 VALUE_OPTIONAL),
469 'timezone' =>
470 new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default',
471 VALUE_OPTIONAL),
472 'mailformat' =>
473 new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc',
474 VALUE_OPTIONAL),
475 'description' =>
476 new external_value(core_user::get_property_type('description'), 'User profile description, no HTML', VALUE_OPTIONAL),
477 'city' =>
478 new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
479 'country' =>
480 new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
481 'firstnamephonetic' =>
482 new external_value(core_user::get_property_type('firstnamephonetic'), 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
483 'lastnamephonetic' =>
484 new external_value(core_user::get_property_type('lastnamephonetic'), 'The family name phonetically of the user', VALUE_OPTIONAL),
485 'middlename' =>
486 new external_value(core_user::get_property_type('middlename'), 'The middle name of the user', VALUE_OPTIONAL),
487 'alternatename' =>
488 new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user', VALUE_OPTIONAL),
489 'userpicture' =>
490 new external_value(PARAM_INT, 'The itemid where the new user picture '.
491 'has been uploaded to, 0 to delete', VALUE_OPTIONAL),
492 'customfields' => new external_multiple_structure(
493 new external_single_structure(
494 array(
495 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
496 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
498 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
499 'preferences' => new external_multiple_structure(
500 new external_single_structure(
501 array(
502 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
503 'value' => new external_value(PARAM_RAW, 'The value of the preference')
505 ), 'User preferences', VALUE_OPTIONAL),
514 * Update users
516 * @param array $users
517 * @return null
518 * @since Moodle 2.2
520 public static function update_users($users) {
521 global $CFG, $DB, $USER;
522 require_once($CFG->dirroot."/user/lib.php");
523 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
525 // Ensure the current user is allowed to run this function.
526 $context = context_system::instance();
527 require_capability('moodle/user:update', $context);
528 self::validate_context($context);
530 $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
532 $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
533 'subdirs' => 0,
534 'maxfiles' => 1,
535 'accepted_types' => 'web_image');
537 $transaction = $DB->start_delegated_transaction();
539 foreach ($params['users'] as $user) {
540 // First check the user exists.
541 if (!$existinguser = core_user::get_user($user['id'])) {
542 continue;
544 // Check if we are trying to update an admin.
545 if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
546 continue;
548 // Other checks (deleted, remote or guest users).
549 if ($existinguser->deleted or is_mnet_remote_user($existinguser) or isguestuser($existinguser->id)) {
550 continue;
552 user_update_user($user, true, false);
554 // Update user picture if it was specified for this user.
555 if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
556 $userobject = (object)$user;
558 $userobject->deletepicture = null;
560 if ($user['userpicture'] == 0) {
561 $userobject->deletepicture = true;
562 } else {
563 $userobject->imagefile = $user['userpicture'];
566 core_user::update_picture($userobject, $filemanageroptions);
569 // Update user custom fields.
570 if (!empty($user['customfields'])) {
572 foreach ($user['customfields'] as $customfield) {
573 // Profile_save_data() saves profile file it's expecting a user with the correct id,
574 // and custom field to be named profile_field_"shortname".
575 $user["profile_field_".$customfield['type']] = $customfield['value'];
577 profile_save_data((object) $user);
580 // Trigger event.
581 \core\event\user_updated::create_from_userid($user['id'])->trigger();
583 // Preferences.
584 if (!empty($user['preferences'])) {
585 foreach ($user['preferences'] as $preference) {
586 set_user_preference($preference['type'], $preference['value'], $user['id']);
589 if (isset($user['suspended']) and $user['suspended']) {
590 \core\session\manager::kill_user_sessions($user['id']);
594 $transaction->allow_commit();
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, imap, etc', VALUE_OPTIONAL),
1036 'suspended' => new external_value(core_user::get_property_type('suspended'), 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
1037 'confirmed' => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
1038 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
1039 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
1040 'theme' => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
1041 'timezone' => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
1042 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
1043 'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL),
1044 'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL),
1045 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
1046 'url' => new external_value(core_user::get_property_type('url'), 'URL of the user', VALUE_OPTIONAL),
1047 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
1048 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
1049 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
1050 'customfields' => new external_multiple_structure(
1051 new external_single_structure(
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");
1336 $params = self::validate_parameters(self::view_user_list_parameters(),
1337 array(
1338 'courseid' => $courseid
1341 $warnings = array();
1343 if (empty($params['courseid'])) {
1344 $params['courseid'] = SITEID;
1347 $course = get_course($params['courseid']);
1349 if ($course->id == SITEID) {
1350 $context = context_system::instance();
1351 } else {
1352 $context = context_course::instance($course->id);
1354 self::validate_context($context);
1356 if ($course->id == SITEID) {
1357 require_capability('moodle/site:viewparticipants', $context);
1358 } else {
1359 require_capability('moodle/course:viewparticipants', $context);
1362 user_list_view($course, $context);
1364 $result = array();
1365 $result['status'] = true;
1366 $result['warnings'] = $warnings;
1367 return $result;
1371 * Returns description of method result value
1373 * @return external_description
1374 * @since Moodle 2.9
1376 public static function view_user_list_returns() {
1377 return new external_single_structure(
1378 array(
1379 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1380 'warnings' => new external_warnings()
1386 * Returns description of method parameters
1388 * @return external_function_parameters
1389 * @since Moodle 2.9
1391 public static function view_user_profile_parameters() {
1392 return new external_function_parameters(
1393 array(
1394 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1395 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
1401 * Trigger the user profile viewed event.
1403 * @param int $userid id of user
1404 * @param int $courseid id of course
1405 * @return array of warnings and status result
1406 * @since Moodle 2.9
1407 * @throws moodle_exception
1409 public static function view_user_profile($userid, $courseid = 0) {
1410 global $CFG, $USER;
1411 require_once($CFG->dirroot . "/user/profile/lib.php");
1413 $params = self::validate_parameters(self::view_user_profile_parameters(),
1414 array(
1415 'userid' => $userid,
1416 'courseid' => $courseid
1419 $warnings = array();
1421 if (empty($params['userid'])) {
1422 $params['userid'] = $USER->id;
1425 if (empty($params['courseid'])) {
1426 $params['courseid'] = SITEID;
1429 $course = get_course($params['courseid']);
1430 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1431 core_user::require_active_user($user);
1433 if ($course->id == SITEID) {
1434 $coursecontext = context_system::instance();;
1435 } else {
1436 $coursecontext = context_course::instance($course->id);
1438 self::validate_context($coursecontext);
1440 $currentuser = $USER->id == $user->id;
1441 $usercontext = context_user::instance($user->id);
1443 if (!$currentuser and
1444 !has_capability('moodle/user:viewdetails', $coursecontext) and
1445 !has_capability('moodle/user:viewdetails', $usercontext)) {
1446 throw new moodle_exception('cannotviewprofile');
1449 // Case like user/profile.php.
1450 if ($course->id == SITEID) {
1451 profile_view($user, $usercontext);
1452 } else {
1453 // Case like user/view.php.
1454 if (!$currentuser and !can_access_course($course, $user, '', true)) {
1455 throw new moodle_exception('notenrolledprofile');
1458 profile_view($user, $coursecontext, $course);
1461 $result = array();
1462 $result['status'] = true;
1463 $result['warnings'] = $warnings;
1464 return $result;
1468 * Returns description of method result value
1470 * @return external_description
1471 * @since Moodle 2.9
1473 public static function view_user_profile_returns() {
1474 return new external_single_structure(
1475 array(
1476 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1477 'warnings' => new external_warnings()
1483 * Returns description of method parameters
1485 * @return external_function_parameters
1486 * @since Moodle 3.2
1488 public static function get_user_preferences_parameters() {
1489 return new external_function_parameters(
1490 array(
1491 'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''),
1492 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0)
1498 * Return user preferences.
1500 * @param string $name preference name, empty for all
1501 * @param int $userid id of the user, 0 for current user
1502 * @return array of warnings and preferences
1503 * @since Moodle 3.2
1504 * @throws moodle_exception
1506 public static function get_user_preferences($name = '', $userid = 0) {
1507 global $USER;
1509 $params = self::validate_parameters(self::get_user_preferences_parameters(),
1510 array(
1511 'name' => $name,
1512 'userid' => $userid
1514 $preferences = array();
1515 $warnings = array();
1517 $context = context_system::instance();
1518 self::validate_context($context);
1520 if (empty($params['name'])) {
1521 $name = null;
1523 if (empty($params['userid'])) {
1524 $user = null;
1525 } else {
1526 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1527 core_user::require_active_user($user);
1528 if ($user->id != $USER->id) {
1529 // Only admins can retrieve other users preferences.
1530 require_capability('moodle/site:config', $context);
1534 $userpreferences = get_user_preferences($name, null, $user);
1535 // Check if we received just one preference.
1536 if (!is_array($userpreferences)) {
1537 $userpreferences = array($name => $userpreferences);
1540 foreach ($userpreferences as $name => $value) {
1541 $preferences[] = array(
1542 'name' => $name,
1543 'value' => $value,
1547 $result = array();
1548 $result['preferences'] = $preferences;
1549 $result['warnings'] = $warnings;
1550 return $result;
1554 * Returns description of method result value
1556 * @return external_description
1557 * @since Moodle 3.2
1559 public static function get_user_preferences_returns() {
1560 return new external_single_structure(
1561 array(
1562 'preferences' => new external_multiple_structure(
1563 new external_single_structure(
1564 array(
1565 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1566 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1569 'User custom fields (also known as user profile fields)'
1571 'warnings' => new external_warnings()
1577 * Returns description of method parameters
1579 * @return external_function_parameters
1580 * @since Moodle 3.2
1582 public static function update_picture_parameters() {
1583 return new external_function_parameters(
1584 array(
1585 'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'),
1586 'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false),
1587 'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0)
1593 * Update or delete the user picture in the site
1595 * @param int $draftitemid id of the user draft file to use as image
1596 * @param bool $delete if we should delete the user picture
1597 * @param int $userid id of the user, 0 for current user
1598 * @return array warnings and success status
1599 * @since Moodle 3.2
1600 * @throws moodle_exception
1602 public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1603 global $CFG, $USER, $PAGE;
1605 $params = self::validate_parameters(
1606 self::update_picture_parameters(),
1607 array(
1608 'draftitemid' => $draftitemid,
1609 'delete' => $delete,
1610 'userid' => $userid
1614 $context = context_system::instance();
1615 self::validate_context($context);
1617 if (!empty($CFG->disableuserimages)) {
1618 throw new moodle_exception('userimagesdisabled', 'admin');
1621 if (empty($params['userid']) or $params['userid'] == $USER->id) {
1622 $user = $USER;
1623 require_capability('moodle/user:editownprofile', $context);
1624 } else {
1625 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1626 core_user::require_active_user($user);
1627 $personalcontext = context_user::instance($user->id);
1629 require_capability('moodle/user:editprofile', $personalcontext);
1630 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
1631 throw new moodle_exception('useradmineditadmin');
1635 // Load the appropriate auth plugin.
1636 $userauth = get_auth_plugin($user->auth);
1637 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1638 throw new moodle_exception('noprofileedit', 'auth');
1641 $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image');
1642 $user->deletepicture = $params['delete'];
1643 $user->imagefile = $params['draftitemid'];
1644 $success = core_user::update_picture($user, $filemanageroptions);
1646 $result = array(
1647 'success' => $success,
1648 'warnings' => array(),
1650 if ($success) {
1651 $userpicture = new user_picture(core_user::get_user($user->id));
1652 $userpicture->size = 1; // Size f1.
1653 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1655 return $result;
1659 * Returns description of method result value
1661 * @return external_description
1662 * @since Moodle 3.2
1664 public static function update_picture_returns() {
1665 return new external_single_structure(
1666 array(
1667 'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'),
1668 'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL),
1669 'warnings' => new external_warnings()
1675 * Returns description of method parameters
1677 * @return external_function_parameters
1678 * @since Moodle 3.2
1680 public static function set_user_preferences_parameters() {
1681 return new external_function_parameters(
1682 array(
1683 'preferences' => new external_multiple_structure(
1684 new external_single_structure(
1685 array(
1686 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1687 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1688 'userid' => new external_value(PARAM_INT, 'Id of the user to set the preference'),
1697 * Set user preferences.
1699 * @param array $preferences list of preferences including name, value and userid
1700 * @return array of warnings and preferences saved
1701 * @since Moodle 3.2
1702 * @throws moodle_exception
1704 public static function set_user_preferences($preferences) {
1705 global $USER;
1707 $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
1708 $warnings = array();
1709 $saved = array();
1711 $context = context_system::instance();
1712 self::validate_context($context);
1713 require_capability('moodle/site:config', $context);
1715 $userscache = array();
1716 foreach ($params['preferences'] as $pref) {
1717 // Check to which user set the preference.
1718 if (!empty($userscache[$pref['userid']])) {
1719 $user = $userscache[$pref['userid']];
1720 } else {
1721 try {
1722 $user = core_user::get_user($pref['userid'], '*', MUST_EXIST);
1723 core_user::require_active_user($user);
1724 $userscache[$pref['userid']] = $user;
1725 } catch (Exception $e) {
1726 $warnings[] = array(
1727 'item' => 'user',
1728 'itemid' => $pref['userid'],
1729 'warningcode' => 'invaliduser',
1730 'message' => $e->getMessage()
1732 continue;
1736 try {
1737 set_user_preference($pref['name'], $pref['value'], $user);
1738 $saved[] = array(
1739 'name' => $pref['name'],
1740 'userid' => $user->id,
1742 } catch (Exception $e) {
1743 $warnings[] = array(
1744 'item' => 'user',
1745 'itemid' => $user->id,
1746 'warningcode' => 'errorsavingpreference',
1747 'message' => $e->getMessage()
1752 $result = array();
1753 $result['saved'] = $saved;
1754 $result['warnings'] = $warnings;
1755 return $result;
1759 * Returns description of method result value
1761 * @return external_description
1762 * @since Moodle 3.2
1764 public static function set_user_preferences_returns() {
1765 return new external_single_structure(
1766 array(
1767 'saved' => new external_multiple_structure(
1768 new external_single_structure(
1769 array(
1770 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1771 'userid' => new external_value(PARAM_INT, 'The user the preference was set for'),
1773 ), 'Preferences saved'
1775 'warnings' => new external_warnings()
1781 * Returns description of method parameters.
1783 * @return external_function_parameters
1784 * @since Moodle 3.2
1786 public static function agree_site_policy_parameters() {
1787 return new external_function_parameters(array());
1791 * Agree the site policy for the current user.
1793 * @return array of warnings and status result
1794 * @since Moodle 3.2
1795 * @throws moodle_exception
1797 public static function agree_site_policy() {
1798 global $CFG, $DB, $USER;
1800 $warnings = array();
1802 $context = context_system::instance();
1803 try {
1804 // We expect an exception here since the user didn't agree the site policy yet.
1805 self::validate_context($context);
1806 } catch (Exception $e) {
1807 // We are expecting only a sitepolicynotagreed exception.
1808 if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
1809 // In case we receive a different exception, throw it.
1810 throw $e;
1814 if (empty($CFG->sitepolicy)) {
1815 $status = false;
1816 $warnings[] = array(
1817 'item' => 'user',
1818 'itemid' => $USER->id,
1819 'warningcode' => 'nositepolicy',
1820 'message' => 'The site does not have a site policy configured.'
1822 } else if (!empty($USER->policyagreed)) {
1823 $status = false;
1824 $warnings[] = array(
1825 'item' => 'user',
1826 'itemid' => $USER->id,
1827 'warningcode' => 'alreadyagreed',
1828 'message' => 'The user already agreed the site policy.'
1830 } else {
1831 $DB->set_field('user', 'policyagreed', 1, array('id' => $USER->id));
1832 $USER->policyagreed = 1;
1833 $status = true;
1836 $result = array();
1837 $result['status'] = $status;
1838 $result['warnings'] = $warnings;
1839 return $result;
1843 * Returns description of method result value.
1845 * @return external_description
1846 * @since Moodle 3.2
1848 public static function agree_site_policy_returns() {
1849 return new external_single_structure(
1850 array(
1851 'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'),
1852 'warnings' => new external_warnings()