MDL-61581 lesson: style continue to last buttons
[moodle.git] / user / externallib.php
blob83da6dcd000a8795b2d8b5addba526b34abfbd1c
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * External user API
20 * @package core_user
21 * @category external
22 * @copyright 2009 Petr Skodak
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 require_once("$CFG->libdir/externallib.php");
30 /**
31 * User external functions
33 * @package core_user
34 * @category external
35 * @copyright 2011 Jerome Mouneyrac
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 * @since Moodle 2.2
39 class core_user_external extends external_api {
41 /**
42 * Returns description of method parameters
44 * @return external_function_parameters
45 * @since Moodle 2.2
47 public static function create_users_parameters() {
48 global $CFG;
50 return new external_function_parameters(
51 array(
52 'users' => new external_multiple_structure(
53 new external_single_structure(
54 array(
55 'username' =>
56 new external_value(core_user::get_property_type('username'), 'Username policy is defined in Moodle security config.'),
57 'password' =>
58 new external_value(core_user::get_property_type('password'), 'Plain text password consisting of any characters', VALUE_OPTIONAL),
59 'createpassword' =>
60 new external_value(PARAM_BOOL, 'True if password should be created and mailed to user.',
61 VALUE_OPTIONAL),
62 'firstname' =>
63 new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user'),
64 'lastname' =>
65 new external_value(core_user::get_property_type('lastname'), 'The family name of the user'),
66 'email' =>
67 new external_value(core_user::get_property_type('email'), 'A valid and unique email address'),
68 'auth' =>
69 new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_DEFAULT,
70 'manual', core_user::get_property_null('auth')),
71 'idnumber' =>
72 new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution',
73 VALUE_DEFAULT, ''),
74 'lang' =>
75 new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_DEFAULT,
76 core_user::get_property_default('lang'), core_user::get_property_null('lang')),
77 'calendartype' =>
78 new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server',
79 VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
80 'theme' =>
81 new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server',
82 VALUE_OPTIONAL),
83 'timezone' =>
84 new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default',
85 VALUE_OPTIONAL),
86 'mailformat' =>
87 new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc',
88 VALUE_OPTIONAL),
89 'description' =>
90 new external_value(core_user::get_property_type('description'), 'User profile description, no HTML', VALUE_OPTIONAL),
91 'city' =>
92 new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
93 'country' =>
94 new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
95 'firstnamephonetic' =>
96 new external_value(core_user::get_property_type('firstnamephonetic'), 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
97 'lastnamephonetic' =>
98 new external_value(core_user::get_property_type('lastnamephonetic'), 'The family name phonetically of the user', VALUE_OPTIONAL),
99 'middlename' =>
100 new external_value(core_user::get_property_type('middlename'), 'The middle name of the user', VALUE_OPTIONAL),
101 'alternatename' =>
102 new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user', VALUE_OPTIONAL),
103 'preferences' => new external_multiple_structure(
104 new external_single_structure(
105 array(
106 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
107 'value' => new external_value(PARAM_RAW, 'The value of the preference')
109 ), 'User preferences', VALUE_OPTIONAL),
110 'customfields' => new external_multiple_structure(
111 new external_single_structure(
112 array(
113 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
114 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
116 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
125 * Create one or more users.
127 * @throws invalid_parameter_exception
128 * @param array $users An array of users to create.
129 * @return array An array of arrays
130 * @since Moodle 2.2
132 public static function create_users($users) {
133 global $CFG, $DB;
134 require_once($CFG->dirroot."/lib/weblib.php");
135 require_once($CFG->dirroot."/user/lib.php");
136 require_once($CFG->dirroot."/user/editlib.php");
137 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
139 // Ensure the current user is allowed to run this function.
140 $context = context_system::instance();
141 self::validate_context($context);
142 require_capability('moodle/user:create', $context);
144 // Do basic automatic PARAM checks on incoming data, using params description.
145 // If any problems are found then exceptions are thrown with helpful error messages.
146 $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
148 $availableauths = core_component::get_plugin_list('auth');
149 unset($availableauths['mnet']); // These would need mnethostid too.
150 unset($availableauths['webservice']); // We do not want new webservice users for now.
152 $availablethemes = core_component::get_plugin_list('theme');
153 $availablelangs = get_string_manager()->get_list_of_translations();
155 $transaction = $DB->start_delegated_transaction();
157 $userids = array();
158 $createpassword = false;
159 foreach ($params['users'] as $user) {
160 // Make sure that the username doesn't already exist.
161 if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
162 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
165 // Make sure auth is valid.
166 if (empty($availableauths[$user['auth']])) {
167 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
170 // Make sure lang is valid.
171 if (empty($availablelangs[$user['lang']])) {
172 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
175 // Make sure lang is valid.
176 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
177 // so no default value
178 // We need to test if the client sent it
179 // => !empty($user['theme']).
180 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
183 // Make sure we have a password or have to create one.
184 if (empty($user['password']) && empty($user['createpassword'])) {
185 throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
188 $user['confirmed'] = true;
189 $user['mnethostid'] = $CFG->mnet_localhost_id;
191 // Start of user info validation.
192 // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
193 if (!validate_email($user['email'])) {
194 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
195 } else if (empty($CFG->allowaccountssameemail) &&
196 $DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
197 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
199 // End of user info validation.
201 $createpassword = !empty($user['createpassword']);
202 unset($user['createpassword']);
203 if ($createpassword) {
204 $user['password'] = '';
205 $updatepassword = false;
206 } else {
207 $updatepassword = true;
210 // Create the user data now!
211 $user['id'] = user_create_user($user, $updatepassword, false);
213 // Custom fields.
214 if (!empty($user['customfields'])) {
215 foreach ($user['customfields'] as $customfield) {
216 // Profile_save_data() saves profile file it's expecting a user with the correct id,
217 // and custom field to be named profile_field_"shortname".
218 $user["profile_field_".$customfield['type']] = $customfield['value'];
220 profile_save_data((object) $user);
223 if ($createpassword) {
224 $userobject = (object)$user;
225 setnew_password_and_mail($userobject);
226 unset_user_preference('create_password', $userobject);
227 set_user_preference('auth_forcepasswordchange', 1, $userobject);
230 // Trigger event.
231 \core\event\user_created::create_from_userid($user['id'])->trigger();
233 // Preferences.
234 if (!empty($user['preferences'])) {
235 $userpref = (object)$user;
236 foreach ($user['preferences'] as $preference) {
237 $userpref->{'preference_'.$preference['type']} = $preference['value'];
239 useredit_update_user_preference($userpref);
242 $userids[] = array('id' => $user['id'], 'username' => $user['username']);
245 $transaction->allow_commit();
247 return $userids;
251 * Returns description of method result value
253 * @return external_description
254 * @since Moodle 2.2
256 public static function create_users_returns() {
257 return new external_multiple_structure(
258 new external_single_structure(
259 array(
260 'id' => new external_value(core_user::get_property_type('id'), 'user id'),
261 'username' => new external_value(core_user::get_property_type('username'), 'user name'),
269 * Returns description of method parameters
271 * @return external_function_parameters
272 * @since Moodle 2.2
274 public static function delete_users_parameters() {
275 return new external_function_parameters(
276 array(
277 'userids' => new external_multiple_structure(new external_value(core_user::get_property_type('id'), 'user ID')),
283 * Delete users
285 * @throws moodle_exception
286 * @param array $userids
287 * @return null
288 * @since Moodle 2.2
290 public static function delete_users($userids) {
291 global $CFG, $DB, $USER;
292 require_once($CFG->dirroot."/user/lib.php");
294 // Ensure the current user is allowed to run this function.
295 $context = context_system::instance();
296 require_capability('moodle/user:delete', $context);
297 self::validate_context($context);
299 $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
301 $transaction = $DB->start_delegated_transaction();
303 foreach ($params['userids'] as $userid) {
304 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
305 // Must not allow deleting of admins or self!!!
306 if (is_siteadmin($user)) {
307 throw new moodle_exception('useradminodelete', 'error');
309 if ($USER->id == $user->id) {
310 throw new moodle_exception('usernotdeletederror', 'error');
312 user_delete_user($user);
315 $transaction->allow_commit();
317 return null;
321 * Returns description of method result value
323 * @return null
324 * @since Moodle 2.2
326 public static function delete_users_returns() {
327 return null;
331 * Returns description of method parameters.
333 * @return external_function_parameters
334 * @since Moodle 3.2
336 public static function update_user_preferences_parameters() {
337 return new external_function_parameters(
338 array(
339 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
340 'emailstop' => new external_value(core_user::get_property_type('emailstop'),
341 'Enable or disable notifications for this user', VALUE_DEFAULT, null),
342 'preferences' => new external_multiple_structure(
343 new external_single_structure(
344 array(
345 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
346 'value' => new external_value(PARAM_RAW, 'The value of the preference')
348 ), 'User preferences', VALUE_DEFAULT, array()
355 * Update the user's preferences.
357 * @param int $userid
358 * @param bool|null $emailstop
359 * @param array $preferences
360 * @return null
361 * @since Moodle 3.2
363 public static function update_user_preferences($userid, $emailstop = null, $preferences = array()) {
364 global $USER, $CFG;
366 require_once($CFG->dirroot . '/user/lib.php');
367 require_once($CFG->dirroot . '/user/editlib.php');
368 require_once($CFG->dirroot . '/message/lib.php');
370 if (empty($userid)) {
371 $userid = $USER->id;
374 $systemcontext = context_system::instance();
375 self::validate_context($systemcontext);
376 $params = array(
377 'userid' => $userid,
378 'emailstop' => $emailstop,
379 'preferences' => $preferences
381 self::validate_parameters(self::update_user_preferences_parameters(), $params);
383 // Preferences.
384 if (!empty($preferences)) {
385 $userpref = ['id' => $userid];
386 foreach ($preferences as $preference) {
387 $userpref['preference_' . $preference['type']] = $preference['value'];
389 useredit_update_user_preference($userpref);
392 // Check if they want to update the email.
393 if ($emailstop !== null) {
394 $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST);
395 core_user::require_active_user($otheruser);
396 if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) {
397 $user = new stdClass();
398 $user->id = $userid;
399 $user->emailstop = $emailstop;
400 user_update_user($user);
402 // Update the $USER if we should.
403 if ($userid == $USER->id) {
404 $USER->emailstop = $emailstop;
409 return null;
413 * Returns description of method result value
415 * @return null
416 * @since Moodle 3.2
418 public static function update_user_preferences_returns() {
419 return null;
423 * Returns description of method parameters
425 * @return external_function_parameters
426 * @since Moodle 2.2
428 public static function update_users_parameters() {
429 return new external_function_parameters(
430 array(
431 'users' => new external_multiple_structure(
432 new external_single_structure(
433 array(
434 'id' =>
435 new external_value(core_user::get_property_type('id'), 'ID of the user'),
436 'username' =>
437 new external_value(core_user::get_property_type('username'), 'Username policy is defined in Moodle security config.',
438 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
439 'password' =>
440 new external_value(core_user::get_property_type('password'), 'Plain text password consisting of any characters', VALUE_OPTIONAL,
441 '', NULL_NOT_ALLOWED),
442 'firstname' =>
443 new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL, '',
444 NULL_NOT_ALLOWED),
445 'lastname' =>
446 new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
447 'email' =>
448 new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL, '',
449 NULL_NOT_ALLOWED),
450 'auth' =>
451 new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL, '',
452 NULL_NOT_ALLOWED),
453 'suspended' =>
454 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),
455 'idnumber' =>
456 new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution',
457 VALUE_OPTIONAL),
458 'lang' =>
459 new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
460 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
461 'calendartype' =>
462 new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server',
463 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
464 'theme' =>
465 new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server',
466 VALUE_OPTIONAL),
467 'timezone' =>
468 new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default',
469 VALUE_OPTIONAL),
470 'mailformat' =>
471 new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc',
472 VALUE_OPTIONAL),
473 'description' =>
474 new external_value(core_user::get_property_type('description'), 'User profile description, no HTML', VALUE_OPTIONAL),
475 'city' =>
476 new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
477 'country' =>
478 new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
479 'firstnamephonetic' =>
480 new external_value(core_user::get_property_type('firstnamephonetic'), 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
481 'lastnamephonetic' =>
482 new external_value(core_user::get_property_type('lastnamephonetic'), 'The family name phonetically of the user', VALUE_OPTIONAL),
483 'middlename' =>
484 new external_value(core_user::get_property_type('middlename'), 'The middle name of the user', VALUE_OPTIONAL),
485 'alternatename' =>
486 new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user', VALUE_OPTIONAL),
487 'userpicture' =>
488 new external_value(PARAM_INT, 'The itemid where the new user picture '.
489 'has been uploaded to, 0 to delete', VALUE_OPTIONAL),
490 'customfields' => new external_multiple_structure(
491 new external_single_structure(
492 array(
493 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
494 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
496 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
497 'preferences' => new external_multiple_structure(
498 new external_single_structure(
499 array(
500 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
501 'value' => new external_value(PARAM_RAW, 'The value of the preference')
503 ), 'User preferences', VALUE_OPTIONAL),
512 * Update users
514 * @param array $users
515 * @return null
516 * @since Moodle 2.2
518 public static function update_users($users) {
519 global $CFG, $DB, $USER;
520 require_once($CFG->dirroot."/user/lib.php");
521 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
522 require_once($CFG->dirroot.'/user/editlib.php');
524 // Ensure the current user is allowed to run this function.
525 $context = context_system::instance();
526 require_capability('moodle/user:update', $context);
527 self::validate_context($context);
529 $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
531 $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
532 'subdirs' => 0,
533 'maxfiles' => 1,
534 'accepted_types' => 'web_image');
536 $transaction = $DB->start_delegated_transaction();
538 foreach ($params['users'] as $user) {
539 // First check the user exists.
540 if (!$existinguser = core_user::get_user($user['id'])) {
541 continue;
543 // Check if we are trying to update an admin.
544 if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
545 continue;
547 // Other checks (deleted, remote or guest users).
548 if ($existinguser->deleted or is_mnet_remote_user($existinguser) or isguestuser($existinguser->id)) {
549 continue;
551 // Check duplicated emails.
552 if (isset($user['email']) && $user['email'] !== $existinguser->email) {
553 if (!validate_email($user['email'])) {
554 continue;
555 } else if (empty($CFG->allowaccountssameemail) &&
556 $DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $CFG->mnet_localhost_id))) {
557 continue;
561 user_update_user($user, true, false);
563 // Update user picture if it was specified for this user.
564 if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
565 $userobject = (object)$user;
567 $userobject->deletepicture = null;
569 if ($user['userpicture'] == 0) {
570 $userobject->deletepicture = true;
571 } else {
572 $userobject->imagefile = $user['userpicture'];
575 core_user::update_picture($userobject, $filemanageroptions);
578 // Update user custom fields.
579 if (!empty($user['customfields'])) {
581 foreach ($user['customfields'] as $customfield) {
582 // Profile_save_data() saves profile file it's expecting a user with the correct id,
583 // and custom field to be named profile_field_"shortname".
584 $user["profile_field_".$customfield['type']] = $customfield['value'];
586 profile_save_data((object) $user);
589 // Trigger event.
590 \core\event\user_updated::create_from_userid($user['id'])->trigger();
592 // Preferences.
593 if (!empty($user['preferences'])) {
594 $userpref = clone($existinguser);
595 foreach ($user['preferences'] as $preference) {
596 $userpref->{'preference_'.$preference['type']} = $preference['value'];
598 useredit_update_user_preference($userpref);
600 if (isset($user['suspended']) and $user['suspended']) {
601 \core\session\manager::kill_user_sessions($user['id']);
605 $transaction->allow_commit();
607 return null;
611 * Returns description of method result value
613 * @return null
614 * @since Moodle 2.2
616 public static function update_users_returns() {
617 return null;
621 * Returns description of method parameters
623 * @return external_function_parameters
624 * @since Moodle 2.4
626 public static function get_users_by_field_parameters() {
627 return new external_function_parameters(
628 array(
629 'field' => new external_value(PARAM_ALPHA, 'the search field can be
630 \'id\' or \'idnumber\' or \'username\' or \'email\''),
631 'values' => new external_multiple_structure(
632 new external_value(PARAM_RAW, 'the value to match'))
638 * Get user information for a unique field.
640 * @throws coding_exception
641 * @throws invalid_parameter_exception
642 * @param string $field
643 * @param array $values
644 * @return array An array of arrays containg user profiles.
645 * @since Moodle 2.4
647 public static function get_users_by_field($field, $values) {
648 global $CFG, $USER, $DB;
649 require_once($CFG->dirroot . "/user/lib.php");
651 $params = self::validate_parameters(self::get_users_by_field_parameters(),
652 array('field' => $field, 'values' => $values));
654 // This array will keep all the users that are allowed to be searched,
655 // according to the current user's privileges.
656 $cleanedvalues = array();
658 switch ($field) {
659 case 'id':
660 $paramtype = core_user::get_property_type('id');
661 break;
662 case 'idnumber':
663 $paramtype = core_user::get_property_type('idnumber');
664 break;
665 case 'username':
666 $paramtype = core_user::get_property_type('username');
667 break;
668 case 'email':
669 $paramtype = core_user::get_property_type('email');
670 break;
671 default:
672 throw new coding_exception('invalid field parameter',
673 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
676 // Clean the values.
677 foreach ($values as $value) {
678 $cleanedvalue = clean_param($value, $paramtype);
679 if ( $value != $cleanedvalue) {
680 throw new invalid_parameter_exception('The field \'' . $field .
681 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
683 $cleanedvalues[] = $cleanedvalue;
686 // Retrieve the users.
687 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
689 $context = context_system::instance();
690 self::validate_context($context);
692 // Finally retrieve each users information.
693 $returnedusers = array();
694 foreach ($users as $user) {
695 $userdetails = user_get_user_details_courses($user);
697 // Return the user only if the searched field is returned.
698 // Otherwise it means that the $USER was not allowed to search the returned user.
699 if (!empty($userdetails) and !empty($userdetails[$field])) {
700 $returnedusers[] = $userdetails;
704 return $returnedusers;
708 * Returns description of method result value
710 * @return external_multiple_structure
711 * @since Moodle 2.4
713 public static function get_users_by_field_returns() {
714 return new external_multiple_structure(self::user_description());
719 * Returns description of get_users() parameters.
721 * @return external_function_parameters
722 * @since Moodle 2.5
724 public static function get_users_parameters() {
725 return new external_function_parameters(
726 array(
727 'criteria' => new external_multiple_structure(
728 new external_single_structure(
729 array(
730 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
731 "id" (int) matching user id,
732 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
733 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
734 "idnumber" (string) matching user idnumber,
735 "username" (string) matching user username,
736 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
737 "auth" (string) matching user auth plugin'),
738 'value' => new external_value(PARAM_RAW, 'the value to search')
740 ), 'the key/value pairs to be considered in user search. Values can not be empty.
741 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
742 key occurences are forbidden.
743 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
744 the search is still executed on the valid criterias.
745 You can search without criteria, but the function is not designed for it.
746 It could very slow or timeout. The function is designed to search some specific users.'
753 * Retrieve matching user.
755 * @throws moodle_exception
756 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
757 * @return array An array of arrays containing user profiles.
758 * @since Moodle 2.5
760 public static function get_users($criteria = array()) {
761 global $CFG, $USER, $DB;
763 require_once($CFG->dirroot . "/user/lib.php");
765 $params = self::validate_parameters(self::get_users_parameters(),
766 array('criteria' => $criteria));
768 // Validate the criteria and retrieve the users.
769 $users = array();
770 $warnings = array();
771 $sqlparams = array();
772 $usedkeys = array();
774 // Do not retrieve deleted users.
775 $sql = ' deleted = 0';
777 foreach ($params['criteria'] as $criteriaindex => $criteria) {
779 // Check that the criteria has never been used.
780 if (array_key_exists($criteria['key'], $usedkeys)) {
781 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
782 } else {
783 $usedkeys[$criteria['key']] = true;
786 $invalidcriteria = false;
787 // Clean the parameters.
788 $paramtype = PARAM_RAW;
789 switch ($criteria['key']) {
790 case 'id':
791 $paramtype = core_user::get_property_type('id');
792 break;
793 case 'idnumber':
794 $paramtype = core_user::get_property_type('idnumber');
795 break;
796 case 'username':
797 $paramtype = core_user::get_property_type('username');
798 break;
799 case 'email':
800 // We use PARAM_RAW to allow searches with %.
801 $paramtype = core_user::get_property_type('email');
802 break;
803 case 'auth':
804 $paramtype = core_user::get_property_type('auth');
805 break;
806 case 'lastname':
807 case 'firstname':
808 $paramtype = core_user::get_property_type('firstname');
809 break;
810 default:
811 // Send back a warning that this search key is not supported in this version.
812 // This warning will make the function extandable without breaking clients.
813 $warnings[] = array(
814 'item' => $criteria['key'],
815 'warningcode' => 'invalidfieldparameter',
816 'message' =>
817 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
819 // Do not add this invalid criteria to the created SQL request.
820 $invalidcriteria = true;
821 unset($params['criteria'][$criteriaindex]);
822 break;
825 if (!$invalidcriteria) {
826 $cleanedvalue = clean_param($criteria['value'], $paramtype);
828 $sql .= ' AND ';
830 // Create the SQL.
831 switch ($criteria['key']) {
832 case 'id':
833 case 'idnumber':
834 case 'username':
835 case 'auth':
836 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
837 $sqlparams[$criteria['key']] = $cleanedvalue;
838 break;
839 case 'email':
840 case 'lastname':
841 case 'firstname':
842 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
843 $sqlparams[$criteria['key']] = $cleanedvalue;
844 break;
845 default:
846 break;
851 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
853 // Finally retrieve each users information.
854 $returnedusers = array();
855 foreach ($users as $user) {
856 $userdetails = user_get_user_details_courses($user);
858 // Return the user only if all the searched fields are returned.
859 // Otherwise it means that the $USER was not allowed to search the returned user.
860 if (!empty($userdetails)) {
861 $validuser = true;
863 foreach ($params['criteria'] as $criteria) {
864 if (empty($userdetails[$criteria['key']])) {
865 $validuser = false;
869 if ($validuser) {
870 $returnedusers[] = $userdetails;
875 return array('users' => $returnedusers, 'warnings' => $warnings);
879 * Returns description of get_users result value.
881 * @return external_description
882 * @since Moodle 2.5
884 public static function get_users_returns() {
885 return new external_single_structure(
886 array('users' => new external_multiple_structure(
887 self::user_description()
889 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
895 * Returns description of method parameters
897 * @return external_function_parameters
898 * @since Moodle 2.2
900 public static function get_course_user_profiles_parameters() {
901 return new external_function_parameters(
902 array(
903 'userlist' => new external_multiple_structure(
904 new external_single_structure(
905 array(
906 'userid' => new external_value(core_user::get_property_type('id'), 'userid'),
907 'courseid' => new external_value(PARAM_INT, 'courseid'),
916 * Get course participant's details
918 * @param array $userlist array of user ids and according course ids
919 * @return array An array of arrays describing course participants
920 * @since Moodle 2.2
922 public static function get_course_user_profiles($userlist) {
923 global $CFG, $USER, $DB;
924 require_once($CFG->dirroot . "/user/lib.php");
925 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
927 $userids = array();
928 $courseids = array();
929 foreach ($params['userlist'] as $value) {
930 $userids[] = $value['userid'];
931 $courseids[$value['userid']] = $value['courseid'];
934 // Cache all courses.
935 $courses = array();
936 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
937 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
938 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
939 $params['contextlevel'] = CONTEXT_COURSE;
940 $coursesql = "SELECT c.* $cselect
941 FROM {course} c $cjoin
942 WHERE c.id $sqlcourseids";
943 $rs = $DB->get_recordset_sql($coursesql, $params);
944 foreach ($rs as $course) {
945 // Adding course contexts to cache.
946 context_helper::preload_from_record($course);
947 // Cache courses.
948 $courses[$course->id] = $course;
950 $rs->close();
952 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
953 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
954 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
955 $params['contextlevel'] = CONTEXT_USER;
956 $usersql = "SELECT u.* $uselect
957 FROM {user} u $ujoin
958 WHERE u.id $sqluserids";
959 $users = $DB->get_recordset_sql($usersql, $params);
960 $result = array();
961 foreach ($users as $user) {
962 if (!empty($user->deleted)) {
963 continue;
965 context_helper::preload_from_record($user);
966 $course = $courses[$courseids[$user->id]];
967 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
968 self::validate_context($context);
969 if ($userarray = user_get_user_details($user, $course)) {
970 $result[] = $userarray;
974 $users->close();
976 return $result;
980 * Returns description of method result value
982 * @return external_description
983 * @since Moodle 2.2
985 public static function get_course_user_profiles_returns() {
986 $additionalfields = array(
987 'groups' => new external_multiple_structure(
988 new external_single_structure(
989 array(
990 'id' => new external_value(PARAM_INT, 'group id'),
991 'name' => new external_value(PARAM_RAW, 'group name'),
992 'description' => new external_value(PARAM_RAW, 'group description'),
993 'descriptionformat' => new external_format_value('description'),
995 ), 'user groups', VALUE_OPTIONAL),
996 'roles' => new external_multiple_structure(
997 new external_single_structure(
998 array(
999 'roleid' => new external_value(PARAM_INT, 'role id'),
1000 'name' => new external_value(PARAM_RAW, 'role name'),
1001 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
1002 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
1004 ), 'user roles', VALUE_OPTIONAL),
1005 'enrolledcourses' => new external_multiple_structure(
1006 new external_single_structure(
1007 array(
1008 'id' => new external_value(PARAM_INT, 'Id of the course'),
1009 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
1010 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
1012 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
1015 return new external_multiple_structure(self::user_description($additionalfields));
1019 * Create user return value description.
1021 * @param array $additionalfields some additional field
1022 * @return single_structure_description
1024 public static function user_description($additionalfields = array()) {
1025 $userfields = array(
1026 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
1027 'username' => new external_value(core_user::get_property_type('username'), 'The username', VALUE_OPTIONAL),
1028 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL),
1029 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
1030 'fullname' => new external_value(core_user::get_property_type('firstname'), 'The fullname of the user'),
1031 'email' => new external_value(core_user::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
1032 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
1033 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
1034 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
1035 'icq' => new external_value(core_user::get_property_type('icq'), 'icq number', VALUE_OPTIONAL),
1036 'skype' => new external_value(core_user::get_property_type('skype'), 'skype id', VALUE_OPTIONAL),
1037 'yahoo' => new external_value(core_user::get_property_type('yahoo'), 'yahoo id', VALUE_OPTIONAL),
1038 'aim' => new external_value(core_user::get_property_type('aim'), 'aim id', VALUE_OPTIONAL),
1039 'msn' => new external_value(core_user::get_property_type('msn'), 'msn number', VALUE_OPTIONAL),
1040 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
1041 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
1042 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
1043 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
1044 'firstaccess' => new external_value(core_user::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL),
1045 'lastaccess' => new external_value(core_user::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL),
1046 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL),
1047 '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),
1048 'confirmed' => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
1049 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
1050 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
1051 'theme' => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
1052 'timezone' => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
1053 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
1054 'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL),
1055 'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL),
1056 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
1057 'url' => new external_value(core_user::get_property_type('url'), 'URL of the user', VALUE_OPTIONAL),
1058 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
1059 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
1060 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
1061 'customfields' => new external_multiple_structure(
1062 new external_single_structure(
1063 array(
1064 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
1065 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
1066 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
1067 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
1069 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
1070 'preferences' => new external_multiple_structure(
1071 new external_single_structure(
1072 array(
1073 'name' => new external_value(PARAM_RAW, 'The name of the preferences'),
1074 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1076 ), 'Users preferences', VALUE_OPTIONAL)
1078 if (!empty($additionalfields)) {
1079 $userfields = array_merge($userfields, $additionalfields);
1081 return new external_single_structure($userfields);
1085 * Returns description of method parameters
1087 * @return external_function_parameters
1088 * @since Moodle 2.6
1090 public static function add_user_private_files_parameters() {
1091 return new external_function_parameters(
1092 array(
1093 'draftid' => new external_value(PARAM_INT, 'draft area id')
1099 * Copy files from a draft area to users private files area.
1101 * @throws invalid_parameter_exception
1102 * @param int $draftid Id of a draft area containing files.
1103 * @return array An array of warnings
1104 * @since Moodle 2.6
1106 public static function add_user_private_files($draftid) {
1107 global $CFG, $USER;
1108 require_once($CFG->libdir . "/filelib.php");
1110 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
1112 if (isguestuser()) {
1113 throw new invalid_parameter_exception('Guest users cannot upload files');
1116 $context = context_user::instance($USER->id);
1117 require_capability('moodle/user:manageownfiles', $context);
1119 $maxbytes = $CFG->userquota;
1120 $maxareabytes = $CFG->userquota;
1121 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1122 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1123 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1126 $options = array('subdirs' => 1,
1127 'maxbytes' => $maxbytes,
1128 'maxfiles' => -1,
1129 'areamaxbytes' => $maxareabytes);
1131 file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options);
1133 return null;
1137 * Returns description of method result value
1139 * @return external_description
1140 * @since Moodle 2.2
1142 public static function add_user_private_files_returns() {
1143 return null;
1147 * Returns description of method parameters.
1149 * @return external_function_parameters
1150 * @since Moodle 2.6
1152 public static function add_user_device_parameters() {
1153 return new external_function_parameters(
1154 array(
1155 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1156 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1157 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1158 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1159 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1160 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1161 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1167 * Add a user device in Moodle database (for PUSH notifications usually).
1169 * @throws moodle_exception
1170 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1171 * @param string $name The device name, occam or iPhone etc.
1172 * @param string $model The device model Nexus4 or iPad1.1 etc.
1173 * @param string $platform The device platform iOs or Android etc.
1174 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1175 * @param string $pushid The device PUSH token/key/identifier/registration id.
1176 * @param string $uuid The device UUID.
1177 * @return array List of possible warnings.
1178 * @since Moodle 2.6
1180 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1181 global $CFG, $USER, $DB;
1182 require_once($CFG->dirroot . "/user/lib.php");
1184 $params = self::validate_parameters(self::add_user_device_parameters(),
1185 array('appid' => $appid,
1186 'name' => $name,
1187 'model' => $model,
1188 'platform' => $platform,
1189 'version' => $version,
1190 'pushid' => $pushid,
1191 'uuid' => $uuid
1194 $warnings = array();
1196 // Prevent duplicate keys for users.
1197 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1198 $warnings['warning'][] = array(
1199 'item' => $params['pushid'],
1200 'warningcode' => 'existingkeyforthisuser',
1201 'message' => 'This key is already stored for this user'
1203 return $warnings;
1206 // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1207 // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1208 if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1209 'appid' => $params['appid'], 'userid' => $USER->id))) {
1211 foreach ($userdevices as $userdevice) {
1212 $userdevice->version = $params['version']; // Maybe the user upgraded the device.
1213 $userdevice->pushid = $params['pushid'];
1214 $userdevice->timemodified = time();
1215 $DB->update_record('user_devices', $userdevice);
1218 } else {
1219 $userdevice = new stdclass;
1220 $userdevice->userid = $USER->id;
1221 $userdevice->appid = $params['appid'];
1222 $userdevice->name = $params['name'];
1223 $userdevice->model = $params['model'];
1224 $userdevice->platform = $params['platform'];
1225 $userdevice->version = $params['version'];
1226 $userdevice->pushid = $params['pushid'];
1227 $userdevice->uuid = $params['uuid'];
1228 $userdevice->timecreated = time();
1229 $userdevice->timemodified = $userdevice->timecreated;
1231 if (!$DB->insert_record('user_devices', $userdevice)) {
1232 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1236 return $warnings;
1240 * Returns description of method result value.
1242 * @return external_multiple_structure
1243 * @since Moodle 2.6
1245 public static function add_user_device_returns() {
1246 return new external_multiple_structure(
1247 new external_warnings()
1252 * Returns description of method parameters.
1254 * @return external_function_parameters
1255 * @since Moodle 2.9
1257 public static function remove_user_device_parameters() {
1258 return new external_function_parameters(
1259 array(
1260 'uuid' => new external_value(PARAM_RAW, 'the device UUID'),
1261 'appid' => new external_value(PARAM_NOTAGS,
1262 'the app id, if empty devices matching the UUID for the user will be removed',
1263 VALUE_DEFAULT, ''),
1269 * Remove a user device from the Moodle database (for PUSH notifications usually).
1271 * @param string $uuid The device UUID.
1272 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1273 * @return array List of possible warnings and removal status.
1274 * @since Moodle 2.9
1276 public static function remove_user_device($uuid, $appid = "") {
1277 global $CFG;
1278 require_once($CFG->dirroot . "/user/lib.php");
1280 $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1282 $context = context_system::instance();
1283 self::validate_context($context);
1285 // Warnings array, it can be empty at the end but is mandatory.
1286 $warnings = array();
1288 $removed = user_remove_user_device($params['uuid'], $params['appid']);
1290 if (!$removed) {
1291 $warnings[] = array(
1292 'item' => $params['uuid'],
1293 'warningcode' => 'devicedoesnotexist',
1294 'message' => 'The device doesn\'t exists in the database'
1298 $result = array(
1299 'removed' => $removed,
1300 'warnings' => $warnings
1303 return $result;
1307 * Returns description of method result value.
1309 * @return external_multiple_structure
1310 * @since Moodle 2.9
1312 public static function remove_user_device_returns() {
1313 return new external_single_structure(
1314 array(
1315 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
1316 'warnings' => new external_warnings(),
1322 * Returns description of method parameters
1324 * @return external_function_parameters
1325 * @since Moodle 2.9
1327 public static function view_user_list_parameters() {
1328 return new external_function_parameters(
1329 array(
1330 'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site')
1336 * Trigger the user_list_viewed event.
1338 * @param int $courseid id of course
1339 * @return array of warnings and status result
1340 * @since Moodle 2.9
1341 * @throws moodle_exception
1343 public static function view_user_list($courseid) {
1344 global $CFG;
1345 require_once($CFG->dirroot . "/user/lib.php");
1346 require_once($CFG->dirroot . '/course/lib.php');
1348 $params = self::validate_parameters(self::view_user_list_parameters(),
1349 array(
1350 'courseid' => $courseid
1353 $warnings = array();
1355 if (empty($params['courseid'])) {
1356 $params['courseid'] = SITEID;
1359 $course = get_course($params['courseid']);
1361 if ($course->id == SITEID) {
1362 $context = context_system::instance();
1363 } else {
1364 $context = context_course::instance($course->id);
1366 self::validate_context($context);
1368 course_require_view_participants($context);
1370 user_list_view($course, $context);
1372 $result = array();
1373 $result['status'] = true;
1374 $result['warnings'] = $warnings;
1375 return $result;
1379 * Returns description of method result value
1381 * @return external_description
1382 * @since Moodle 2.9
1384 public static function view_user_list_returns() {
1385 return new external_single_structure(
1386 array(
1387 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1388 'warnings' => new external_warnings()
1394 * Returns description of method parameters
1396 * @return external_function_parameters
1397 * @since Moodle 2.9
1399 public static function view_user_profile_parameters() {
1400 return new external_function_parameters(
1401 array(
1402 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1403 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
1409 * Trigger the user profile viewed event.
1411 * @param int $userid id of user
1412 * @param int $courseid id of course
1413 * @return array of warnings and status result
1414 * @since Moodle 2.9
1415 * @throws moodle_exception
1417 public static function view_user_profile($userid, $courseid = 0) {
1418 global $CFG, $USER;
1419 require_once($CFG->dirroot . "/user/profile/lib.php");
1421 $params = self::validate_parameters(self::view_user_profile_parameters(),
1422 array(
1423 'userid' => $userid,
1424 'courseid' => $courseid
1427 $warnings = array();
1429 if (empty($params['userid'])) {
1430 $params['userid'] = $USER->id;
1433 if (empty($params['courseid'])) {
1434 $params['courseid'] = SITEID;
1437 $course = get_course($params['courseid']);
1438 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1439 core_user::require_active_user($user);
1441 if ($course->id == SITEID) {
1442 $coursecontext = context_system::instance();;
1443 } else {
1444 $coursecontext = context_course::instance($course->id);
1446 self::validate_context($coursecontext);
1448 $currentuser = $USER->id == $user->id;
1449 $usercontext = context_user::instance($user->id);
1451 if (!$currentuser and
1452 !has_capability('moodle/user:viewdetails', $coursecontext) and
1453 !has_capability('moodle/user:viewdetails', $usercontext)) {
1454 throw new moodle_exception('cannotviewprofile');
1457 // Case like user/profile.php.
1458 if ($course->id == SITEID) {
1459 profile_view($user, $usercontext);
1460 } else {
1461 // Case like user/view.php.
1462 if (!$currentuser and !can_access_course($course, $user, '', true)) {
1463 throw new moodle_exception('notenrolledprofile');
1466 profile_view($user, $coursecontext, $course);
1469 $result = array();
1470 $result['status'] = true;
1471 $result['warnings'] = $warnings;
1472 return $result;
1476 * Returns description of method result value
1478 * @return external_description
1479 * @since Moodle 2.9
1481 public static function view_user_profile_returns() {
1482 return new external_single_structure(
1483 array(
1484 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1485 'warnings' => new external_warnings()
1491 * Returns description of method parameters
1493 * @return external_function_parameters
1494 * @since Moodle 3.2
1496 public static function get_user_preferences_parameters() {
1497 return new external_function_parameters(
1498 array(
1499 'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''),
1500 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0)
1506 * Return user preferences.
1508 * @param string $name preference name, empty for all
1509 * @param int $userid id of the user, 0 for current user
1510 * @return array of warnings and preferences
1511 * @since Moodle 3.2
1512 * @throws moodle_exception
1514 public static function get_user_preferences($name = '', $userid = 0) {
1515 global $USER;
1517 $params = self::validate_parameters(self::get_user_preferences_parameters(),
1518 array(
1519 'name' => $name,
1520 'userid' => $userid
1522 $preferences = array();
1523 $warnings = array();
1525 $context = context_system::instance();
1526 self::validate_context($context);
1528 if (empty($params['name'])) {
1529 $name = null;
1531 if (empty($params['userid'])) {
1532 $user = null;
1533 } else {
1534 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1535 core_user::require_active_user($user);
1536 if ($user->id != $USER->id) {
1537 // Only admins can retrieve other users preferences.
1538 require_capability('moodle/site:config', $context);
1542 $userpreferences = get_user_preferences($name, null, $user);
1543 // Check if we received just one preference.
1544 if (!is_array($userpreferences)) {
1545 $userpreferences = array($name => $userpreferences);
1548 foreach ($userpreferences as $name => $value) {
1549 $preferences[] = array(
1550 'name' => $name,
1551 'value' => $value,
1555 $result = array();
1556 $result['preferences'] = $preferences;
1557 $result['warnings'] = $warnings;
1558 return $result;
1562 * Returns description of method result value
1564 * @return external_description
1565 * @since Moodle 3.2
1567 public static function get_user_preferences_returns() {
1568 return new external_single_structure(
1569 array(
1570 'preferences' => new external_multiple_structure(
1571 new external_single_structure(
1572 array(
1573 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1574 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1577 'User custom fields (also known as user profile fields)'
1579 'warnings' => new external_warnings()
1585 * Returns description of method parameters
1587 * @return external_function_parameters
1588 * @since Moodle 3.2
1590 public static function update_picture_parameters() {
1591 return new external_function_parameters(
1592 array(
1593 'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'),
1594 'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false),
1595 'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0)
1601 * Update or delete the user picture in the site
1603 * @param int $draftitemid id of the user draft file to use as image
1604 * @param bool $delete if we should delete the user picture
1605 * @param int $userid id of the user, 0 for current user
1606 * @return array warnings and success status
1607 * @since Moodle 3.2
1608 * @throws moodle_exception
1610 public static function update_picture($draftitemid, $delete = false, $userid = 0) {
1611 global $CFG, $USER, $PAGE;
1613 $params = self::validate_parameters(
1614 self::update_picture_parameters(),
1615 array(
1616 'draftitemid' => $draftitemid,
1617 'delete' => $delete,
1618 'userid' => $userid
1622 $context = context_system::instance();
1623 self::validate_context($context);
1625 if (!empty($CFG->disableuserimages)) {
1626 throw new moodle_exception('userimagesdisabled', 'admin');
1629 if (empty($params['userid']) or $params['userid'] == $USER->id) {
1630 $user = $USER;
1631 require_capability('moodle/user:editownprofile', $context);
1632 } else {
1633 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1634 core_user::require_active_user($user);
1635 $personalcontext = context_user::instance($user->id);
1637 require_capability('moodle/user:editprofile', $personalcontext);
1638 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
1639 throw new moodle_exception('useradmineditadmin');
1643 // Load the appropriate auth plugin.
1644 $userauth = get_auth_plugin($user->auth);
1645 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
1646 throw new moodle_exception('noprofileedit', 'auth');
1649 $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image');
1650 $user->deletepicture = $params['delete'];
1651 $user->imagefile = $params['draftitemid'];
1652 $success = core_user::update_picture($user, $filemanageroptions);
1654 $result = array(
1655 'success' => $success,
1656 'warnings' => array(),
1658 if ($success) {
1659 $userpicture = new user_picture(core_user::get_user($user->id));
1660 $userpicture->size = 1; // Size f1.
1661 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1663 return $result;
1667 * Returns description of method result value
1669 * @return external_description
1670 * @since Moodle 3.2
1672 public static function update_picture_returns() {
1673 return new external_single_structure(
1674 array(
1675 'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'),
1676 'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL),
1677 'warnings' => new external_warnings()
1683 * Returns description of method parameters
1685 * @return external_function_parameters
1686 * @since Moodle 3.2
1688 public static function set_user_preferences_parameters() {
1689 return new external_function_parameters(
1690 array(
1691 'preferences' => new external_multiple_structure(
1692 new external_single_structure(
1693 array(
1694 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1695 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
1696 'userid' => new external_value(PARAM_INT, 'Id of the user to set the preference'),
1705 * Set user preferences.
1707 * @param array $preferences list of preferences including name, value and userid
1708 * @return array of warnings and preferences saved
1709 * @since Moodle 3.2
1710 * @throws moodle_exception
1712 public static function set_user_preferences($preferences) {
1713 global $USER;
1715 $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
1716 $warnings = array();
1717 $saved = array();
1719 $context = context_system::instance();
1720 self::validate_context($context);
1722 $userscache = array();
1723 foreach ($params['preferences'] as $pref) {
1724 // Check to which user set the preference.
1725 if (!empty($userscache[$pref['userid']])) {
1726 $user = $userscache[$pref['userid']];
1727 } else {
1728 try {
1729 $user = core_user::get_user($pref['userid'], '*', MUST_EXIST);
1730 core_user::require_active_user($user);
1731 $userscache[$pref['userid']] = $user;
1732 } catch (Exception $e) {
1733 $warnings[] = array(
1734 'item' => 'user',
1735 'itemid' => $pref['userid'],
1736 'warningcode' => 'invaliduser',
1737 'message' => $e->getMessage()
1739 continue;
1743 try {
1744 if (core_user::can_edit_preference($pref['name'], $user)) {
1745 $value = core_user::clean_preference($pref['value'], $pref['name']);
1746 set_user_preference($pref['name'], $value, $user->id);
1747 $saved[] = array(
1748 'name' => $pref['name'],
1749 'userid' => $user->id,
1751 } else {
1752 $warnings[] = array(
1753 'item' => 'user',
1754 'itemid' => $user->id,
1755 'warningcode' => 'nopermission',
1756 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id
1759 } catch (Exception $e) {
1760 $warnings[] = array(
1761 'item' => 'user',
1762 'itemid' => $user->id,
1763 'warningcode' => 'errorsavingpreference',
1764 'message' => $e->getMessage()
1769 $result = array();
1770 $result['saved'] = $saved;
1771 $result['warnings'] = $warnings;
1772 return $result;
1776 * Returns description of method result value
1778 * @return external_description
1779 * @since Moodle 3.2
1781 public static function set_user_preferences_returns() {
1782 return new external_single_structure(
1783 array(
1784 'saved' => new external_multiple_structure(
1785 new external_single_structure(
1786 array(
1787 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
1788 'userid' => new external_value(PARAM_INT, 'The user the preference was set for'),
1790 ), 'Preferences saved'
1792 'warnings' => new external_warnings()
1798 * Returns description of method parameters.
1800 * @return external_function_parameters
1801 * @since Moodle 3.2
1803 public static function agree_site_policy_parameters() {
1804 return new external_function_parameters(array());
1808 * Agree the site policy for the current user.
1810 * @return array of warnings and status result
1811 * @since Moodle 3.2
1812 * @throws moodle_exception
1814 public static function agree_site_policy() {
1815 global $CFG, $DB, $USER;
1817 $warnings = array();
1819 $context = context_system::instance();
1820 try {
1821 // We expect an exception here since the user didn't agree the site policy yet.
1822 self::validate_context($context);
1823 } catch (Exception $e) {
1824 // We are expecting only a sitepolicynotagreed exception.
1825 if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
1826 // In case we receive a different exception, throw it.
1827 throw $e;
1831 $manager = new \core_privacy\local\sitepolicy\manager();
1832 if (!empty($USER->policyagreed)) {
1833 $status = false;
1834 $warnings[] = array(
1835 'item' => 'user',
1836 'itemid' => $USER->id,
1837 'warningcode' => 'alreadyagreed',
1838 'message' => 'The user already agreed the site policy.'
1840 } else if (!$manager->is_defined()) {
1841 $status = false;
1842 $warnings[] = array(
1843 'item' => 'user',
1844 'itemid' => $USER->id,
1845 'warningcode' => 'nositepolicy',
1846 'message' => 'The site does not have a site policy configured.'
1848 } else {
1849 $status = $manager->accept();
1852 $result = array();
1853 $result['status'] = $status;
1854 $result['warnings'] = $warnings;
1855 return $result;
1859 * Returns description of method result value.
1861 * @return external_description
1862 * @since Moodle 3.2
1864 public static function agree_site_policy_returns() {
1865 return new external_single_structure(
1866 array(
1867 'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'),
1868 'warnings' => new external_warnings()
1874 * Returns description of method parameters.
1876 * @return external_function_parameters
1877 * @since Moodle 3.4
1879 public static function get_private_files_info_parameters() {
1880 return new external_function_parameters(
1881 array(
1882 'userid' => new external_value(PARAM_INT, 'Id of the user, default to current user.', VALUE_DEFAULT, 0)
1888 * Returns general information about files in the user private files area.
1890 * @param int $userid Id of the user, default to current user.
1891 * @return array of warnings and file area information
1892 * @since Moodle 3.4
1893 * @throws moodle_exception
1895 public static function get_private_files_info($userid = 0) {
1896 global $CFG, $USER;
1897 require_once($CFG->libdir . '/filelib.php');
1899 $params = self::validate_parameters(self::get_private_files_info_parameters(), array('userid' => $userid));
1900 $warnings = array();
1902 $context = context_system::instance();
1903 self::validate_context($context);
1905 if (empty($params['userid']) || $params['userid'] == $USER->id) {
1906 $usercontext = context_user::instance($USER->id);
1907 require_capability('moodle/user:manageownfiles', $usercontext);
1908 } else {
1909 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1910 core_user::require_active_user($user);
1911 // Only admins can retrieve other users information.
1912 require_capability('moodle/site:config', $context);
1913 $usercontext = context_user::instance($user->id);
1916 $fileareainfo = file_get_file_area_info($usercontext->id, 'user', 'private');
1918 $result = array();
1919 $result['filecount'] = $fileareainfo['filecount'];
1920 $result['foldercount'] = $fileareainfo['foldercount'];
1921 $result['filesize'] = $fileareainfo['filesize'];
1922 $result['filesizewithoutreferences'] = $fileareainfo['filesize_without_references'];
1923 $result['warnings'] = $warnings;
1924 return $result;
1928 * Returns description of method result value.
1930 * @return external_description
1931 * @since Moodle 3.4
1933 public static function get_private_files_info_returns() {
1934 return new external_single_structure(
1935 array(
1936 'filecount' => new external_value(PARAM_INT, 'Number of files in the area.'),
1937 'foldercount' => new external_value(PARAM_INT, 'Number of folders in the area.'),
1938 'filesize' => new external_value(PARAM_INT, 'Total size of the files in the area.'),
1939 'filesizewithoutreferences' => new external_value(PARAM_INT, 'Total size of the area excluding file references'),
1940 'warnings' => new external_warnings()