Merge branch 'master_MDL-37714' of git://github.com/greg-or/moodle
[moodle.git] / user / externallib.php
blobae028aeac855ea754d359cd4bcb69c0935b7e625
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/>.
18 /**
19 * External user API
21 * @package core_user
22 * @category external
23 * @copyright 2009 Petr Skodak
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 require_once("$CFG->libdir/externallib.php");
29 /**
30 * User external functions
32 * @package core_user
33 * @category external
34 * @copyright 2011 Jerome Mouneyrac
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 * @since Moodle 2.2
38 class core_user_external extends external_api {
40 /**
41 * Returns description of method parameters
43 * @return external_function_parameters
44 * @since Moodle 2.2
46 public static function create_users_parameters() {
47 global $CFG;
49 return new external_function_parameters(
50 array(
51 'users' => new external_multiple_structure(
52 new external_single_structure(
53 array(
54 'username' => new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config.'),
55 'password' => new external_value(PARAM_RAW, 'Plain text password consisting of any characters'),
56 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
57 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user'),
58 'email' => new external_value(PARAM_EMAIL, 'A valid and unique email address'),
59 'auth' => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT, 'manual', NULL_NOT_ALLOWED),
60 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_DEFAULT, ''),
61 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_DEFAULT, $CFG->lang, NULL_NOT_ALLOWED),
62 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server', VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
63 'theme' => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
64 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
65 'mailformat' => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
66 'description' => new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
67 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
68 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
69 'firstnamephonetic' => new external_value(PARAM_NOTAGS, 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
70 'lastnamephonetic' => new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
71 'middlename' => new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
72 'alternatename' => new external_value(PARAM_NOTAGS, 'The alternate name of the user', VALUE_OPTIONAL),
73 'preferences' => new external_multiple_structure(
74 new external_single_structure(
75 array(
76 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
77 'value' => new external_value(PARAM_RAW, 'The value of the preference')
79 ), 'User preferences', VALUE_OPTIONAL),
80 'customfields' => new external_multiple_structure(
81 new external_single_structure(
82 array(
83 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
84 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
86 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
94 /**
95 * Create one or more users
97 * @param array $users An array of users to create.
98 * @return array An array of arrays
99 * @since Moodle 2.2
101 public static function create_users($users) {
102 global $CFG, $DB;
103 require_once($CFG->dirroot."/lib/weblib.php");
104 require_once($CFG->dirroot."/user/lib.php");
105 require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function
107 // Ensure the current user is allowed to run this function
108 $context = context_system::instance();
109 self::validate_context($context);
110 require_capability('moodle/user:create', $context);
112 // Do basic automatic PARAM checks on incoming data, using params description
113 // If any problems are found then exceptions are thrown with helpful error messages
114 $params = self::validate_parameters(self::create_users_parameters(), array('users'=>$users));
116 $availableauths = core_component::get_plugin_list('auth');
117 unset($availableauths['mnet']); // these would need mnethostid too
118 unset($availableauths['webservice']); // we do not want new webservice users for now
120 $availablethemes = core_component::get_plugin_list('theme');
121 $availablelangs = get_string_manager()->get_list_of_translations();
123 $transaction = $DB->start_delegated_transaction();
125 $userids = array();
126 foreach ($params['users'] as $user) {
127 // Make sure that the username doesn't already exist
128 if ($DB->record_exists('user', array('username'=>$user['username'], 'mnethostid'=>$CFG->mnet_localhost_id))) {
129 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
132 // Make sure auth is valid
133 if (empty($availableauths[$user['auth']])) {
134 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
137 // Make sure lang is valid
138 if (empty($availablelangs[$user['lang']])) {
139 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
142 // Make sure lang is valid
143 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { //theme is VALUE_OPTIONAL,
144 // so no default value.
145 // We need to test if the client sent it
146 // => !empty($user['theme'])
147 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
150 $user['confirmed'] = true;
151 $user['mnethostid'] = $CFG->mnet_localhost_id;
153 // Start of user info validation.
154 // Lets make sure we validate current user info as handled by current GUI. see user/editadvanced_form.php function validation()
155 if (!validate_email($user['email'])) {
156 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
157 } else if ($DB->record_exists('user', array('email'=>$user['email'], 'mnethostid'=>$user['mnethostid']))) {
158 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
160 // End of user info validation.
162 // create the user data now!
163 $user['id'] = user_create_user($user);
165 // custom fields
166 if(!empty($user['customfields'])) {
167 foreach($user['customfields'] as $customfield) {
168 $user["profile_field_".$customfield['type']] = $customfield['value']; //profile_save_data() saves profile file
169 //it's expecting a user with the correct id,
170 //and custom field to be named profile_field_"shortname"
172 profile_save_data((object) $user);
175 //preferences
176 if (!empty($user['preferences'])) {
177 foreach($user['preferences'] as $preference) {
178 set_user_preference($preference['type'], $preference['value'],$user['id']);
182 $userids[] = array('id'=>$user['id'], 'username'=>$user['username']);
185 $transaction->allow_commit();
187 return $userids;
191 * Returns description of method result value
193 * @return external_description
194 * @since Moodle 2.2
196 public static function create_users_returns() {
197 return new external_multiple_structure(
198 new external_single_structure(
199 array(
200 'id' => new external_value(PARAM_INT, 'user id'),
201 'username' => new external_value(PARAM_USERNAME, 'user name'),
209 * Returns description of method parameters
211 * @return external_function_parameters
212 * @since Moodle 2.2
214 public static function delete_users_parameters() {
215 return new external_function_parameters(
216 array(
217 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
223 * Delete users
225 * @param array $userids
226 * @return null
227 * @since Moodle 2.2
229 public static function delete_users($userids) {
230 global $CFG, $DB, $USER;
231 require_once($CFG->dirroot."/user/lib.php");
233 // Ensure the current user is allowed to run this function
234 $context = context_system::instance();
235 require_capability('moodle/user:delete', $context);
236 self::validate_context($context);
238 $params = self::validate_parameters(self::delete_users_parameters(), array('userids'=>$userids));
240 $transaction = $DB->start_delegated_transaction();
242 foreach ($params['userids'] as $userid) {
243 $user = $DB->get_record('user', array('id'=>$userid, 'deleted'=>0), '*', MUST_EXIST);
244 // must not allow deleting of admins or self!!!
245 if (is_siteadmin($user)) {
246 throw new moodle_exception('useradminodelete', 'error');
248 if ($USER->id == $user->id) {
249 throw new moodle_exception('usernotdeletederror', 'error');
251 user_delete_user($user);
254 $transaction->allow_commit();
256 return null;
260 * Returns description of method result value
262 * @return null
263 * @since Moodle 2.2
265 public static function delete_users_returns() {
266 return null;
271 * Returns description of method parameters
273 * @return external_function_parameters
274 * @since Moodle 2.2
276 public static function update_users_parameters() {
277 return new external_function_parameters(
278 array(
279 'users' => new external_multiple_structure(
280 new external_single_structure(
281 array(
282 'id' => new external_value(PARAM_INT, 'ID of the user'),
283 'username' => new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config.', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
284 'password' => new external_value(PARAM_RAW, 'Plain text password consisting of any characters', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
285 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
286 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
287 'email' => new external_value(PARAM_EMAIL, 'A valid and unique email address', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
288 'auth' => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
289 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
290 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
291 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
292 'theme' => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
293 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
294 'mailformat' => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
295 'description' => new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
296 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
297 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
298 'firstnamephonetic' => new external_value(PARAM_NOTAGS, 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
299 'lastnamephonetic' => new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
300 'middlename' => new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
301 'alternatename' => new external_value(PARAM_NOTAGS, 'The alternate name of the user', VALUE_OPTIONAL),
302 'customfields' => new external_multiple_structure(
303 new external_single_structure(
304 array(
305 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
306 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
308 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
309 'preferences' => new external_multiple_structure(
310 new external_single_structure(
311 array(
312 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
313 'value' => new external_value(PARAM_RAW, 'The value of the preference')
315 ), 'User preferences', VALUE_OPTIONAL),
324 * Update users
326 * @param array $users
327 * @return null
328 * @since Moodle 2.2
330 public static function update_users($users) {
331 global $CFG, $DB;
332 require_once($CFG->dirroot."/user/lib.php");
333 require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function
335 // Ensure the current user is allowed to run this function
336 $context = context_system::instance();
337 require_capability('moodle/user:update', $context);
338 self::validate_context($context);
340 $params = self::validate_parameters(self::update_users_parameters(), array('users'=>$users));
342 $transaction = $DB->start_delegated_transaction();
344 foreach ($params['users'] as $user) {
345 user_update_user($user);
346 //update user custom fields
347 if(!empty($user['customfields'])) {
349 foreach($user['customfields'] as $customfield) {
350 $user["profile_field_".$customfield['type']] = $customfield['value']; //profile_save_data() saves profile file
351 //it's expecting a user with the correct id,
352 //and custom field to be named profile_field_"shortname"
354 profile_save_data((object) $user);
357 //preferences
358 if (!empty($user['preferences'])) {
359 foreach($user['preferences'] as $preference) {
360 set_user_preference($preference['type'], $preference['value'],$user['id']);
365 $transaction->allow_commit();
367 return null;
371 * Returns description of method result value
373 * @return null
374 * @since Moodle 2.2
376 public static function update_users_returns() {
377 return null;
381 * Returns description of method parameters
383 * @return external_function_parameters
384 * @since Moodle 2.4
386 public static function get_users_by_field_parameters() {
387 return new external_function_parameters(
388 array(
389 'field' => new external_value(PARAM_ALPHA, 'the search field can be
390 \'id\' or \'idnumber\' or \'username\' or \'email\''),
391 'values' => new external_multiple_structure(
392 new external_value(PARAM_RAW, 'the value to match'))
398 * Get user information for a unique field.
400 * @param string $field
401 * @param array $values
402 * @return array An array of arrays containg user profiles.
403 * @since Moodle 2.4
405 public static function get_users_by_field($field, $values) {
406 global $CFG, $USER, $DB;
407 require_once($CFG->dirroot . "/user/lib.php");
409 $params = self::validate_parameters(self::get_users_by_field_parameters(),
410 array('field' => $field, 'values' => $values));
412 // This array will keep all the users that are allowed to be searched,
413 // according to the current user's privileges.
414 $cleanedvalues = array();
416 switch ($field) {
417 case 'id':
418 $paramtype = PARAM_INT;
419 break;
420 case 'idnumber':
421 $paramtype = PARAM_RAW;
422 break;
423 case 'username':
424 $paramtype = PARAM_RAW;
425 break;
426 case 'email':
427 $paramtype = PARAM_EMAIL;
428 break;
429 default:
430 throw new coding_exception('invalid field parameter',
431 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
434 // Clean the values
435 foreach ($values as $value) {
436 $cleanedvalue = clean_param($value, $paramtype);
437 if ( $value != $cleanedvalue) {
438 throw new invalid_parameter_exception('The field \'' . $field .
439 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
441 $cleanedvalues[] = $cleanedvalue;
444 // Retrieve the users
445 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
447 // Finally retrieve each users information
448 $returnedusers = array();
449 foreach ($users as $user) {
450 $userdetails = user_get_user_details_courses($user);
452 // Return the user only if the searched field is returned
453 // Otherwise it means that the $USER was not allowed to search the returned user
454 if (!empty($userdetails) and !empty($userdetails[$field])) {
455 $returnedusers[] = $userdetails;
459 return $returnedusers;
463 * Returns description of method result value
465 * @return external_multiple_structure
466 * @since Moodle 2.4
468 public static function get_users_by_field_returns() {
469 return new external_multiple_structure(self::user_description());
474 * Returns description of get_users() parameters.
476 * @return external_function_parameters
477 * @since Moodle 2.5
479 public static function get_users_parameters() {
480 return new external_function_parameters(
481 array(
482 'criteria' => new external_multiple_structure(
483 new external_single_structure(
484 array(
485 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
486 "id" (int) matching user id,
487 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
488 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
489 "idnumber" (string) matching user idnumber,
490 "username" (string) matching user username,
491 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
492 "auth" (string) matching user auth plugin'),
493 'value' => new external_value(PARAM_RAW, 'the value to search')
495 ), 'the key/value pairs to be considered in user search. Values can not be empty.
496 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
497 key occurences are forbidden.
498 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
499 the search is still executed on the valid criterias.
500 You can search without criteria, but the function is not designed for it.
501 It could very slow or timeout. The function is designed to search some specific users.'
508 * Retrieve matching user.
510 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
511 * @return array An array of arrays containing user profiles.
512 * @since Moodle 2.5
514 public static function get_users($criteria = array()) {
515 global $CFG, $USER, $DB;
517 require_once($CFG->dirroot . "/user/lib.php");
519 $params = self::validate_parameters(self::get_users_parameters(),
520 array('criteria' => $criteria));
522 // Validate the criteria and retrieve the users.
523 $users = array();
524 $warnings = array();
525 $sqlparams = array();
526 $usedkeys = array();
528 // Do not retrieve deleted users.
529 $sql = ' deleted = 0';
531 foreach ($params['criteria'] as $criteriaindex => $criteria) {
533 // Check that the criteria has never been used.
534 if (array_key_exists($criteria['key'], $usedkeys)) {
535 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
536 } else {
537 $usedkeys[$criteria['key']] = true;
540 $invalidcriteria = false;
541 // Clean the parameters.
542 $paramtype = PARAM_RAW;
543 switch ($criteria['key']) {
544 case 'id':
545 $paramtype = PARAM_INT;
546 break;
547 case 'idnumber':
548 $paramtype = PARAM_RAW;
549 break;
550 case 'username':
551 $paramtype = PARAM_RAW;
552 break;
553 case 'email':
554 // We use PARAM_RAW to allow searches with %.
555 $paramtype = PARAM_RAW;
556 break;
557 case 'auth':
558 $paramtype = PARAM_AUTH;
559 break;
560 case 'lastname':
561 case 'firstname':
562 $paramtype = PARAM_TEXT;
563 break;
564 default:
565 // Send back a warning that this search key is not supported in this version.
566 // This warning will make the function extandable without breaking clients.
567 $warnings[] = array(
568 'item' => $criteria['key'],
569 'warningcode' => 'invalidfieldparameter',
570 'message' => 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
572 // Do not add this invalid criteria to the created SQL request.
573 $invalidcriteria = true;
574 unset($params['criteria'][$criteriaindex]);
575 break;
578 if (!$invalidcriteria) {
579 $cleanedvalue = clean_param($criteria['value'], $paramtype);
581 $sql .= ' AND ';
583 // Create the SQL.
584 switch ($criteria['key']) {
585 case 'id':
586 case 'idnumber':
587 case 'username':
588 case 'auth':
589 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
590 $sqlparams[$criteria['key']] = $cleanedvalue;
591 break;
592 case 'email':
593 case 'lastname':
594 case 'firstname':
595 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
596 $sqlparams[$criteria['key']] = $cleanedvalue;
597 break;
598 default:
599 break;
604 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
606 // Finally retrieve each users information.
607 $returnedusers = array();
608 foreach ($users as $user) {
609 $userdetails = user_get_user_details_courses($user);
611 // Return the user only if all the searched fields are returned.
612 // Otherwise it means that the $USER was not allowed to search the returned user.
613 if (!empty($userdetails)) {
614 $validuser = true;
616 foreach($params['criteria'] as $criteria) {
617 if (empty($userdetails[$criteria['key']])) {
618 $validuser = false;
622 if ($validuser) {
623 $returnedusers[] = $userdetails;
628 return array('users' => $returnedusers, 'warnings' => $warnings);
632 * Returns description of get_users result value.
634 * @return external_description
635 * @since Moodle 2.5
637 public static function get_users_returns() {
638 return new external_single_structure(
639 array('users' => new external_multiple_structure(
640 self::user_description()
642 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
648 * Returns description of method parameters
650 * @return external_function_parameters
651 * @since Moodle 2.2
652 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
653 * @see core_user_external::get_users_by_field_parameters()
655 public static function get_users_by_id_parameters() {
656 return new external_function_parameters(
657 array(
658 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
664 * Get user information
665 * - This function is matching the permissions of /user/profil.php
666 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
667 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
669 * @param array $userids array of user ids
670 * @return array An array of arrays describing users
671 * @since Moodle 2.2
672 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
673 * @see core_user_external::get_users_by_field()
675 public static function get_users_by_id($userids) {
676 global $CFG, $USER, $DB;
677 require_once($CFG->dirroot . "/user/lib.php");
679 $params = self::validate_parameters(self::get_users_by_id_parameters(),
680 array('userids'=>$userids));
682 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
683 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
684 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
685 $params['contextlevel'] = CONTEXT_USER;
686 $usersql = "SELECT u.* $uselect
687 FROM {user} u $ujoin
688 WHERE u.id $sqluserids";
689 $users = $DB->get_recordset_sql($usersql, $params);
691 $result = array();
692 $hasuserupdatecap = has_capability('moodle/user:update', context_system::instance());
693 foreach ($users as $user) {
694 if (!empty($user->deleted)) {
695 continue;
697 context_helper::preload_from_record($user);
698 $usercontext = context_user::instance($user->id, IGNORE_MISSING);
699 self::validate_context($usercontext);
700 $currentuser = ($user->id == $USER->id);
702 if ($userarray = user_get_user_details($user)) {
703 //fields matching permissions from /user/editadvanced.php
704 if ($currentuser or $hasuserupdatecap) {
705 $userarray['auth'] = $user->auth;
706 $userarray['confirmed'] = $user->confirmed;
707 $userarray['idnumber'] = $user->idnumber;
708 $userarray['lang'] = $user->lang;
709 $userarray['theme'] = $user->theme;
710 $userarray['timezone'] = $user->timezone;
711 $userarray['mailformat'] = $user->mailformat;
713 $result[] = $userarray;
716 $users->close();
718 return $result;
722 * Returns description of method result value
724 * @return external_description
725 * @since Moodle 2.2
726 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
727 * @see core_user_external::get_users_by_field_returns()
729 public static function get_users_by_id_returns() {
730 $additionalfields = array (
731 'enrolledcourses' => new external_multiple_structure(
732 new external_single_structure(
733 array(
734 'id' => new external_value(PARAM_INT, 'Id of the course'),
735 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
736 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
738 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL));
739 return new external_multiple_structure(self::user_description($additionalfields));
743 * Returns description of method parameters
745 * @return external_function_parameters
746 * @since Moodle 2.2
748 public static function get_course_user_profiles_parameters() {
749 return new external_function_parameters(
750 array(
751 'userlist' => new external_multiple_structure(
752 new external_single_structure(
753 array(
754 'userid' => new external_value(PARAM_INT, 'userid'),
755 'courseid' => new external_value(PARAM_INT, 'courseid'),
764 * Get course participant's details
766 * @param array $userlist array of user ids and according course ids
767 * @return array An array of arrays describing course participants
768 * @since Moodle 2.2
770 public static function get_course_user_profiles($userlist) {
771 global $CFG, $USER, $DB;
772 require_once($CFG->dirroot . "/user/lib.php");
773 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist'=>$userlist));
775 $userids = array();
776 $courseids = array();
777 foreach ($params['userlist'] as $value) {
778 $userids[] = $value['userid'];
779 $courseids[$value['userid']] = $value['courseid'];
782 // cache all courses
783 $courses = array();
784 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
785 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
786 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
787 $params['contextlevel'] = CONTEXT_COURSE;
788 $coursesql = "SELECT c.* $cselect
789 FROM {course} c $cjoin
790 WHERE c.id $sqlcourseids";
791 $rs = $DB->get_recordset_sql($coursesql, $params);
792 foreach ($rs as $course) {
793 // adding course contexts to cache
794 context_helper::preload_from_record($course);
795 // cache courses
796 $courses[$course->id] = $course;
798 $rs->close();
800 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
801 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
802 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
803 $params['contextlevel'] = CONTEXT_USER;
804 $usersql = "SELECT u.* $uselect
805 FROM {user} u $ujoin
806 WHERE u.id $sqluserids";
807 $users = $DB->get_recordset_sql($usersql, $params);
808 $result = array();
809 foreach ($users as $user) {
810 if (!empty($user->deleted)) {
811 continue;
813 context_helper::preload_from_record($user);
814 $course = $courses[$courseids[$user->id]];
815 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
816 self::validate_context($context);
817 if ($userarray = user_get_user_details($user, $course)) {
818 $result[] = $userarray;
822 $users->close();
824 return $result;
828 * Returns description of method result value
830 * @return external_description
831 * @since Moodle 2.2
833 public static function get_course_user_profiles_returns() {
834 $additionalfields = array(
835 'groups' => new external_multiple_structure(
836 new external_single_structure(
837 array(
838 'id' => new external_value(PARAM_INT, 'group id'),
839 'name' => new external_value(PARAM_RAW, 'group name'),
840 'description' => new external_value(PARAM_RAW, 'group description'),
841 'descriptionformat' => new external_format_value('description'),
843 ), 'user groups', VALUE_OPTIONAL),
844 'roles' => new external_multiple_structure(
845 new external_single_structure(
846 array(
847 'roleid' => new external_value(PARAM_INT, 'role id'),
848 'name' => new external_value(PARAM_RAW, 'role name'),
849 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
850 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
852 ), 'user roles', VALUE_OPTIONAL),
853 'enrolledcourses' => new external_multiple_structure(
854 new external_single_structure(
855 array(
856 'id' => new external_value(PARAM_INT, 'Id of the course'),
857 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
858 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
860 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
863 return new external_multiple_structure(self::user_description($additionalfields));
867 * Create user return value description.
869 * @param array $additionalfields some additional field
870 * @return single_structure_description
872 public static function user_description($additionalfields = array()) {
873 $userfields = array(
874 'id' => new external_value(PARAM_INT, 'ID of the user'),
875 'username' => new external_value(PARAM_RAW, 'The username', VALUE_OPTIONAL),
876 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
877 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
878 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
879 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
880 'address' => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL),
881 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
882 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
883 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
884 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
885 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
886 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
887 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
888 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
889 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
890 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
891 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
892 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
893 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
894 'auth' => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
895 'confirmed' => new external_value(PARAM_INT, 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
896 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
897 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
898 'theme' => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
899 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
900 'mailformat' => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
901 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
902 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
903 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
904 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
905 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
906 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
907 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
908 'customfields' => new external_multiple_structure(
909 new external_single_structure(
910 array(
911 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
912 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
913 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
914 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
916 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
917 'preferences' => new external_multiple_structure(
918 new external_single_structure(
919 array(
920 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
921 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
923 ), 'Users preferences', VALUE_OPTIONAL)
925 if (!empty($additionalfields)) {
926 $userfields = array_merge($userfields, $additionalfields);
928 return new external_single_structure($userfields);
932 * Returns description of method parameters
934 * @return external_function_parameters
935 * @since Moodle 2.6
937 public static function add_user_private_files_parameters() {
938 return new external_function_parameters(
939 array(
940 'draftid' => new external_value(PARAM_INT, 'draft area id')
946 * Copy files from a draft area to users private files area.
948 * @param int $draftid Id of a draft area containing files.
949 * @return array An array of warnings
950 * @since Moodle 2.6
952 public static function add_user_private_files($draftid) {
953 global $CFG, $USER, $DB;
955 require_once($CFG->dirroot . "/user/lib.php");
956 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid'=>$draftid));
958 if (isguestuser()) {
959 throw new invalid_parameter_exception('Guest users cannot upload files');
962 $context = context_user::instance($USER->id);
963 require_capability('moodle/user:manageownfiles', $context);
965 $maxbytes = $CFG->userquota;
966 $maxareabytes = $CFG->userquota;
967 if (has_capability('moodle/user:ignoreuserquota', $context)) {
968 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
969 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
972 $options = array('subdirs' => 1,
973 'maxbytes' => $maxbytes,
974 'maxfiles' => -1,
975 'accepted_types' => '*',
976 'areamaxbytes' => $maxareabytes);
978 file_save_draft_area_files($draftid, $context->id, 'user', 'private', 0, $options);
980 return null;
984 * Returns description of method result value
986 * @return external_description
987 * @since Moodle 2.2
989 public static function add_user_private_files_returns() {
990 return null;
994 * Returns description of method parameters.
996 * @return external_function_parameters
997 * @since Moodle 2.6
999 public static function add_user_device_parameters() {
1000 return new external_function_parameters(
1001 array(
1002 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1003 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1004 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1005 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1006 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1007 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1008 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1014 * Add a user device in Moodle database (for PUSH notifications usually).
1016 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1017 * @param string $name The device name, occam or iPhone etc.
1018 * @param string $model The device model Nexus4 or iPad1.1 etc.
1019 * @param string $platform The device platform iOs or Android etc.
1020 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1021 * @param string $pushid The device PUSH token/key/identifier/registration id.
1022 * @param string $uuid The device UUID.
1023 * @return array List of possible warnings.
1024 * @since Moodle 2.6
1026 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1027 global $CFG, $USER, $DB;
1028 require_once($CFG->dirroot . "/user/lib.php");
1030 $params = self::validate_parameters(self::add_user_device_parameters(),
1031 array('appid' => $appid,
1032 'name' => $name,
1033 'model' => $model,
1034 'platform' => $platform,
1035 'version' => $version,
1036 'pushid' => $pushid,
1037 'uuid' => $uuid
1040 $warnings = array();
1042 // Prevent duplicate keys for users.
1043 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1044 $warnings['warning'][] = array(
1045 'item' => $params['pushid'],
1046 'warningcode' => 'existingkeyforthisuser',
1047 'message' => 'This key is already stored for this user'
1049 return $warnings;
1052 // The same key can't exists for the same platform.
1053 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'platform' => $params['platform']))) {
1054 $warnings['warning'][] = array(
1055 'item' => $params['pushid'],
1056 'warningcode' => 'existingkeyforplatform',
1057 'message' => 'This key is already stored for other device using the same platform'
1059 return $warnings;
1062 $userdevice = new stdclass;
1063 $userdevice->userid = $USER->id;
1064 $userdevice->appid = $params['appid'];
1065 $userdevice->name = $params['name'];
1066 $userdevice->model = $params['model'];
1067 $userdevice->platform = $params['platform'];
1068 $userdevice->version = $params['version'];
1069 $userdevice->pushid = $params['pushid'];
1070 $userdevice->uuid = $params['uuid'];
1071 $userdevice->timecreated = time();
1072 $userdevice->timemodified = $userdevice->timecreated;
1074 if (!$DB->insert_record('user_devices', $userdevice)) {
1075 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1078 return $warnings;
1082 * Returns description of method result value.
1084 * @return external_multiple_structure
1085 * @since Moodle 2.6
1087 public static function add_user_device_returns() {
1088 return new external_multiple_structure(
1089 new external_warnings()
1096 * Deprecated user external functions
1098 * @package core_user
1099 * @copyright 2009 Petr Skodak
1100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1101 * @since Moodle 2.0
1102 * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
1103 * @see core_user_external
1105 class moodle_user_external extends external_api {
1108 * Returns description of method parameters
1110 * @return external_function_parameters
1111 * @since Moodle 2.0
1112 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1113 * @see core_user_external::create_users_parameters()
1115 public static function create_users_parameters() {
1116 return core_user_external::create_users_parameters();
1120 * Create one or more users
1122 * @param array $users An array of users to create.
1123 * @return array An array of arrays
1124 * @since Moodle 2.0
1125 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1126 * @see core_user_external::create_users()
1128 public static function create_users($users) {
1129 return core_user_external::create_users($users);
1133 * Returns description of method result value
1135 * @return external_description
1136 * @since Moodle 2.0
1137 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1138 * @see core_user_external::create_users_returns()
1140 public static function create_users_returns() {
1141 return core_user_external::create_users_returns();
1146 * Returns description of method parameters
1148 * @return external_function_parameters
1149 * @since Moodle 2.0
1150 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1151 * @see core_user_external::delete_users_parameters()
1153 public static function delete_users_parameters() {
1154 return core_user_external::delete_users_parameters();
1158 * Delete users
1160 * @param array $userids
1161 * @return null
1162 * @since Moodle 2.0
1163 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1164 * @see core_user_external::delete_users()
1166 public static function delete_users($userids) {
1167 return core_user_external::delete_users($userids);
1171 * Returns description of method result value
1173 * @return null
1174 * @since Moodle 2.0
1175 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1176 * @see core_user_external::delete_users_returns()
1178 public static function delete_users_returns() {
1179 return core_user_external::delete_users_returns();
1184 * Returns description of method parameters
1186 * @return external_function_parameters
1187 * @since Moodle 2.0
1188 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1189 * @see core_user_external::update_users_parameters()
1191 public static function update_users_parameters() {
1192 return core_user_external::update_users_parameters();
1196 * Update users
1198 * @param array $users
1199 * @return null
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::update_users()
1204 public static function update_users($users) {
1205 return core_user_external::update_users($users);
1209 * Returns description of method result value
1211 * @return null
1212 * @since Moodle 2.0
1213 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1214 * @see core_user_external::update_users_returns()
1216 public static function update_users_returns() {
1217 return core_user_external::update_users_returns();
1221 * Returns description of method parameters
1223 * @return external_function_parameters
1224 * @since Moodle 2.0
1225 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1226 * @see core_user_external::get_users_by_id_parameters()
1228 public static function get_users_by_id_parameters() {
1229 return core_user_external::get_users_by_id_parameters();
1233 * Get user information
1234 * - This function is matching the permissions of /user/profil.php
1235 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
1236 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
1238 * @param array $userids array of user ids
1239 * @return array An array of arrays describing users
1240 * @since Moodle 2.0
1241 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1242 * @see core_user_external::get_users_by_id()
1244 public static function get_users_by_id($userids) {
1245 return core_user_external::get_users_by_id($userids);
1249 * Returns description of method result value
1251 * @return external_description
1252 * @since Moodle 2.0
1253 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1254 * @see core_user_external::get_users_by_id_returns()
1256 public static function get_users_by_id_returns() {
1257 return core_user_external::get_users_by_id_returns();
1260 * Returns description of method parameters
1262 * @return external_function_parameters
1263 * @since Moodle 2.1
1264 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1265 * @see core_user_external::get_course_user_profiles_parameters()
1267 public static function get_course_participants_by_id_parameters() {
1268 return core_user_external::get_course_user_profiles_parameters();
1272 * Get course participant's details
1274 * @param array $userlist array of user ids and according course ids
1275 * @return array An array of arrays describing course participants
1276 * @since Moodle 2.1
1277 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1278 * @see core_user_external::get_course_user_profiles()
1280 public static function get_course_participants_by_id($userlist) {
1281 return core_user_external::get_course_user_profiles($userlist);
1285 * Returns description of method result value
1287 * @return external_description
1288 * @since Moodle 2.1
1289 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1290 * @see core_user_external::get_course_user_profiles_returns()
1292 public static function get_course_participants_by_id_returns() {
1293 return core_user_external::get_course_user_profiles_returns();
1297 * Returns description of method parameters
1299 * @return external_function_parameters
1300 * @since Moodle 2.1
1301 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1302 * @see core_enrol_external::get_enrolled_users_parameters()
1304 public static function get_users_by_courseid_parameters() {
1305 global $CFG;
1306 require_once($CFG->dirroot . '/enrol/externallib.php');
1307 return core_enrol_external::get_enrolled_users_parameters();
1311 * Get course participants details
1313 * @param int $courseid course id
1314 * @param array $options options {
1315 * 'name' => option name
1316 * 'value' => option value
1318 * @return array An array of users
1319 * @since Moodle 2.1
1320 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1321 * @see core_enrol_external::get_enrolled_users()
1323 public static function get_users_by_courseid($courseid, $options) {
1324 global $CFG;
1325 require_once($CFG->dirroot . '/enrol/externallib.php');
1326 return core_enrol_external::get_enrolled_users($courseid, $options);
1329 * Returns description of method result value
1331 * @return external_description
1332 * @since Moodle 2.1
1333 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1334 * @see core_enrol_external::get_enrolled_users_returns()
1336 public static function get_users_by_courseid_returns() {
1337 global $CFG;
1338 require_once($CFG->dirroot . '/enrol/externallib.php');
1339 return core_enrol_external::get_enrolled_users_returns();