2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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");
29 * User external functions
33 * @copyright 2011 Jerome Mouneyrac
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class core_user_external
extends external_api
{
40 * Returns description of method parameters
42 * @return external_function_parameters
45 public static function create_users_parameters() {
48 return new external_function_parameters(
50 'users' => new external_multiple_structure(
51 new external_single_structure(
54 new external_value(PARAM_USERNAME
, 'Username policy is defined in Moodle security config.'),
56 new external_value(PARAM_RAW
, 'Plain text password consisting of any characters'),
58 new external_value(PARAM_NOTAGS
, 'The first name(s) of the user'),
60 new external_value(PARAM_NOTAGS
, 'The family name of the user'),
62 new external_value(PARAM_EMAIL
, 'A valid and unique email address'),
64 new external_value(PARAM_PLUGIN
, 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT
,
65 'manual', NULL_NOT_ALLOWED
),
67 new external_value(PARAM_RAW
, 'An arbitrary ID code number perhaps from the institution',
70 new external_value(PARAM_SAFEDIR
, 'Language code such as "en", must exist on server', VALUE_DEFAULT
,
71 $CFG->lang
, NULL_NOT_ALLOWED
),
73 new external_value(PARAM_PLUGIN
, 'Calendar type such as "gregorian", must exist on server',
74 VALUE_DEFAULT
, $CFG->calendartype
, VALUE_OPTIONAL
),
76 new external_value(PARAM_PLUGIN
, 'Theme name such as "standard", must exist on server',
79 new external_value(PARAM_TIMEZONE
, 'Timezone code such as Australia/Perth, or 99 for default',
82 new external_value(PARAM_INT
, 'Mail format code is 0 for plain text, 1 for HTML etc',
85 new external_value(PARAM_TEXT
, 'User profile description, no HTML', VALUE_OPTIONAL
),
87 new external_value(PARAM_NOTAGS
, 'Home city of the user', VALUE_OPTIONAL
),
89 new external_value(PARAM_ALPHA
, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
90 'firstnamephonetic' =>
91 new external_value(PARAM_NOTAGS
, 'The first name(s) phonetically of the user', VALUE_OPTIONAL
),
93 new external_value(PARAM_NOTAGS
, 'The family name phonetically of the user', VALUE_OPTIONAL
),
95 new external_value(PARAM_NOTAGS
, 'The middle name of the user', VALUE_OPTIONAL
),
97 new external_value(PARAM_NOTAGS
, 'The alternate name of the user', VALUE_OPTIONAL
),
98 'preferences' => new external_multiple_structure(
99 new external_single_structure(
101 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the preference'),
102 'value' => new external_value(PARAM_RAW
, 'The value of the preference')
104 ), 'User preferences', VALUE_OPTIONAL
),
105 'customfields' => new external_multiple_structure(
106 new external_single_structure(
108 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the custom field'),
109 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')
111 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL
)
120 * Create one or more users.
122 * @throws invalid_parameter_exception
123 * @param array $users An array of users to create.
124 * @return array An array of arrays
127 public static function create_users($users) {
129 require_once($CFG->dirroot
."/lib/weblib.php");
130 require_once($CFG->dirroot
."/user/lib.php");
131 require_once($CFG->dirroot
."/user/profile/lib.php"); // Required for customfields related function.
133 // Ensure the current user is allowed to run this function.
134 $context = context_system
::instance();
135 self
::validate_context($context);
136 require_capability('moodle/user:create', $context);
138 // Do basic automatic PARAM checks on incoming data, using params description.
139 // If any problems are found then exceptions are thrown with helpful error messages.
140 $params = self
::validate_parameters(self
::create_users_parameters(), array('users' => $users));
142 $availableauths = core_component
::get_plugin_list('auth');
143 unset($availableauths['mnet']); // These would need mnethostid too.
144 unset($availableauths['webservice']); // We do not want new webservice users for now.
146 $availablethemes = core_component
::get_plugin_list('theme');
147 $availablelangs = get_string_manager()->get_list_of_translations();
149 $transaction = $DB->start_delegated_transaction();
152 foreach ($params['users'] as $user) {
153 // Make sure that the username doesn't already exist.
154 if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id
))) {
155 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
158 // Make sure auth is valid.
159 if (empty($availableauths[$user['auth']])) {
160 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
163 // Make sure lang is valid.
164 if (empty($availablelangs[$user['lang']])) {
165 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
168 // Make sure lang is valid.
169 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
170 // so no default value
171 // We need to test if the client sent it
172 // => !empty($user['theme']).
173 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
176 $user['confirmed'] = true;
177 $user['mnethostid'] = $CFG->mnet_localhost_id
;
179 // Start of user info validation.
180 // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
181 if (!validate_email($user['email'])) {
182 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
183 } else if ($DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
184 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
186 // End of user info validation.
188 // Create the user data now!
189 $user['id'] = user_create_user($user, true, false);
192 if (!empty($user['customfields'])) {
193 foreach ($user['customfields'] as $customfield) {
194 // Profile_save_data() saves profile file it's expecting a user with the correct id,
195 // and custom field to be named profile_field_"shortname".
196 $user["profile_field_".$customfield['type']] = $customfield['value'];
198 profile_save_data((object) $user);
202 \core\event\user_created
::create_from_userid($user['id'])->trigger();
205 if (!empty($user['preferences'])) {
206 foreach ($user['preferences'] as $preference) {
207 set_user_preference($preference['type'], $preference['value'], $user['id']);
211 $userids[] = array('id' => $user['id'], 'username' => $user['username']);
214 $transaction->allow_commit();
220 * Returns description of method result value
222 * @return external_description
225 public static function create_users_returns() {
226 return new external_multiple_structure(
227 new external_single_structure(
229 'id' => new external_value(PARAM_INT
, 'user id'),
230 'username' => new external_value(PARAM_USERNAME
, 'user name'),
238 * Returns description of method parameters
240 * @return external_function_parameters
243 public static function delete_users_parameters() {
244 return new external_function_parameters(
246 'userids' => new external_multiple_structure(new external_value(PARAM_INT
, 'user ID')),
254 * @throws moodle_exception
255 * @param array $userids
259 public static function delete_users($userids) {
260 global $CFG, $DB, $USER;
261 require_once($CFG->dirroot
."/user/lib.php");
263 // Ensure the current user is allowed to run this function.
264 $context = context_system
::instance();
265 require_capability('moodle/user:delete', $context);
266 self
::validate_context($context);
268 $params = self
::validate_parameters(self
::delete_users_parameters(), array('userids' => $userids));
270 $transaction = $DB->start_delegated_transaction();
272 foreach ($params['userids'] as $userid) {
273 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST
);
274 // Must not allow deleting of admins or self!!!
275 if (is_siteadmin($user)) {
276 throw new moodle_exception('useradminodelete', 'error');
278 if ($USER->id
== $user->id
) {
279 throw new moodle_exception('usernotdeletederror', 'error');
281 user_delete_user($user);
284 $transaction->allow_commit();
290 * Returns description of method result value
295 public static function delete_users_returns() {
301 * Returns description of method parameters
303 * @return external_function_parameters
306 public static function update_users_parameters() {
307 return new external_function_parameters(
309 'users' => new external_multiple_structure(
310 new external_single_structure(
313 new external_value(PARAM_INT
, 'ID of the user'),
315 new external_value(PARAM_USERNAME
, 'Username policy is defined in Moodle security config.',
316 VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
318 new external_value(PARAM_RAW
, 'Plain text password consisting of any characters', VALUE_OPTIONAL
,
319 '', NULL_NOT_ALLOWED
),
321 new external_value(PARAM_NOTAGS
, 'The first name(s) of the user', VALUE_OPTIONAL
, '',
324 new external_value(PARAM_NOTAGS
, 'The family name of the user', VALUE_OPTIONAL
),
326 new external_value(PARAM_EMAIL
, 'A valid and unique email address', VALUE_OPTIONAL
, '',
329 new external_value(PARAM_PLUGIN
, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL
, '',
332 new external_value(PARAM_RAW
, 'An arbitrary ID code number perhaps from the institution',
335 new external_value(PARAM_SAFEDIR
, 'Language code such as "en", must exist on server',
336 VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
338 new external_value(PARAM_PLUGIN
, 'Calendar type such as "gregorian", must exist on server',
339 VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
341 new external_value(PARAM_PLUGIN
, 'Theme name such as "standard", must exist on server',
344 new external_value(PARAM_TIMEZONE
, 'Timezone code such as Australia/Perth, or 99 for default',
347 new external_value(PARAM_INT
, 'Mail format code is 0 for plain text, 1 for HTML etc',
350 new external_value(PARAM_TEXT
, 'User profile description, no HTML', VALUE_OPTIONAL
),
352 new external_value(PARAM_NOTAGS
, 'Home city of the user', VALUE_OPTIONAL
),
354 new external_value(PARAM_ALPHA
, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
355 'firstnamephonetic' =>
356 new external_value(PARAM_NOTAGS
, 'The first name(s) phonetically of the user', VALUE_OPTIONAL
),
357 'lastnamephonetic' =>
358 new external_value(PARAM_NOTAGS
, 'The family name phonetically of the user', VALUE_OPTIONAL
),
360 new external_value(PARAM_NOTAGS
, 'The middle name of the user', VALUE_OPTIONAL
),
362 new external_value(PARAM_NOTAGS
, 'The alternate name of the user', VALUE_OPTIONAL
),
363 'customfields' => new external_multiple_structure(
364 new external_single_structure(
366 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the custom field'),
367 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')
369 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL
),
370 'preferences' => new external_multiple_structure(
371 new external_single_structure(
373 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the preference'),
374 'value' => new external_value(PARAM_RAW
, 'The value of the preference')
376 ), 'User preferences', VALUE_OPTIONAL
),
387 * @param array $users
391 public static function update_users($users) {
393 require_once($CFG->dirroot
."/user/lib.php");
394 require_once($CFG->dirroot
."/user/profile/lib.php"); // Required for customfields related function.
396 // Ensure the current user is allowed to run this function.
397 $context = context_system
::instance();
398 require_capability('moodle/user:update', $context);
399 self
::validate_context($context);
401 $params = self
::validate_parameters(self
::update_users_parameters(), array('users' => $users));
403 $transaction = $DB->start_delegated_transaction();
405 foreach ($params['users'] as $user) {
406 user_update_user($user, true, false);
407 // Update user custom fields.
408 if (!empty($user['customfields'])) {
410 foreach ($user['customfields'] as $customfield) {
411 // Profile_save_data() saves profile file it's expecting a user with the correct id,
412 // and custom field to be named profile_field_"shortname".
413 $user["profile_field_".$customfield['type']] = $customfield['value'];
415 profile_save_data((object) $user);
419 \core\event\user_updated
::create_from_userid($user['id'])->trigger();
422 if (!empty($user['preferences'])) {
423 foreach ($user['preferences'] as $preference) {
424 set_user_preference($preference['type'], $preference['value'], $user['id']);
429 $transaction->allow_commit();
435 * Returns description of method result value
440 public static function update_users_returns() {
445 * Returns description of method parameters
447 * @return external_function_parameters
450 public static function get_users_by_field_parameters() {
451 return new external_function_parameters(
453 'field' => new external_value(PARAM_ALPHA
, 'the search field can be
454 \'id\' or \'idnumber\' or \'username\' or \'email\''),
455 'values' => new external_multiple_structure(
456 new external_value(PARAM_RAW
, 'the value to match'))
462 * Get user information for a unique field.
464 * @throws coding_exception
465 * @throws invalid_parameter_exception
466 * @param string $field
467 * @param array $values
468 * @return array An array of arrays containg user profiles.
471 public static function get_users_by_field($field, $values) {
472 global $CFG, $USER, $DB;
473 require_once($CFG->dirroot
. "/user/lib.php");
475 $params = self
::validate_parameters(self
::get_users_by_field_parameters(),
476 array('field' => $field, 'values' => $values));
478 // This array will keep all the users that are allowed to be searched,
479 // according to the current user's privileges.
480 $cleanedvalues = array();
484 $paramtype = PARAM_INT
;
487 $paramtype = PARAM_RAW
;
490 $paramtype = PARAM_RAW
;
493 $paramtype = PARAM_EMAIL
;
496 throw new coding_exception('invalid field parameter',
497 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
501 foreach ($values as $value) {
502 $cleanedvalue = clean_param($value, $paramtype);
503 if ( $value != $cleanedvalue) {
504 throw new invalid_parameter_exception('The field \'' . $field .
505 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
507 $cleanedvalues[] = $cleanedvalue;
510 // Retrieve the users.
511 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
513 // Finally retrieve each users information.
514 $returnedusers = array();
515 foreach ($users as $user) {
516 $userdetails = user_get_user_details_courses($user);
518 // Return the user only if the searched field is returned.
519 // Otherwise it means that the $USER was not allowed to search the returned user.
520 if (!empty($userdetails) and !empty($userdetails[$field])) {
521 $returnedusers[] = $userdetails;
525 return $returnedusers;
529 * Returns description of method result value
531 * @return external_multiple_structure
534 public static function get_users_by_field_returns() {
535 return new external_multiple_structure(self
::user_description());
540 * Returns description of get_users() parameters.
542 * @return external_function_parameters
545 public static function get_users_parameters() {
546 return new external_function_parameters(
548 'criteria' => new external_multiple_structure(
549 new external_single_structure(
551 'key' => new external_value(PARAM_ALPHA
, 'the user column to search, expected keys (value format) are:
552 "id" (int) matching user id,
553 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
554 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
555 "idnumber" (string) matching user idnumber,
556 "username" (string) matching user username,
557 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
558 "auth" (string) matching user auth plugin'),
559 'value' => new external_value(PARAM_RAW
, 'the value to search')
561 ), 'the key/value pairs to be considered in user search. Values can not be empty.
562 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
563 key occurences are forbidden.
564 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
565 the search is still executed on the valid criterias.
566 You can search without criteria, but the function is not designed for it.
567 It could very slow or timeout. The function is designed to search some specific users.'
574 * Retrieve matching user.
576 * @throws moodle_exception
577 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
578 * @return array An array of arrays containing user profiles.
581 public static function get_users($criteria = array()) {
582 global $CFG, $USER, $DB;
584 require_once($CFG->dirroot
. "/user/lib.php");
586 $params = self
::validate_parameters(self
::get_users_parameters(),
587 array('criteria' => $criteria));
589 // Validate the criteria and retrieve the users.
592 $sqlparams = array();
595 // Do not retrieve deleted users.
596 $sql = ' deleted = 0';
598 foreach ($params['criteria'] as $criteriaindex => $criteria) {
600 // Check that the criteria has never been used.
601 if (array_key_exists($criteria['key'], $usedkeys)) {
602 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
604 $usedkeys[$criteria['key']] = true;
607 $invalidcriteria = false;
608 // Clean the parameters.
609 $paramtype = PARAM_RAW
;
610 switch ($criteria['key']) {
612 $paramtype = PARAM_INT
;
615 $paramtype = PARAM_RAW
;
618 $paramtype = PARAM_RAW
;
621 // We use PARAM_RAW to allow searches with %.
622 $paramtype = PARAM_RAW
;
625 $paramtype = PARAM_AUTH
;
629 $paramtype = PARAM_TEXT
;
632 // Send back a warning that this search key is not supported in this version.
633 // This warning will make the function extandable without breaking clients.
635 'item' => $criteria['key'],
636 'warningcode' => 'invalidfieldparameter',
638 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
640 // Do not add this invalid criteria to the created SQL request.
641 $invalidcriteria = true;
642 unset($params['criteria'][$criteriaindex]);
646 if (!$invalidcriteria) {
647 $cleanedvalue = clean_param($criteria['value'], $paramtype);
652 switch ($criteria['key']) {
657 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
658 $sqlparams[$criteria['key']] = $cleanedvalue;
663 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
664 $sqlparams[$criteria['key']] = $cleanedvalue;
672 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
674 // Finally retrieve each users information.
675 $returnedusers = array();
676 foreach ($users as $user) {
677 $userdetails = user_get_user_details_courses($user);
679 // Return the user only if all the searched fields are returned.
680 // Otherwise it means that the $USER was not allowed to search the returned user.
681 if (!empty($userdetails)) {
684 foreach ($params['criteria'] as $criteria) {
685 if (empty($userdetails[$criteria['key']])) {
691 $returnedusers[] = $userdetails;
696 return array('users' => $returnedusers, 'warnings' => $warnings);
700 * Returns description of get_users result value.
702 * @return external_description
705 public static function get_users_returns() {
706 return new external_single_structure(
707 array('users' => new external_multiple_structure(
708 self
::user_description()
710 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
716 * Returns description of method parameters
718 * @return external_function_parameters
720 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
721 * @see core_user_external::get_users_by_field_parameters()
723 public static function get_users_by_id_parameters() {
724 return new external_function_parameters(
726 'userids' => new external_multiple_structure(new external_value(PARAM_INT
, 'user ID')),
732 * Get user information
733 * - This function is matching the permissions of /user/profil.php
734 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
735 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
737 * @param array $userids array of user ids
738 * @return array An array of arrays describing users
740 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
741 * @see core_user_external::get_users_by_field()
743 public static function get_users_by_id($userids) {
744 global $CFG, $USER, $DB;
745 require_once($CFG->dirroot
. "/user/lib.php");
747 $params = self
::validate_parameters(self
::get_users_by_id_parameters(),
748 array('userids' => $userids));
750 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
);
751 $uselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
752 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
753 $params['contextlevel'] = CONTEXT_USER
;
754 $usersql = "SELECT u.* $uselect
756 WHERE u.id $sqluserids";
757 $users = $DB->get_recordset_sql($usersql, $params);
760 $hasuserupdatecap = has_capability('moodle/user:update', context_system
::instance());
761 foreach ($users as $user) {
762 if (!empty($user->deleted
)) {
765 context_helper
::preload_from_record($user);
766 $usercontext = context_user
::instance($user->id
, IGNORE_MISSING
);
767 self
::validate_context($usercontext);
768 $currentuser = ($user->id
== $USER->id
);
770 if ($userarray = user_get_user_details($user)) {
771 // Fields matching permissions from /user/editadvanced.php.
772 if ($currentuser or $hasuserupdatecap) {
773 $userarray['auth'] = $user->auth
;
774 $userarray['confirmed'] = $user->confirmed
;
775 $userarray['idnumber'] = $user->idnumber
;
776 $userarray['lang'] = $user->lang
;
777 $userarray['theme'] = $user->theme
;
778 $userarray['timezone'] = $user->timezone
;
779 $userarray['mailformat'] = $user->mailformat
;
781 $result[] = $userarray;
790 * Returns description of method result value
792 * @return external_description
794 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
795 * @see core_user_external::get_users_by_field_returns()
797 public static function get_users_by_id_returns() {
798 $additionalfields = array (
799 'enrolledcourses' => new external_multiple_structure(
800 new external_single_structure(
802 'id' => new external_value(PARAM_INT
, 'Id of the course'),
803 'fullname' => new external_value(PARAM_RAW
, 'Fullname of the course'),
804 'shortname' => new external_value(PARAM_RAW
, 'Shortname of the course')
806 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
));
807 return new external_multiple_structure(self
::user_description($additionalfields));
811 * Returns description of method parameters
813 * @return external_function_parameters
816 public static function get_course_user_profiles_parameters() {
817 return new external_function_parameters(
819 'userlist' => new external_multiple_structure(
820 new external_single_structure(
822 'userid' => new external_value(PARAM_INT
, 'userid'),
823 'courseid' => new external_value(PARAM_INT
, 'courseid'),
832 * Get course participant's details
834 * @param array $userlist array of user ids and according course ids
835 * @return array An array of arrays describing course participants
838 public static function get_course_user_profiles($userlist) {
839 global $CFG, $USER, $DB;
840 require_once($CFG->dirroot
. "/user/lib.php");
841 $params = self
::validate_parameters(self
::get_course_user_profiles_parameters(), array('userlist' => $userlist));
844 $courseids = array();
845 foreach ($params['userlist'] as $value) {
846 $userids[] = $value['userid'];
847 $courseids[$value['userid']] = $value['courseid'];
850 // Cache all courses.
852 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED
);
853 $cselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
854 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
855 $params['contextlevel'] = CONTEXT_COURSE
;
856 $coursesql = "SELECT c.* $cselect
857 FROM {course} c $cjoin
858 WHERE c.id $sqlcourseids";
859 $rs = $DB->get_recordset_sql($coursesql, $params);
860 foreach ($rs as $course) {
861 // Adding course contexts to cache.
862 context_helper
::preload_from_record($course);
864 $courses[$course->id
] = $course;
868 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
);
869 $uselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
870 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
871 $params['contextlevel'] = CONTEXT_USER
;
872 $usersql = "SELECT u.* $uselect
874 WHERE u.id $sqluserids";
875 $users = $DB->get_recordset_sql($usersql, $params);
877 foreach ($users as $user) {
878 if (!empty($user->deleted
)) {
881 context_helper
::preload_from_record($user);
882 $course = $courses[$courseids[$user->id
]];
883 $context = context_course
::instance($courseids[$user->id
], IGNORE_MISSING
);
884 self
::validate_context($context);
885 if ($userarray = user_get_user_details($user, $course)) {
886 $result[] = $userarray;
896 * Returns description of method result value
898 * @return external_description
901 public static function get_course_user_profiles_returns() {
902 $additionalfields = array(
903 'groups' => new external_multiple_structure(
904 new external_single_structure(
906 'id' => new external_value(PARAM_INT
, 'group id'),
907 'name' => new external_value(PARAM_RAW
, 'group name'),
908 'description' => new external_value(PARAM_RAW
, 'group description'),
909 'descriptionformat' => new external_format_value('description'),
911 ), 'user groups', VALUE_OPTIONAL
),
912 'roles' => new external_multiple_structure(
913 new external_single_structure(
915 'roleid' => new external_value(PARAM_INT
, 'role id'),
916 'name' => new external_value(PARAM_RAW
, 'role name'),
917 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'role shortname'),
918 'sortorder' => new external_value(PARAM_INT
, 'role sortorder')
920 ), 'user roles', VALUE_OPTIONAL
),
921 'enrolledcourses' => new external_multiple_structure(
922 new external_single_structure(
924 'id' => new external_value(PARAM_INT
, 'Id of the course'),
925 'fullname' => new external_value(PARAM_RAW
, 'Fullname of the course'),
926 'shortname' => new external_value(PARAM_RAW
, 'Shortname of the course')
928 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
)
931 return new external_multiple_structure(self
::user_description($additionalfields));
935 * Create user return value description.
937 * @param array $additionalfields some additional field
938 * @return single_structure_description
940 public static function user_description($additionalfields = array()) {
942 'id' => new external_value(PARAM_INT
, 'ID of the user'),
943 'username' => new external_value(PARAM_RAW
, 'The username', VALUE_OPTIONAL
),
944 'firstname' => new external_value(PARAM_NOTAGS
, 'The first name(s) of the user', VALUE_OPTIONAL
),
945 'lastname' => new external_value(PARAM_NOTAGS
, 'The family name of the user', VALUE_OPTIONAL
),
946 'fullname' => new external_value(PARAM_NOTAGS
, 'The fullname of the user'),
947 'email' => new external_value(PARAM_TEXT
, 'An email address - allow email as root@localhost', VALUE_OPTIONAL
),
948 'address' => new external_value(PARAM_TEXT
, 'Postal address', VALUE_OPTIONAL
),
949 'phone1' => new external_value(PARAM_NOTAGS
, 'Phone 1', VALUE_OPTIONAL
),
950 'phone2' => new external_value(PARAM_NOTAGS
, 'Phone 2', VALUE_OPTIONAL
),
951 'icq' => new external_value(PARAM_NOTAGS
, 'icq number', VALUE_OPTIONAL
),
952 'skype' => new external_value(PARAM_NOTAGS
, 'skype id', VALUE_OPTIONAL
),
953 'yahoo' => new external_value(PARAM_NOTAGS
, 'yahoo id', VALUE_OPTIONAL
),
954 'aim' => new external_value(PARAM_NOTAGS
, 'aim id', VALUE_OPTIONAL
),
955 'msn' => new external_value(PARAM_NOTAGS
, 'msn number', VALUE_OPTIONAL
),
956 'department' => new external_value(PARAM_TEXT
, 'department', VALUE_OPTIONAL
),
957 'institution' => new external_value(PARAM_TEXT
, 'institution', VALUE_OPTIONAL
),
958 'idnumber' => new external_value(PARAM_RAW
, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL
),
959 'interests' => new external_value(PARAM_TEXT
, 'user interests (separated by commas)', VALUE_OPTIONAL
),
960 'firstaccess' => new external_value(PARAM_INT
, 'first access to the site (0 if never)', VALUE_OPTIONAL
),
961 'lastaccess' => new external_value(PARAM_INT
, 'last access to the site (0 if never)', VALUE_OPTIONAL
),
962 'auth' => new external_value(PARAM_PLUGIN
, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL
),
963 'confirmed' => new external_value(PARAM_INT
, 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL
),
964 'lang' => new external_value(PARAM_SAFEDIR
, 'Language code such as "en", must exist on server', VALUE_OPTIONAL
),
965 'calendartype' => new external_value(PARAM_PLUGIN
, 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL
),
966 'theme' => new external_value(PARAM_PLUGIN
, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL
),
967 'timezone' => new external_value(PARAM_TIMEZONE
, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL
),
968 'mailformat' => new external_value(PARAM_INT
, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL
),
969 'description' => new external_value(PARAM_RAW
, 'User profile description', VALUE_OPTIONAL
),
970 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL
),
971 'city' => new external_value(PARAM_NOTAGS
, 'Home city of the user', VALUE_OPTIONAL
),
972 'url' => new external_value(PARAM_URL
, 'URL of the user', VALUE_OPTIONAL
),
973 'country' => new external_value(PARAM_ALPHA
, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL
),
974 'profileimageurlsmall' => new external_value(PARAM_URL
, 'User image profile URL - small version'),
975 'profileimageurl' => new external_value(PARAM_URL
, 'User image profile URL - big version'),
976 'customfields' => new external_multiple_structure(
977 new external_single_structure(
979 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The type of the custom field - text field, checkbox...'),
980 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
981 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
982 'shortname' => new external_value(PARAM_RAW
, 'The shortname of the custom field - to be able to build the field class in the code'),
984 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL
),
985 'preferences' => new external_multiple_structure(
986 new external_single_structure(
988 'name' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the preferences'),
989 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
991 ), 'Users preferences', VALUE_OPTIONAL
)
993 if (!empty($additionalfields)) {
994 $userfields = array_merge($userfields, $additionalfields);
996 return new external_single_structure($userfields);
1000 * Returns description of method parameters
1002 * @return external_function_parameters
1005 public static function add_user_private_files_parameters() {
1006 return new external_function_parameters(
1008 'draftid' => new external_value(PARAM_INT
, 'draft area id')
1014 * Copy files from a draft area to users private files area.
1016 * @throws invalid_parameter_exception
1017 * @param int $draftid Id of a draft area containing files.
1018 * @return array An array of warnings
1021 public static function add_user_private_files($draftid) {
1022 global $CFG, $USER, $DB;
1024 require_once($CFG->dirroot
. "/user/lib.php");
1025 $params = self
::validate_parameters(self
::add_user_private_files_parameters(), array('draftid' => $draftid));
1027 if (isguestuser()) {
1028 throw new invalid_parameter_exception('Guest users cannot upload files');
1031 $context = context_user
::instance($USER->id
);
1032 require_capability('moodle/user:manageownfiles', $context);
1034 $maxbytes = $CFG->userquota
;
1035 $maxareabytes = $CFG->userquota
;
1036 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1037 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
1038 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED
;
1041 $options = array('subdirs' => 1,
1042 'maxbytes' => $maxbytes,
1044 'accepted_types' => '*',
1045 'areamaxbytes' => $maxareabytes);
1047 file_save_draft_area_files($draftid, $context->id
, 'user', 'private', 0, $options);
1053 * Returns description of method result value
1055 * @return external_description
1058 public static function add_user_private_files_returns() {
1063 * Returns description of method parameters.
1065 * @return external_function_parameters
1068 public static function add_user_device_parameters() {
1069 return new external_function_parameters(
1071 'appid' => new external_value(PARAM_NOTAGS
, 'the app id, usually something like com.moodle.moodlemobile'),
1072 'name' => new external_value(PARAM_NOTAGS
, 'the device name, \'occam\' or \'iPhone\' etc.'),
1073 'model' => new external_value(PARAM_NOTAGS
, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1074 'platform' => new external_value(PARAM_NOTAGS
, 'the device platform \'iOS\' or \'Android\' etc.'),
1075 'version' => new external_value(PARAM_NOTAGS
, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1076 'pushid' => new external_value(PARAM_RAW
, 'the device PUSH token/key/identifier/registration id'),
1077 'uuid' => new external_value(PARAM_RAW
, 'the device UUID')
1083 * Add a user device in Moodle database (for PUSH notifications usually).
1085 * @throws moodle_exception
1086 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1087 * @param string $name The device name, occam or iPhone etc.
1088 * @param string $model The device model Nexus4 or iPad1.1 etc.
1089 * @param string $platform The device platform iOs or Android etc.
1090 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1091 * @param string $pushid The device PUSH token/key/identifier/registration id.
1092 * @param string $uuid The device UUID.
1093 * @return array List of possible warnings.
1096 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1097 global $CFG, $USER, $DB;
1098 require_once($CFG->dirroot
. "/user/lib.php");
1100 $params = self
::validate_parameters(self
::add_user_device_parameters(),
1101 array('appid' => $appid,
1104 'platform' => $platform,
1105 'version' => $version,
1106 'pushid' => $pushid,
1110 $warnings = array();
1112 // Prevent duplicate keys for users.
1113 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id
))) {
1114 $warnings['warning'][] = array(
1115 'item' => $params['pushid'],
1116 'warningcode' => 'existingkeyforthisuser',
1117 'message' => 'This key is already stored for this user'
1122 $userdevice = new stdclass
;
1123 $userdevice->userid
= $USER->id
;
1124 $userdevice->appid
= $params['appid'];
1125 $userdevice->name
= $params['name'];
1126 $userdevice->model
= $params['model'];
1127 $userdevice->platform
= $params['platform'];
1128 $userdevice->version
= $params['version'];
1129 $userdevice->pushid
= $params['pushid'];
1130 $userdevice->uuid
= $params['uuid'];
1131 $userdevice->timecreated
= time();
1132 $userdevice->timemodified
= $userdevice->timecreated
;
1134 if (!$DB->insert_record('user_devices', $userdevice)) {
1135 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1142 * Returns description of method result value.
1144 * @return external_multiple_structure
1147 public static function add_user_device_returns() {
1148 return new external_multiple_structure(
1149 new external_warnings()
1156 * Deprecated user external functions
1158 * @package core_user
1159 * @copyright 2009 Petr Skodak
1160 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1162 * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
1163 * @see core_user_external
1165 class moodle_user_external
extends external_api
{
1168 * Returns description of method parameters
1170 * @return external_function_parameters
1172 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1173 * @see core_user_external::create_users_parameters()
1175 public static function create_users_parameters() {
1176 return core_user_external
::create_users_parameters();
1180 * Create one or more users
1182 * @param array $users An array of users to create.
1183 * @return array An array of arrays
1185 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1186 * @see core_user_external::create_users()
1188 public static function create_users($users) {
1189 return core_user_external
::create_users($users);
1193 * Returns description of method result value
1195 * @return external_description
1197 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1198 * @see core_user_external::create_users_returns()
1200 public static function create_users_returns() {
1201 return core_user_external
::create_users_returns();
1206 * Returns description of method parameters
1208 * @return external_function_parameters
1210 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1211 * @see core_user_external::delete_users_parameters()
1213 public static function delete_users_parameters() {
1214 return core_user_external
::delete_users_parameters();
1220 * @param array $userids
1223 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1224 * @see core_user_external::delete_users()
1226 public static function delete_users($userids) {
1227 return core_user_external
::delete_users($userids);
1231 * Returns description of method result value
1235 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1236 * @see core_user_external::delete_users_returns()
1238 public static function delete_users_returns() {
1239 return core_user_external
::delete_users_returns();
1244 * Returns description of method parameters
1246 * @return external_function_parameters
1248 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1249 * @see core_user_external::update_users_parameters()
1251 public static function update_users_parameters() {
1252 return core_user_external
::update_users_parameters();
1258 * @param array $users
1261 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1262 * @see core_user_external::update_users()
1264 public static function update_users($users) {
1265 return core_user_external
::update_users($users);
1269 * Returns description of method result value
1273 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1274 * @see core_user_external::update_users_returns()
1276 public static function update_users_returns() {
1277 return core_user_external
::update_users_returns();
1281 * Returns description of method parameters
1283 * @return external_function_parameters
1285 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1286 * @see core_user_external::get_users_by_id_parameters()
1288 public static function get_users_by_id_parameters() {
1289 return core_user_external
::get_users_by_id_parameters();
1293 * Get user information
1294 * - This function is matching the permissions of /user/profil.php
1295 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
1296 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
1298 * @param array $userids array of user ids
1299 * @return array An array of arrays describing users
1301 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1302 * @see core_user_external::get_users_by_id()
1304 public static function get_users_by_id($userids) {
1305 return core_user_external
::get_users_by_id($userids);
1309 * Returns description of method result value
1311 * @return external_description
1313 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1314 * @see core_user_external::get_users_by_id_returns()
1316 public static function get_users_by_id_returns() {
1317 return core_user_external
::get_users_by_id_returns();
1320 * Returns description of method parameters
1322 * @return external_function_parameters
1324 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1325 * @see core_user_external::get_course_user_profiles_parameters()
1327 public static function get_course_participants_by_id_parameters() {
1328 return core_user_external
::get_course_user_profiles_parameters();
1332 * Get course participant's details
1334 * @param array $userlist array of user ids and according course ids
1335 * @return array An array of arrays describing course participants
1337 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1338 * @see core_user_external::get_course_user_profiles()
1340 public static function get_course_participants_by_id($userlist) {
1341 return core_user_external
::get_course_user_profiles($userlist);
1345 * Returns description of method result value
1347 * @return external_description
1349 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1350 * @see core_user_external::get_course_user_profiles_returns()
1352 public static function get_course_participants_by_id_returns() {
1353 return core_user_external
::get_course_user_profiles_returns();
1357 * Returns description of method parameters
1359 * @return external_function_parameters
1361 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1362 * @see core_enrol_external::get_enrolled_users_parameters()
1364 public static function get_users_by_courseid_parameters() {
1366 require_once($CFG->dirroot
. '/enrol/externallib.php');
1367 return core_enrol_external
::get_enrolled_users_parameters();
1371 * Get course participants details
1373 * @param int $courseid course id
1374 * @param array $options options {
1375 * 'name' => option name
1376 * 'value' => option value
1378 * @return array An array of users
1380 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1381 * @see core_enrol_external::get_enrolled_users()
1383 public static function get_users_by_courseid($courseid, $options) {
1385 require_once($CFG->dirroot
. '/enrol/externallib.php');
1386 return core_enrol_external
::get_enrolled_users($courseid, $options);
1389 * Returns description of method result value
1391 * @return external_description
1393 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1394 * @see core_enrol_external::get_enrolled_users_returns()
1396 public static function get_users_by_courseid_returns() {
1398 require_once($CFG->dirroot
. '/enrol/externallib.php');
1399 return core_enrol_external
::get_enrolled_users_returns();