MDL-44717 events: Fix for the name strings in various events.
[moodle.git] / user / externallib.php
blob506b629c453a1a8a07b2ca2a347b9c303fc42ef9
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * External user API
20 * @package core_user
21 * @category external
22 * @copyright 2009 Petr Skodak
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once("$CFG->libdir/externallib.php");
28 /**
29 * User external functions
31 * @package core_user
32 * @category external
33 * @copyright 2011 Jerome Mouneyrac
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 * @since Moodle 2.2
37 class core_user_external extends external_api {
39 /**
40 * Returns description of method parameters
42 * @return external_function_parameters
43 * @since Moodle 2.2
45 public static function create_users_parameters() {
46 global $CFG;
48 return new external_function_parameters(
49 array(
50 'users' => new external_multiple_structure(
51 new external_single_structure(
52 array(
53 'username' =>
54 new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config.'),
55 'password' =>
56 new external_value(PARAM_RAW, 'Plain text password consisting of any characters'),
57 'firstname' =>
58 new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
59 'lastname' =>
60 new external_value(PARAM_NOTAGS, 'The family name of the user'),
61 'email' =>
62 new external_value(PARAM_EMAIL, 'A valid and unique email address'),
63 'auth' =>
64 new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT,
65 'manual', NULL_NOT_ALLOWED),
66 'idnumber' =>
67 new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution',
68 VALUE_DEFAULT, ''),
69 'lang' =>
70 new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_DEFAULT,
71 $CFG->lang, NULL_NOT_ALLOWED),
72 'calendartype' =>
73 new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server',
74 VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
75 'theme' =>
76 new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server',
77 VALUE_OPTIONAL),
78 'timezone' =>
79 new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default',
80 VALUE_OPTIONAL),
81 'mailformat' =>
82 new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc',
83 VALUE_OPTIONAL),
84 'description' =>
85 new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
86 'city' =>
87 new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
88 'country' =>
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),
92 'lastnamephonetic' =>
93 new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
94 'middlename' =>
95 new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
96 'alternatename' =>
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(
100 array(
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(
107 array(
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
125 * @since Moodle 2.2
127 public static function create_users($users) {
128 global $CFG, $DB;
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();
151 $userids = array();
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);
191 // Custom fields.
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);
201 // Preferences.
202 if (!empty($user['preferences'])) {
203 foreach ($user['preferences'] as $preference) {
204 set_user_preference($preference['type'], $preference['value'], $user['id']);
208 $userids[] = array('id' => $user['id'], 'username' => $user['username']);
211 $transaction->allow_commit();
213 return $userids;
217 * Returns description of method result value
219 * @return external_description
220 * @since Moodle 2.2
222 public static function create_users_returns() {
223 return new external_multiple_structure(
224 new external_single_structure(
225 array(
226 'id' => new external_value(PARAM_INT, 'user id'),
227 'username' => new external_value(PARAM_USERNAME, 'user name'),
235 * Returns description of method parameters
237 * @return external_function_parameters
238 * @since Moodle 2.2
240 public static function delete_users_parameters() {
241 return new external_function_parameters(
242 array(
243 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
249 * Delete users
251 * @throws moodle_exception
252 * @param array $userids
253 * @return null
254 * @since Moodle 2.2
256 public static function delete_users($userids) {
257 global $CFG, $DB, $USER;
258 require_once($CFG->dirroot."/user/lib.php");
260 // Ensure the current user is allowed to run this function.
261 $context = context_system::instance();
262 require_capability('moodle/user:delete', $context);
263 self::validate_context($context);
265 $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
267 $transaction = $DB->start_delegated_transaction();
269 foreach ($params['userids'] as $userid) {
270 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
271 // Must not allow deleting of admins or self!!!
272 if (is_siteadmin($user)) {
273 throw new moodle_exception('useradminodelete', 'error');
275 if ($USER->id == $user->id) {
276 throw new moodle_exception('usernotdeletederror', 'error');
278 user_delete_user($user);
281 $transaction->allow_commit();
283 return null;
287 * Returns description of method result value
289 * @return null
290 * @since Moodle 2.2
292 public static function delete_users_returns() {
293 return null;
298 * Returns description of method parameters
300 * @return external_function_parameters
301 * @since Moodle 2.2
303 public static function update_users_parameters() {
304 return new external_function_parameters(
305 array(
306 'users' => new external_multiple_structure(
307 new external_single_structure(
308 array(
309 'id' =>
310 new external_value(PARAM_INT, 'ID of the user'),
311 'username' =>
312 new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config.',
313 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
314 'password' =>
315 new external_value(PARAM_RAW, 'Plain text password consisting of any characters', VALUE_OPTIONAL,
316 '', NULL_NOT_ALLOWED),
317 'firstname' =>
318 new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL, '',
319 NULL_NOT_ALLOWED),
320 'lastname' =>
321 new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
322 'email' =>
323 new external_value(PARAM_EMAIL, 'A valid and unique email address', VALUE_OPTIONAL, '',
324 NULL_NOT_ALLOWED),
325 'auth' =>
326 new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL, '',
327 NULL_NOT_ALLOWED),
328 'idnumber' =>
329 new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution',
330 VALUE_OPTIONAL),
331 'lang' =>
332 new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server',
333 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
334 'calendartype' =>
335 new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server',
336 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
337 'theme' =>
338 new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server',
339 VALUE_OPTIONAL),
340 'timezone' =>
341 new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default',
342 VALUE_OPTIONAL),
343 'mailformat' =>
344 new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc',
345 VALUE_OPTIONAL),
346 'description' =>
347 new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
348 'city' =>
349 new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
350 'country' =>
351 new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
352 'firstnamephonetic' =>
353 new external_value(PARAM_NOTAGS, 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
354 'lastnamephonetic' =>
355 new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
356 'middlename' =>
357 new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
358 'alternatename' =>
359 new external_value(PARAM_NOTAGS, 'The alternate name of the user', VALUE_OPTIONAL),
360 'customfields' => new external_multiple_structure(
361 new external_single_structure(
362 array(
363 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
364 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
366 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
367 'preferences' => new external_multiple_structure(
368 new external_single_structure(
369 array(
370 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
371 'value' => new external_value(PARAM_RAW, 'The value of the preference')
373 ), 'User preferences', VALUE_OPTIONAL),
382 * Update users
384 * @param array $users
385 * @return null
386 * @since Moodle 2.2
388 public static function update_users($users) {
389 global $CFG, $DB;
390 require_once($CFG->dirroot."/user/lib.php");
391 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
393 // Ensure the current user is allowed to run this function.
394 $context = context_system::instance();
395 require_capability('moodle/user:update', $context);
396 self::validate_context($context);
398 $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
400 $transaction = $DB->start_delegated_transaction();
402 foreach ($params['users'] as $user) {
403 user_update_user($user);
404 // Update user custom fields.
405 if (!empty($user['customfields'])) {
407 foreach ($user['customfields'] as $customfield) {
408 // Profile_save_data() saves profile file it's expecting a user with the correct id,
409 // and custom field to be named profile_field_"shortname".
410 $user["profile_field_".$customfield['type']] = $customfield['value'];
412 profile_save_data((object) $user);
415 // Preferences.
416 if (!empty($user['preferences'])) {
417 foreach ($user['preferences'] as $preference) {
418 set_user_preference($preference['type'], $preference['value'], $user['id']);
423 $transaction->allow_commit();
425 return null;
429 * Returns description of method result value
431 * @return null
432 * @since Moodle 2.2
434 public static function update_users_returns() {
435 return null;
439 * Returns description of method parameters
441 * @return external_function_parameters
442 * @since Moodle 2.4
444 public static function get_users_by_field_parameters() {
445 return new external_function_parameters(
446 array(
447 'field' => new external_value(PARAM_ALPHA, 'the search field can be
448 \'id\' or \'idnumber\' or \'username\' or \'email\''),
449 'values' => new external_multiple_structure(
450 new external_value(PARAM_RAW, 'the value to match'))
456 * Get user information for a unique field.
458 * @throws coding_exception
459 * @throws invalid_parameter_exception
460 * @param string $field
461 * @param array $values
462 * @return array An array of arrays containg user profiles.
463 * @since Moodle 2.4
465 public static function get_users_by_field($field, $values) {
466 global $CFG, $USER, $DB;
467 require_once($CFG->dirroot . "/user/lib.php");
469 $params = self::validate_parameters(self::get_users_by_field_parameters(),
470 array('field' => $field, 'values' => $values));
472 // This array will keep all the users that are allowed to be searched,
473 // according to the current user's privileges.
474 $cleanedvalues = array();
476 switch ($field) {
477 case 'id':
478 $paramtype = PARAM_INT;
479 break;
480 case 'idnumber':
481 $paramtype = PARAM_RAW;
482 break;
483 case 'username':
484 $paramtype = PARAM_RAW;
485 break;
486 case 'email':
487 $paramtype = PARAM_EMAIL;
488 break;
489 default:
490 throw new coding_exception('invalid field parameter',
491 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
494 // Clean the values.
495 foreach ($values as $value) {
496 $cleanedvalue = clean_param($value, $paramtype);
497 if ( $value != $cleanedvalue) {
498 throw new invalid_parameter_exception('The field \'' . $field .
499 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
501 $cleanedvalues[] = $cleanedvalue;
504 // Retrieve the users.
505 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
507 // Finally retrieve each users information.
508 $returnedusers = array();
509 foreach ($users as $user) {
510 $userdetails = user_get_user_details_courses($user);
512 // Return the user only if the searched field is returned.
513 // Otherwise it means that the $USER was not allowed to search the returned user.
514 if (!empty($userdetails) and !empty($userdetails[$field])) {
515 $returnedusers[] = $userdetails;
519 return $returnedusers;
523 * Returns description of method result value
525 * @return external_multiple_structure
526 * @since Moodle 2.4
528 public static function get_users_by_field_returns() {
529 return new external_multiple_structure(self::user_description());
534 * Returns description of get_users() parameters.
536 * @return external_function_parameters
537 * @since Moodle 2.5
539 public static function get_users_parameters() {
540 return new external_function_parameters(
541 array(
542 'criteria' => new external_multiple_structure(
543 new external_single_structure(
544 array(
545 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
546 "id" (int) matching user id,
547 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
548 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
549 "idnumber" (string) matching user idnumber,
550 "username" (string) matching user username,
551 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
552 "auth" (string) matching user auth plugin'),
553 'value' => new external_value(PARAM_RAW, 'the value to search')
555 ), 'the key/value pairs to be considered in user search. Values can not be empty.
556 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
557 key occurences are forbidden.
558 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
559 the search is still executed on the valid criterias.
560 You can search without criteria, but the function is not designed for it.
561 It could very slow or timeout. The function is designed to search some specific users.'
568 * Retrieve matching user.
570 * @throws moodle_exception
571 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
572 * @return array An array of arrays containing user profiles.
573 * @since Moodle 2.5
575 public static function get_users($criteria = array()) {
576 global $CFG, $USER, $DB;
578 require_once($CFG->dirroot . "/user/lib.php");
580 $params = self::validate_parameters(self::get_users_parameters(),
581 array('criteria' => $criteria));
583 // Validate the criteria and retrieve the users.
584 $users = array();
585 $warnings = array();
586 $sqlparams = array();
587 $usedkeys = array();
589 // Do not retrieve deleted users.
590 $sql = ' deleted = 0';
592 foreach ($params['criteria'] as $criteriaindex => $criteria) {
594 // Check that the criteria has never been used.
595 if (array_key_exists($criteria['key'], $usedkeys)) {
596 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
597 } else {
598 $usedkeys[$criteria['key']] = true;
601 $invalidcriteria = false;
602 // Clean the parameters.
603 $paramtype = PARAM_RAW;
604 switch ($criteria['key']) {
605 case 'id':
606 $paramtype = PARAM_INT;
607 break;
608 case 'idnumber':
609 $paramtype = PARAM_RAW;
610 break;
611 case 'username':
612 $paramtype = PARAM_RAW;
613 break;
614 case 'email':
615 // We use PARAM_RAW to allow searches with %.
616 $paramtype = PARAM_RAW;
617 break;
618 case 'auth':
619 $paramtype = PARAM_AUTH;
620 break;
621 case 'lastname':
622 case 'firstname':
623 $paramtype = PARAM_TEXT;
624 break;
625 default:
626 // Send back a warning that this search key is not supported in this version.
627 // This warning will make the function extandable without breaking clients.
628 $warnings[] = array(
629 'item' => $criteria['key'],
630 'warningcode' => 'invalidfieldparameter',
631 'message' =>
632 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
634 // Do not add this invalid criteria to the created SQL request.
635 $invalidcriteria = true;
636 unset($params['criteria'][$criteriaindex]);
637 break;
640 if (!$invalidcriteria) {
641 $cleanedvalue = clean_param($criteria['value'], $paramtype);
643 $sql .= ' AND ';
645 // Create the SQL.
646 switch ($criteria['key']) {
647 case 'id':
648 case 'idnumber':
649 case 'username':
650 case 'auth':
651 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
652 $sqlparams[$criteria['key']] = $cleanedvalue;
653 break;
654 case 'email':
655 case 'lastname':
656 case 'firstname':
657 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
658 $sqlparams[$criteria['key']] = $cleanedvalue;
659 break;
660 default:
661 break;
666 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
668 // Finally retrieve each users information.
669 $returnedusers = array();
670 foreach ($users as $user) {
671 $userdetails = user_get_user_details_courses($user);
673 // Return the user only if all the searched fields are returned.
674 // Otherwise it means that the $USER was not allowed to search the returned user.
675 if (!empty($userdetails)) {
676 $validuser = true;
678 foreach ($params['criteria'] as $criteria) {
679 if (empty($userdetails[$criteria['key']])) {
680 $validuser = false;
684 if ($validuser) {
685 $returnedusers[] = $userdetails;
690 return array('users' => $returnedusers, 'warnings' => $warnings);
694 * Returns description of get_users result value.
696 * @return external_description
697 * @since Moodle 2.5
699 public static function get_users_returns() {
700 return new external_single_structure(
701 array('users' => new external_multiple_structure(
702 self::user_description()
704 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
710 * Returns description of method parameters
712 * @return external_function_parameters
713 * @since Moodle 2.2
714 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
715 * @see core_user_external::get_users_by_field_parameters()
717 public static function get_users_by_id_parameters() {
718 return new external_function_parameters(
719 array(
720 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
726 * Get user information
727 * - This function is matching the permissions of /user/profil.php
728 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
729 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
731 * @param array $userids array of user ids
732 * @return array An array of arrays describing users
733 * @since Moodle 2.2
734 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
735 * @see core_user_external::get_users_by_field()
737 public static function get_users_by_id($userids) {
738 global $CFG, $USER, $DB;
739 require_once($CFG->dirroot . "/user/lib.php");
741 $params = self::validate_parameters(self::get_users_by_id_parameters(),
742 array('userids' => $userids));
744 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
745 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
746 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
747 $params['contextlevel'] = CONTEXT_USER;
748 $usersql = "SELECT u.* $uselect
749 FROM {user} u $ujoin
750 WHERE u.id $sqluserids";
751 $users = $DB->get_recordset_sql($usersql, $params);
753 $result = array();
754 $hasuserupdatecap = has_capability('moodle/user:update', context_system::instance());
755 foreach ($users as $user) {
756 if (!empty($user->deleted)) {
757 continue;
759 context_helper::preload_from_record($user);
760 $usercontext = context_user::instance($user->id, IGNORE_MISSING);
761 self::validate_context($usercontext);
762 $currentuser = ($user->id == $USER->id);
764 if ($userarray = user_get_user_details($user)) {
765 // Fields matching permissions from /user/editadvanced.php.
766 if ($currentuser or $hasuserupdatecap) {
767 $userarray['auth'] = $user->auth;
768 $userarray['confirmed'] = $user->confirmed;
769 $userarray['idnumber'] = $user->idnumber;
770 $userarray['lang'] = $user->lang;
771 $userarray['theme'] = $user->theme;
772 $userarray['timezone'] = $user->timezone;
773 $userarray['mailformat'] = $user->mailformat;
775 $result[] = $userarray;
778 $users->close();
780 return $result;
784 * Returns description of method result value
786 * @return external_description
787 * @since Moodle 2.2
788 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
789 * @see core_user_external::get_users_by_field_returns()
791 public static function get_users_by_id_returns() {
792 $additionalfields = array (
793 'enrolledcourses' => new external_multiple_structure(
794 new external_single_structure(
795 array(
796 'id' => new external_value(PARAM_INT, 'Id of the course'),
797 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
798 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
800 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL));
801 return new external_multiple_structure(self::user_description($additionalfields));
805 * Returns description of method parameters
807 * @return external_function_parameters
808 * @since Moodle 2.2
810 public static function get_course_user_profiles_parameters() {
811 return new external_function_parameters(
812 array(
813 'userlist' => new external_multiple_structure(
814 new external_single_structure(
815 array(
816 'userid' => new external_value(PARAM_INT, 'userid'),
817 'courseid' => new external_value(PARAM_INT, 'courseid'),
826 * Get course participant's details
828 * @param array $userlist array of user ids and according course ids
829 * @return array An array of arrays describing course participants
830 * @since Moodle 2.2
832 public static function get_course_user_profiles($userlist) {
833 global $CFG, $USER, $DB;
834 require_once($CFG->dirroot . "/user/lib.php");
835 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
837 $userids = array();
838 $courseids = array();
839 foreach ($params['userlist'] as $value) {
840 $userids[] = $value['userid'];
841 $courseids[$value['userid']] = $value['courseid'];
844 // Cache all courses.
845 $courses = array();
846 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
847 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
848 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
849 $params['contextlevel'] = CONTEXT_COURSE;
850 $coursesql = "SELECT c.* $cselect
851 FROM {course} c $cjoin
852 WHERE c.id $sqlcourseids";
853 $rs = $DB->get_recordset_sql($coursesql, $params);
854 foreach ($rs as $course) {
855 // Adding course contexts to cache.
856 context_helper::preload_from_record($course);
857 // Cache courses.
858 $courses[$course->id] = $course;
860 $rs->close();
862 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
863 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
864 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
865 $params['contextlevel'] = CONTEXT_USER;
866 $usersql = "SELECT u.* $uselect
867 FROM {user} u $ujoin
868 WHERE u.id $sqluserids";
869 $users = $DB->get_recordset_sql($usersql, $params);
870 $result = array();
871 foreach ($users as $user) {
872 if (!empty($user->deleted)) {
873 continue;
875 context_helper::preload_from_record($user);
876 $course = $courses[$courseids[$user->id]];
877 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
878 self::validate_context($context);
879 if ($userarray = user_get_user_details($user, $course)) {
880 $result[] = $userarray;
884 $users->close();
886 return $result;
890 * Returns description of method result value
892 * @return external_description
893 * @since Moodle 2.2
895 public static function get_course_user_profiles_returns() {
896 $additionalfields = array(
897 'groups' => new external_multiple_structure(
898 new external_single_structure(
899 array(
900 'id' => new external_value(PARAM_INT, 'group id'),
901 'name' => new external_value(PARAM_RAW, 'group name'),
902 'description' => new external_value(PARAM_RAW, 'group description'),
903 'descriptionformat' => new external_format_value('description'),
905 ), 'user groups', VALUE_OPTIONAL),
906 'roles' => new external_multiple_structure(
907 new external_single_structure(
908 array(
909 'roleid' => new external_value(PARAM_INT, 'role id'),
910 'name' => new external_value(PARAM_RAW, 'role name'),
911 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
912 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
914 ), 'user roles', VALUE_OPTIONAL),
915 'enrolledcourses' => new external_multiple_structure(
916 new external_single_structure(
917 array(
918 'id' => new external_value(PARAM_INT, 'Id of the course'),
919 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
920 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
922 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
925 return new external_multiple_structure(self::user_description($additionalfields));
929 * Create user return value description.
931 * @param array $additionalfields some additional field
932 * @return single_structure_description
934 public static function user_description($additionalfields = array()) {
935 $userfields = array(
936 'id' => new external_value(PARAM_INT, 'ID of the user'),
937 'username' => new external_value(PARAM_RAW, 'The username', VALUE_OPTIONAL),
938 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
939 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
940 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
941 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
942 'address' => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL),
943 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
944 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
945 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
946 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
947 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
948 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
949 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
950 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
951 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
952 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
953 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
954 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
955 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
956 'auth' => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
957 'confirmed' => new external_value(PARAM_INT, 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
958 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
959 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
960 'theme' => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
961 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
962 'mailformat' => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
963 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
964 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
965 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
966 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
967 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
968 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
969 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
970 'customfields' => new external_multiple_structure(
971 new external_single_structure(
972 array(
973 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
974 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
975 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
976 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
978 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
979 'preferences' => new external_multiple_structure(
980 new external_single_structure(
981 array(
982 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
983 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
985 ), 'Users preferences', VALUE_OPTIONAL)
987 if (!empty($additionalfields)) {
988 $userfields = array_merge($userfields, $additionalfields);
990 return new external_single_structure($userfields);
994 * Returns description of method parameters
996 * @return external_function_parameters
997 * @since Moodle 2.6
999 public static function add_user_private_files_parameters() {
1000 return new external_function_parameters(
1001 array(
1002 'draftid' => new external_value(PARAM_INT, 'draft area id')
1008 * Copy files from a draft area to users private files area.
1010 * @throws invalid_parameter_exception
1011 * @param int $draftid Id of a draft area containing files.
1012 * @return array An array of warnings
1013 * @since Moodle 2.6
1015 public static function add_user_private_files($draftid) {
1016 global $CFG, $USER, $DB;
1018 require_once($CFG->dirroot . "/user/lib.php");
1019 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
1021 if (isguestuser()) {
1022 throw new invalid_parameter_exception('Guest users cannot upload files');
1025 $context = context_user::instance($USER->id);
1026 require_capability('moodle/user:manageownfiles', $context);
1028 $maxbytes = $CFG->userquota;
1029 $maxareabytes = $CFG->userquota;
1030 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1031 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1032 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1035 $options = array('subdirs' => 1,
1036 'maxbytes' => $maxbytes,
1037 'maxfiles' => -1,
1038 'accepted_types' => '*',
1039 'areamaxbytes' => $maxareabytes);
1041 file_save_draft_area_files($draftid, $context->id, 'user', 'private', 0, $options);
1043 return null;
1047 * Returns description of method result value
1049 * @return external_description
1050 * @since Moodle 2.2
1052 public static function add_user_private_files_returns() {
1053 return null;
1057 * Returns description of method parameters.
1059 * @return external_function_parameters
1060 * @since Moodle 2.6
1062 public static function add_user_device_parameters() {
1063 return new external_function_parameters(
1064 array(
1065 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1066 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1067 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1068 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1069 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1070 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1071 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1077 * Add a user device in Moodle database (for PUSH notifications usually).
1079 * @throws moodle_exception
1080 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1081 * @param string $name The device name, occam or iPhone etc.
1082 * @param string $model The device model Nexus4 or iPad1.1 etc.
1083 * @param string $platform The device platform iOs or Android etc.
1084 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1085 * @param string $pushid The device PUSH token/key/identifier/registration id.
1086 * @param string $uuid The device UUID.
1087 * @return array List of possible warnings.
1088 * @since Moodle 2.6
1090 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1091 global $CFG, $USER, $DB;
1092 require_once($CFG->dirroot . "/user/lib.php");
1094 $params = self::validate_parameters(self::add_user_device_parameters(),
1095 array('appid' => $appid,
1096 'name' => $name,
1097 'model' => $model,
1098 'platform' => $platform,
1099 'version' => $version,
1100 'pushid' => $pushid,
1101 'uuid' => $uuid
1104 $warnings = array();
1106 // Prevent duplicate keys for users.
1107 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1108 $warnings['warning'][] = array(
1109 'item' => $params['pushid'],
1110 'warningcode' => 'existingkeyforthisuser',
1111 'message' => 'This key is already stored for this user'
1113 return $warnings;
1116 // The same key can't exists for the same platform.
1117 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'platform' => $params['platform']))) {
1118 $warnings['warning'][] = array(
1119 'item' => $params['pushid'],
1120 'warningcode' => 'existingkeyforplatform',
1121 'message' => 'This key is already stored for other device using the same platform'
1123 return $warnings;
1126 $userdevice = new stdclass;
1127 $userdevice->userid = $USER->id;
1128 $userdevice->appid = $params['appid'];
1129 $userdevice->name = $params['name'];
1130 $userdevice->model = $params['model'];
1131 $userdevice->platform = $params['platform'];
1132 $userdevice->version = $params['version'];
1133 $userdevice->pushid = $params['pushid'];
1134 $userdevice->uuid = $params['uuid'];
1135 $userdevice->timecreated = time();
1136 $userdevice->timemodified = $userdevice->timecreated;
1138 if (!$DB->insert_record('user_devices', $userdevice)) {
1139 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1142 return $warnings;
1146 * Returns description of method result value.
1148 * @return external_multiple_structure
1149 * @since Moodle 2.6
1151 public static function add_user_device_returns() {
1152 return new external_multiple_structure(
1153 new external_warnings()
1160 * Deprecated user external functions
1162 * @package core_user
1163 * @copyright 2009 Petr Skodak
1164 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1165 * @since Moodle 2.0
1166 * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
1167 * @see core_user_external
1169 class moodle_user_external extends external_api {
1172 * Returns description of method parameters
1174 * @return external_function_parameters
1175 * @since Moodle 2.0
1176 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1177 * @see core_user_external::create_users_parameters()
1179 public static function create_users_parameters() {
1180 return core_user_external::create_users_parameters();
1184 * Create one or more users
1186 * @param array $users An array of users to create.
1187 * @return array An array of arrays
1188 * @since Moodle 2.0
1189 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1190 * @see core_user_external::create_users()
1192 public static function create_users($users) {
1193 return core_user_external::create_users($users);
1197 * Returns description of method result value
1199 * @return external_description
1200 * @since Moodle 2.0
1201 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1202 * @see core_user_external::create_users_returns()
1204 public static function create_users_returns() {
1205 return core_user_external::create_users_returns();
1210 * Returns description of method parameters
1212 * @return external_function_parameters
1213 * @since Moodle 2.0
1214 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1215 * @see core_user_external::delete_users_parameters()
1217 public static function delete_users_parameters() {
1218 return core_user_external::delete_users_parameters();
1222 * Delete users
1224 * @param array $userids
1225 * @return null
1226 * @since Moodle 2.0
1227 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1228 * @see core_user_external::delete_users()
1230 public static function delete_users($userids) {
1231 return core_user_external::delete_users($userids);
1235 * Returns description of method result value
1237 * @return null
1238 * @since Moodle 2.0
1239 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1240 * @see core_user_external::delete_users_returns()
1242 public static function delete_users_returns() {
1243 return core_user_external::delete_users_returns();
1248 * Returns description of method parameters
1250 * @return external_function_parameters
1251 * @since Moodle 2.0
1252 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1253 * @see core_user_external::update_users_parameters()
1255 public static function update_users_parameters() {
1256 return core_user_external::update_users_parameters();
1260 * Update users
1262 * @param array $users
1263 * @return null
1264 * @since Moodle 2.0
1265 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1266 * @see core_user_external::update_users()
1268 public static function update_users($users) {
1269 return core_user_external::update_users($users);
1273 * Returns description of method result value
1275 * @return null
1276 * @since Moodle 2.0
1277 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1278 * @see core_user_external::update_users_returns()
1280 public static function update_users_returns() {
1281 return core_user_external::update_users_returns();
1285 * Returns description of method parameters
1287 * @return external_function_parameters
1288 * @since Moodle 2.0
1289 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1290 * @see core_user_external::get_users_by_id_parameters()
1292 public static function get_users_by_id_parameters() {
1293 return core_user_external::get_users_by_id_parameters();
1297 * Get user information
1298 * - This function is matching the permissions of /user/profil.php
1299 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
1300 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
1302 * @param array $userids array of user ids
1303 * @return array An array of arrays describing users
1304 * @since Moodle 2.0
1305 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1306 * @see core_user_external::get_users_by_id()
1308 public static function get_users_by_id($userids) {
1309 return core_user_external::get_users_by_id($userids);
1313 * Returns description of method result value
1315 * @return external_description
1316 * @since Moodle 2.0
1317 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1318 * @see core_user_external::get_users_by_id_returns()
1320 public static function get_users_by_id_returns() {
1321 return core_user_external::get_users_by_id_returns();
1324 * Returns description of method parameters
1326 * @return external_function_parameters
1327 * @since Moodle 2.1
1328 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1329 * @see core_user_external::get_course_user_profiles_parameters()
1331 public static function get_course_participants_by_id_parameters() {
1332 return core_user_external::get_course_user_profiles_parameters();
1336 * Get course participant's details
1338 * @param array $userlist array of user ids and according course ids
1339 * @return array An array of arrays describing course participants
1340 * @since Moodle 2.1
1341 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1342 * @see core_user_external::get_course_user_profiles()
1344 public static function get_course_participants_by_id($userlist) {
1345 return core_user_external::get_course_user_profiles($userlist);
1349 * Returns description of method result value
1351 * @return external_description
1352 * @since Moodle 2.1
1353 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1354 * @see core_user_external::get_course_user_profiles_returns()
1356 public static function get_course_participants_by_id_returns() {
1357 return core_user_external::get_course_user_profiles_returns();
1361 * Returns description of method parameters
1363 * @return external_function_parameters
1364 * @since Moodle 2.1
1365 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1366 * @see core_enrol_external::get_enrolled_users_parameters()
1368 public static function get_users_by_courseid_parameters() {
1369 global $CFG;
1370 require_once($CFG->dirroot . '/enrol/externallib.php');
1371 return core_enrol_external::get_enrolled_users_parameters();
1375 * Get course participants details
1377 * @param int $courseid course id
1378 * @param array $options options {
1379 * 'name' => option name
1380 * 'value' => option value
1382 * @return array An array of users
1383 * @since Moodle 2.1
1384 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1385 * @see core_enrol_external::get_enrolled_users()
1387 public static function get_users_by_courseid($courseid, $options) {
1388 global $CFG;
1389 require_once($CFG->dirroot . '/enrol/externallib.php');
1390 return core_enrol_external::get_enrolled_users($courseid, $options);
1393 * Returns description of method result value
1395 * @return external_description
1396 * @since Moodle 2.1
1397 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1398 * @see core_enrol_external::get_enrolled_users_returns()
1400 public static function get_users_by_courseid_returns() {
1401 global $CFG;
1402 require_once($CFG->dirroot . '/enrol/externallib.php');
1403 return core_enrol_external::get_enrolled_users_returns();