Merge branch 'MDL-43911-26' of git://github.com/andrewnicols/moodle into MOODLE_26_STABLE
[moodle.git] / user / externallib.php
blob6cc2e04a6ddd287da069d3c6e71fd88205550ebe
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 'theme' => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
63 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
64 'mailformat' => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
65 'description' => new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
66 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
67 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
68 'firstnamephonetic' => new external_value(PARAM_NOTAGS, 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
69 'lastnamephonetic' => new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
70 'middlename' => new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
71 'alternatename' => new external_value(PARAM_NOTAGS, 'The alternate name of the user', VALUE_OPTIONAL),
72 'preferences' => new external_multiple_structure(
73 new external_single_structure(
74 array(
75 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
76 'value' => new external_value(PARAM_RAW, 'The value of the preference')
78 ), 'User preferences', VALUE_OPTIONAL),
79 'customfields' => new external_multiple_structure(
80 new external_single_structure(
81 array(
82 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
83 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
85 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
93 /**
94 * Create one or more users
96 * @param array $users An array of users to create.
97 * @return array An array of arrays
98 * @since Moodle 2.2
100 public static function create_users($users) {
101 global $CFG, $DB;
102 require_once($CFG->dirroot."/lib/weblib.php");
103 require_once($CFG->dirroot."/user/lib.php");
104 require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function
106 // Ensure the current user is allowed to run this function
107 $context = context_system::instance();
108 self::validate_context($context);
109 require_capability('moodle/user:create', $context);
111 // Do basic automatic PARAM checks on incoming data, using params description
112 // If any problems are found then exceptions are thrown with helpful error messages
113 $params = self::validate_parameters(self::create_users_parameters(), array('users'=>$users));
115 $availableauths = core_component::get_plugin_list('auth');
116 unset($availableauths['mnet']); // these would need mnethostid too
117 unset($availableauths['webservice']); // we do not want new webservice users for now
119 $availablethemes = core_component::get_plugin_list('theme');
120 $availablelangs = get_string_manager()->get_list_of_translations();
122 $transaction = $DB->start_delegated_transaction();
124 $userids = array();
125 foreach ($params['users'] as $user) {
126 // Make sure that the username doesn't already exist
127 if ($DB->record_exists('user', array('username'=>$user['username'], 'mnethostid'=>$CFG->mnet_localhost_id))) {
128 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
131 // Make sure auth is valid
132 if (empty($availableauths[$user['auth']])) {
133 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
136 // Make sure lang is valid
137 if (empty($availablelangs[$user['lang']])) {
138 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
141 // Make sure lang is valid
142 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { //theme is VALUE_OPTIONAL,
143 // so no default value.
144 // We need to test if the client sent it
145 // => !empty($user['theme'])
146 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
149 $user['confirmed'] = true;
150 $user['mnethostid'] = $CFG->mnet_localhost_id;
152 // Start of user info validation.
153 // Lets make sure we validate current user info as handled by current GUI. see user/editadvanced_form.php function validation()
154 if (!validate_email($user['email'])) {
155 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
156 } else if ($DB->record_exists('user', array('email'=>$user['email'], 'mnethostid'=>$user['mnethostid']))) {
157 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
159 // End of user info validation.
161 // create the user data now!
162 $user['id'] = user_create_user($user);
164 // custom fields
165 if(!empty($user['customfields'])) {
166 foreach($user['customfields'] as $customfield) {
167 $user["profile_field_".$customfield['type']] = $customfield['value']; //profile_save_data() saves profile file
168 //it's expecting a user with the correct id,
169 //and custom field to be named profile_field_"shortname"
171 profile_save_data((object) $user);
174 //preferences
175 if (!empty($user['preferences'])) {
176 foreach($user['preferences'] as $preference) {
177 set_user_preference($preference['type'], $preference['value'],$user['id']);
181 $userids[] = array('id'=>$user['id'], 'username'=>$user['username']);
184 $transaction->allow_commit();
186 return $userids;
190 * Returns description of method result value
192 * @return external_description
193 * @since Moodle 2.2
195 public static function create_users_returns() {
196 return new external_multiple_structure(
197 new external_single_structure(
198 array(
199 'id' => new external_value(PARAM_INT, 'user id'),
200 'username' => new external_value(PARAM_USERNAME, 'user name'),
208 * Returns description of method parameters
210 * @return external_function_parameters
211 * @since Moodle 2.2
213 public static function delete_users_parameters() {
214 return new external_function_parameters(
215 array(
216 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
222 * Delete users
224 * @param array $userids
225 * @return null
226 * @since Moodle 2.2
228 public static function delete_users($userids) {
229 global $CFG, $DB, $USER;
230 require_once($CFG->dirroot."/user/lib.php");
232 // Ensure the current user is allowed to run this function
233 $context = context_system::instance();
234 require_capability('moodle/user:delete', $context);
235 self::validate_context($context);
237 $params = self::validate_parameters(self::delete_users_parameters(), array('userids'=>$userids));
239 $transaction = $DB->start_delegated_transaction();
241 foreach ($params['userids'] as $userid) {
242 $user = $DB->get_record('user', array('id'=>$userid, 'deleted'=>0), '*', MUST_EXIST);
243 // must not allow deleting of admins or self!!!
244 if (is_siteadmin($user)) {
245 throw new moodle_exception('useradminodelete', 'error');
247 if ($USER->id == $user->id) {
248 throw new moodle_exception('usernotdeletederror', 'error');
250 user_delete_user($user);
253 $transaction->allow_commit();
255 return null;
259 * Returns description of method result value
261 * @return null
262 * @since Moodle 2.2
264 public static function delete_users_returns() {
265 return null;
270 * Returns description of method parameters
272 * @return external_function_parameters
273 * @since Moodle 2.2
275 public static function update_users_parameters() {
276 global $CFG;
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 'theme' => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
292 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
293 'mailformat' => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
294 'description' => new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
295 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
296 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
297 'firstnamephonetic' => new external_value(PARAM_NOTAGS, 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
298 'lastnamephonetic' => new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
299 'middlename' => new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
300 'alternatename' => new external_value(PARAM_NOTAGS, 'The alternate name of the user', VALUE_OPTIONAL),
301 'customfields' => new external_multiple_structure(
302 new external_single_structure(
303 array(
304 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
305 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
307 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
308 'preferences' => new external_multiple_structure(
309 new external_single_structure(
310 array(
311 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
312 'value' => new external_value(PARAM_RAW, 'The value of the preference')
314 ), 'User preferences', VALUE_OPTIONAL),
323 * Update users
325 * @param array $users
326 * @return null
327 * @since Moodle 2.2
329 public static function update_users($users) {
330 global $CFG, $DB;
331 require_once($CFG->dirroot."/user/lib.php");
332 require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function
334 // Ensure the current user is allowed to run this function
335 $context = context_system::instance();
336 require_capability('moodle/user:update', $context);
337 self::validate_context($context);
339 $params = self::validate_parameters(self::update_users_parameters(), array('users'=>$users));
341 $transaction = $DB->start_delegated_transaction();
343 foreach ($params['users'] as $user) {
344 user_update_user($user);
345 //update user custom fields
346 if(!empty($user['customfields'])) {
348 foreach($user['customfields'] as $customfield) {
349 $user["profile_field_".$customfield['type']] = $customfield['value']; //profile_save_data() saves profile file
350 //it's expecting a user with the correct id,
351 //and custom field to be named profile_field_"shortname"
353 profile_save_data((object) $user);
356 //preferences
357 if (!empty($user['preferences'])) {
358 foreach($user['preferences'] as $preference) {
359 set_user_preference($preference['type'], $preference['value'],$user['id']);
364 $transaction->allow_commit();
366 return null;
370 * Returns description of method result value
372 * @return null
373 * @since Moodle 2.2
375 public static function update_users_returns() {
376 return null;
380 * Returns description of method parameters
382 * @return external_function_parameters
383 * @since Moodle 2.4
385 public static function get_users_by_field_parameters() {
386 return new external_function_parameters(
387 array(
388 'field' => new external_value(PARAM_ALPHA, 'the search field can be
389 \'id\' or \'idnumber\' or \'username\' or \'email\''),
390 'values' => new external_multiple_structure(
391 new external_value(PARAM_RAW, 'the value to match'))
397 * Get user information for a unique field.
399 * @param string $field
400 * @param array $values
401 * @return array An array of arrays containg user profiles.
402 * @since Moodle 2.4
404 public static function get_users_by_field($field, $values) {
405 global $CFG, $USER, $DB;
406 require_once($CFG->dirroot . "/user/lib.php");
408 $params = self::validate_parameters(self::get_users_by_field_parameters(),
409 array('field' => $field, 'values' => $values));
411 // This array will keep all the users that are allowed to be searched,
412 // according to the current user's privileges.
413 $cleanedvalues = array();
415 switch ($field) {
416 case 'id':
417 $paramtype = PARAM_INT;
418 break;
419 case 'idnumber':
420 $paramtype = PARAM_RAW;
421 break;
422 case 'username':
423 $paramtype = PARAM_RAW;
424 break;
425 case 'email':
426 $paramtype = PARAM_EMAIL;
427 break;
428 default:
429 throw new coding_exception('invalid field parameter',
430 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
433 // Clean the values
434 foreach ($values as $value) {
435 $cleanedvalue = clean_param($value, $paramtype);
436 if ( $value != $cleanedvalue) {
437 throw new invalid_parameter_exception('The field \'' . $field .
438 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
440 $cleanedvalues[] = $cleanedvalue;
443 // Retrieve the users
444 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
446 // Finally retrieve each users information
447 $returnedusers = array();
448 foreach ($users as $user) {
449 $userdetails = user_get_user_details_courses($user);
451 // Return the user only if the searched field is returned
452 // Otherwise it means that the $USER was not allowed to search the returned user
453 if (!empty($userdetails) and !empty($userdetails[$field])) {
454 $returnedusers[] = $userdetails;
458 return $returnedusers;
462 * Returns description of method result value
464 * @return external_multiple_structure
465 * @since Moodle 2.4
467 public static function get_users_by_field_returns() {
468 return new external_multiple_structure(self::user_description());
473 * Returns description of get_users() parameters.
475 * @return external_function_parameters
476 * @since Moodle 2.5
478 public static function get_users_parameters() {
479 return new external_function_parameters(
480 array(
481 'criteria' => new external_multiple_structure(
482 new external_single_structure(
483 array(
484 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
485 "id" (int) matching user id,
486 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
487 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
488 "idnumber" (string) matching user idnumber,
489 "username" (string) matching user username,
490 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
491 "auth" (string) matching user auth plugin'),
492 'value' => new external_value(PARAM_RAW, 'the value to search')
494 ), 'the key/value pairs to be considered in user search. Values can not be empty.
495 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
496 key occurences are forbidden.
497 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
498 the search is still executed on the valid criterias.
499 You can search without criteria, but the function is not designed for it.
500 It could very slow or timeout. The function is designed to search some specific users.'
507 * Retrieve matching user.
509 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
510 * @return array An array of arrays containing user profiles.
511 * @since Moodle 2.5
513 public static function get_users($criteria = array()) {
514 global $CFG, $USER, $DB;
516 require_once($CFG->dirroot . "/user/lib.php");
518 $params = self::validate_parameters(self::get_users_parameters(),
519 array('criteria' => $criteria));
521 // Validate the criteria and retrieve the users.
522 $users = array();
523 $warnings = array();
524 $sqlparams = array();
525 $usedkeys = array();
527 // Do not retrieve deleted users.
528 $sql = ' deleted = 0';
530 foreach ($params['criteria'] as $criteriaindex => $criteria) {
532 // Check that the criteria has never been used.
533 if (array_key_exists($criteria['key'], $usedkeys)) {
534 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
535 } else {
536 $usedkeys[$criteria['key']] = true;
539 $invalidcriteria = false;
540 // Clean the parameters.
541 $paramtype = PARAM_RAW;
542 switch ($criteria['key']) {
543 case 'id':
544 $paramtype = PARAM_INT;
545 break;
546 case 'idnumber':
547 $paramtype = PARAM_RAW;
548 break;
549 case 'username':
550 $paramtype = PARAM_RAW;
551 break;
552 case 'email':
553 // We use PARAM_RAW to allow searches with %.
554 $paramtype = PARAM_RAW;
555 break;
556 case 'auth':
557 $paramtype = PARAM_AUTH;
558 break;
559 case 'lastname':
560 case 'firstname':
561 $paramtype = PARAM_TEXT;
562 break;
563 default:
564 // Send back a warning that this search key is not supported in this version.
565 // This warning will make the function extandable without breaking clients.
566 $warnings[] = array(
567 'item' => $criteria['key'],
568 'warningcode' => 'invalidfieldparameter',
569 'message' => 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
571 // Do not add this invalid criteria to the created SQL request.
572 $invalidcriteria = true;
573 unset($params['criteria'][$criteriaindex]);
574 break;
577 if (!$invalidcriteria) {
578 $cleanedvalue = clean_param($criteria['value'], $paramtype);
580 $sql .= ' AND ';
582 // Create the SQL.
583 switch ($criteria['key']) {
584 case 'id':
585 case 'idnumber':
586 case 'username':
587 case 'auth':
588 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
589 $sqlparams[$criteria['key']] = $cleanedvalue;
590 break;
591 case 'email':
592 case 'lastname':
593 case 'firstname':
594 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
595 $sqlparams[$criteria['key']] = $cleanedvalue;
596 break;
597 default:
598 break;
603 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
605 // Finally retrieve each users information.
606 $returnedusers = array();
607 foreach ($users as $user) {
608 $userdetails = user_get_user_details_courses($user);
610 // Return the user only if all the searched fields are returned.
611 // Otherwise it means that the $USER was not allowed to search the returned user.
612 if (!empty($userdetails)) {
613 $validuser = true;
615 foreach($params['criteria'] as $criteria) {
616 if (empty($userdetails[$criteria['key']])) {
617 $validuser = false;
621 if ($validuser) {
622 $returnedusers[] = $userdetails;
627 return array('users' => $returnedusers, 'warnings' => $warnings);
631 * Returns description of get_users result value.
633 * @return external_description
634 * @since Moodle 2.5
636 public static function get_users_returns() {
637 return new external_single_structure(
638 array('users' => new external_multiple_structure(
639 self::user_description()
641 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
647 * Returns description of method parameters
649 * @return external_function_parameters
650 * @since Moodle 2.2
651 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
652 * @see core_user_external::get_users_by_field_parameters()
654 public static function get_users_by_id_parameters() {
655 return new external_function_parameters(
656 array(
657 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
663 * Get user information
664 * - This function is matching the permissions of /user/profil.php
665 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
666 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
668 * @param array $userids array of user ids
669 * @return array An array of arrays describing users
670 * @since Moodle 2.2
671 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
672 * @see core_user_external::get_users_by_field()
674 public static function get_users_by_id($userids) {
675 global $CFG, $USER, $DB;
676 require_once($CFG->dirroot . "/user/lib.php");
678 $params = self::validate_parameters(self::get_users_by_id_parameters(),
679 array('userids'=>$userids));
681 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
682 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
683 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
684 $params['contextlevel'] = CONTEXT_USER;
685 $usersql = "SELECT u.* $uselect
686 FROM {user} u $ujoin
687 WHERE u.id $sqluserids";
688 $users = $DB->get_recordset_sql($usersql, $params);
690 $result = array();
691 $hasuserupdatecap = has_capability('moodle/user:update', context_system::instance());
692 foreach ($users as $user) {
693 if (!empty($user->deleted)) {
694 continue;
696 context_helper::preload_from_record($user);
697 $usercontext = context_user::instance($user->id, IGNORE_MISSING);
698 self::validate_context($usercontext);
699 $currentuser = ($user->id == $USER->id);
701 if ($userarray = user_get_user_details($user)) {
702 //fields matching permissions from /user/editadvanced.php
703 if ($currentuser or $hasuserupdatecap) {
704 $userarray['auth'] = $user->auth;
705 $userarray['confirmed'] = $user->confirmed;
706 $userarray['idnumber'] = $user->idnumber;
707 $userarray['lang'] = $user->lang;
708 $userarray['theme'] = $user->theme;
709 $userarray['timezone'] = $user->timezone;
710 $userarray['mailformat'] = $user->mailformat;
712 $result[] = $userarray;
715 $users->close();
717 return $result;
721 * Returns description of method result value
723 * @return external_description
724 * @since Moodle 2.2
725 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
726 * @see core_user_external::get_users_by_field_returns()
728 public static function get_users_by_id_returns() {
729 $additionalfields = array (
730 'enrolledcourses' => new external_multiple_structure(
731 new external_single_structure(
732 array(
733 'id' => new external_value(PARAM_INT, 'Id of the course'),
734 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
735 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
737 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL));
738 return new external_multiple_structure(self::user_description($additionalfields));
742 * Returns description of method parameters
744 * @return external_function_parameters
745 * @since Moodle 2.2
747 public static function get_course_user_profiles_parameters() {
748 return new external_function_parameters(
749 array(
750 'userlist' => new external_multiple_structure(
751 new external_single_structure(
752 array(
753 'userid' => new external_value(PARAM_INT, 'userid'),
754 'courseid' => new external_value(PARAM_INT, 'courseid'),
763 * Get course participant's details
765 * @param array $userlist array of user ids and according course ids
766 * @return array An array of arrays describing course participants
767 * @since Moodle 2.2
769 public static function get_course_user_profiles($userlist) {
770 global $CFG, $USER, $DB;
771 require_once($CFG->dirroot . "/user/lib.php");
772 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist'=>$userlist));
774 $userids = array();
775 $courseids = array();
776 foreach ($params['userlist'] as $value) {
777 $userids[] = $value['userid'];
778 $courseids[$value['userid']] = $value['courseid'];
781 // cache all courses
782 $courses = array();
783 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
784 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
785 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
786 $params['contextlevel'] = CONTEXT_COURSE;
787 $coursesql = "SELECT c.* $cselect
788 FROM {course} c $cjoin
789 WHERE c.id $sqlcourseids";
790 $rs = $DB->get_recordset_sql($coursesql, $params);
791 foreach ($rs as $course) {
792 // adding course contexts to cache
793 context_helper::preload_from_record($course);
794 // cache courses
795 $courses[$course->id] = $course;
797 $rs->close();
799 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
800 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
801 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
802 $params['contextlevel'] = CONTEXT_USER;
803 $usersql = "SELECT u.* $uselect
804 FROM {user} u $ujoin
805 WHERE u.id $sqluserids";
806 $users = $DB->get_recordset_sql($usersql, $params);
807 $result = array();
808 foreach ($users as $user) {
809 if (!empty($user->deleted)) {
810 continue;
812 context_helper::preload_from_record($user);
813 $course = $courses[$courseids[$user->id]];
814 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
815 self::validate_context($context);
816 if ($userarray = user_get_user_details($user, $course)) {
817 $result[] = $userarray;
821 $users->close();
823 return $result;
827 * Returns description of method result value
829 * @return external_description
830 * @since Moodle 2.2
832 public static function get_course_user_profiles_returns() {
833 $additionalfields = array(
834 'groups' => new external_multiple_structure(
835 new external_single_structure(
836 array(
837 'id' => new external_value(PARAM_INT, 'group id'),
838 'name' => new external_value(PARAM_RAW, 'group name'),
839 'description' => new external_value(PARAM_RAW, 'group description'),
840 'descriptionformat' => new external_format_value('description'),
842 ), 'user groups', VALUE_OPTIONAL),
843 'roles' => new external_multiple_structure(
844 new external_single_structure(
845 array(
846 'roleid' => new external_value(PARAM_INT, 'role id'),
847 'name' => new external_value(PARAM_RAW, 'role name'),
848 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
849 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
851 ), 'user roles', VALUE_OPTIONAL),
852 'enrolledcourses' => new external_multiple_structure(
853 new external_single_structure(
854 array(
855 'id' => new external_value(PARAM_INT, 'Id of the course'),
856 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
857 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
859 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
862 return new external_multiple_structure(self::user_description($additionalfields));
866 * Create user return value description.
868 * @param array $additionalfields some additional field
869 * @return single_structure_description
871 public static function user_description($additionalfields = array()) {
872 $userfields = array(
873 'id' => new external_value(PARAM_INT, 'ID of the user'),
874 'username' => new external_value(PARAM_RAW, 'The username', VALUE_OPTIONAL),
875 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
876 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
877 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
878 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
879 'address' => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL),
880 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
881 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
882 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
883 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
884 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
885 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
886 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
887 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
888 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
889 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
890 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
891 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
892 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
893 'auth' => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
894 'confirmed' => new external_value(PARAM_INT, 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
895 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
896 'theme' => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
897 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
898 'mailformat' => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
899 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
900 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
901 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
902 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
903 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
904 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
905 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
906 'customfields' => new external_multiple_structure(
907 new external_single_structure(
908 array(
909 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
910 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
911 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
912 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
914 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
915 'preferences' => new external_multiple_structure(
916 new external_single_structure(
917 array(
918 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
919 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
921 ), 'Users preferences', VALUE_OPTIONAL)
923 if (!empty($additionalfields)) {
924 $userfields = array_merge($userfields, $additionalfields);
926 return new external_single_structure($userfields);
930 * Returns description of method parameters
932 * @return external_function_parameters
933 * @since Moodle 2.6
935 public static function add_user_private_files_parameters() {
936 return new external_function_parameters(
937 array(
938 'draftid' => new external_value(PARAM_INT, 'draft area id')
944 * Copy files from a draft area to users private files area.
946 * @param int $draftid Id of a draft area containing files.
947 * @return array An array of warnings
948 * @since Moodle 2.6
950 public static function add_user_private_files($draftid) {
951 global $CFG, $USER, $DB;
953 require_once($CFG->dirroot . "/user/lib.php");
954 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid'=>$draftid));
956 if (isguestuser()) {
957 throw new invalid_parameter_exception('Guest users cannot upload files');
960 $context = context_user::instance($USER->id);
961 require_capability('moodle/user:manageownfiles', $context);
963 $maxbytes = $CFG->userquota;
964 $maxareabytes = $CFG->userquota;
965 if (has_capability('moodle/user:ignoreuserquota', $context)) {
966 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
967 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
970 $options = array('subdirs' => 1,
971 'maxbytes' => $maxbytes,
972 'maxfiles' => -1,
973 'accepted_types' => '*',
974 'areamaxbytes' => $maxareabytes);
976 file_save_draft_area_files($draftid, $context->id, 'user', 'private', 0, $options);
978 return null;
982 * Returns description of method result value
984 * @return external_description
985 * @since Moodle 2.2
987 public static function add_user_private_files_returns() {
988 return null;
992 * Returns description of method parameters.
994 * @return external_function_parameters
995 * @since Moodle 2.6
997 public static function add_user_device_parameters() {
998 return new external_function_parameters(
999 array(
1000 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1001 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1002 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1003 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1004 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1005 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1006 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1012 * Add a user device in Moodle database (for PUSH notifications usually).
1014 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1015 * @param string $name The device name, occam or iPhone etc.
1016 * @param string $model The device model Nexus4 or iPad1.1 etc.
1017 * @param string $platform The device platform iOs or Android etc.
1018 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1019 * @param string $pushid The device PUSH token/key/identifier/registration id.
1020 * @param string $uuid The device UUID.
1021 * @return array List of possible warnings.
1022 * @since Moodle 2.6
1024 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1025 global $CFG, $USER, $DB;
1026 require_once($CFG->dirroot . "/user/lib.php");
1028 $params = self::validate_parameters(self::add_user_device_parameters(),
1029 array('appid' => $appid,
1030 'name' => $name,
1031 'model' => $model,
1032 'platform' => $platform,
1033 'version' => $version,
1034 'pushid' => $pushid,
1035 'uuid' => $uuid
1038 $warnings = array();
1040 // Prevent duplicate keys for users.
1041 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1042 $warnings['warning'][] = array(
1043 'item' => $params['pushid'],
1044 'warningcode' => 'existingkeyforthisuser',
1045 'message' => 'This key is already stored for this user'
1047 return $warnings;
1050 // The same key can't exists for the same platform.
1051 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'platform' => $params['platform']))) {
1052 $warnings['warning'][] = array(
1053 'item' => $params['pushid'],
1054 'warningcode' => 'existingkeyforplatform',
1055 'message' => 'This key is already stored for other device using the same platform'
1057 return $warnings;
1060 $userdevice = new stdclass;
1061 $userdevice->userid = $USER->id;
1062 $userdevice->appid = $params['appid'];
1063 $userdevice->name = $params['name'];
1064 $userdevice->model = $params['model'];
1065 $userdevice->platform = $params['platform'];
1066 $userdevice->version = $params['version'];
1067 $userdevice->pushid = $params['pushid'];
1068 $userdevice->uuid = $params['uuid'];
1069 $userdevice->timecreated = time();
1070 $userdevice->timemodified = $userdevice->timecreated;
1072 if (!$DB->insert_record('user_devices', $userdevice)) {
1073 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1076 return $warnings;
1080 * Returns description of method result value.
1082 * @return external_multiple_structure
1083 * @since Moodle 2.6
1085 public static function add_user_device_returns() {
1086 return new external_multiple_structure(
1087 new external_warnings()
1094 * Deprecated user external functions
1096 * @package core_user
1097 * @copyright 2009 Petr Skodak
1098 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1099 * @since Moodle 2.0
1100 * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
1101 * @see core_user_external
1103 class moodle_user_external extends external_api {
1106 * Returns description of method parameters
1108 * @return external_function_parameters
1109 * @since Moodle 2.0
1110 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1111 * @see core_user_external::create_users_parameters()
1113 public static function create_users_parameters() {
1114 return core_user_external::create_users_parameters();
1118 * Create one or more users
1120 * @param array $users An array of users to create.
1121 * @return array An array of arrays
1122 * @since Moodle 2.0
1123 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1124 * @see core_user_external::create_users()
1126 public static function create_users($users) {
1127 return core_user_external::create_users($users);
1131 * Returns description of method result value
1133 * @return external_description
1134 * @since Moodle 2.0
1135 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1136 * @see core_user_external::create_users_returns()
1138 public static function create_users_returns() {
1139 return core_user_external::create_users_returns();
1144 * Returns description of method parameters
1146 * @return external_function_parameters
1147 * @since Moodle 2.0
1148 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1149 * @see core_user_external::delete_users_parameters()
1151 public static function delete_users_parameters() {
1152 return core_user_external::delete_users_parameters();
1156 * Delete users
1158 * @param array $userids
1159 * @return null
1160 * @since Moodle 2.0
1161 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1162 * @see core_user_external::delete_users()
1164 public static function delete_users($userids) {
1165 return core_user_external::delete_users($userids);
1169 * Returns description of method result value
1171 * @return null
1172 * @since Moodle 2.0
1173 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1174 * @see core_user_external::delete_users_returns()
1176 public static function delete_users_returns() {
1177 return core_user_external::delete_users_returns();
1182 * Returns description of method parameters
1184 * @return external_function_parameters
1185 * @since Moodle 2.0
1186 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1187 * @see core_user_external::update_users_parameters()
1189 public static function update_users_parameters() {
1190 return core_user_external::update_users_parameters();
1194 * Update users
1196 * @param array $users
1197 * @return null
1198 * @since Moodle 2.0
1199 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1200 * @see core_user_external::update_users()
1202 public static function update_users($users) {
1203 return core_user_external::update_users($users);
1207 * Returns description of method result value
1209 * @return null
1210 * @since Moodle 2.0
1211 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1212 * @see core_user_external::update_users_returns()
1214 public static function update_users_returns() {
1215 return core_user_external::update_users_returns();
1219 * Returns description of method parameters
1221 * @return external_function_parameters
1222 * @since Moodle 2.0
1223 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1224 * @see core_user_external::get_users_by_id_parameters()
1226 public static function get_users_by_id_parameters() {
1227 return core_user_external::get_users_by_id_parameters();
1231 * Get user information
1232 * - This function is matching the permissions of /user/profil.php
1233 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
1234 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
1236 * @param array $userids array of user ids
1237 * @return array An array of arrays describing users
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::get_users_by_id()
1242 public static function get_users_by_id($userids) {
1243 return core_user_external::get_users_by_id($userids);
1247 * Returns description of method result value
1249 * @return external_description
1250 * @since Moodle 2.0
1251 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1252 * @see core_user_external::get_users_by_id_returns()
1254 public static function get_users_by_id_returns() {
1255 return core_user_external::get_users_by_id_returns();
1258 * Returns description of method parameters
1260 * @return external_function_parameters
1261 * @since Moodle 2.1
1262 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1263 * @see core_user_external::get_course_user_profiles_parameters()
1265 public static function get_course_participants_by_id_parameters() {
1266 return core_user_external::get_course_user_profiles_parameters();
1270 * Get course participant's details
1272 * @param array $userlist array of user ids and according course ids
1273 * @return array An array of arrays describing course participants
1274 * @since Moodle 2.1
1275 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1276 * @see core_user_external::get_course_user_profiles()
1278 public static function get_course_participants_by_id($userlist) {
1279 return core_user_external::get_course_user_profiles($userlist);
1283 * Returns description of method result value
1285 * @return external_description
1286 * @since Moodle 2.1
1287 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1288 * @see core_user_external::get_course_user_profiles_returns()
1290 public static function get_course_participants_by_id_returns() {
1291 return core_user_external::get_course_user_profiles_returns();
1295 * Returns description of method parameters
1297 * @return external_function_parameters
1298 * @since Moodle 2.1
1299 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1300 * @see core_enrol_external::get_enrolled_users_parameters()
1302 public static function get_users_by_courseid_parameters() {
1303 global $CFG;
1304 require_once($CFG->dirroot . '/enrol/externallib.php');
1305 return core_enrol_external::get_enrolled_users_parameters();
1309 * Get course participants details
1311 * @param int $courseid course id
1312 * @param array $options options {
1313 * 'name' => option name
1314 * 'value' => option value
1316 * @return array An array of users
1317 * @since Moodle 2.1
1318 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1319 * @see core_enrol_external::get_enrolled_users()
1321 public static function get_users_by_courseid($courseid, $options) {
1322 global $CFG;
1323 require_once($CFG->dirroot . '/enrol/externallib.php');
1324 return core_enrol_external::get_enrolled_users($courseid, $options);
1327 * Returns description of method result value
1329 * @return external_description
1330 * @since Moodle 2.1
1331 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1332 * @see core_enrol_external::get_enrolled_users_returns()
1334 public static function get_users_by_courseid_returns() {
1335 global $CFG;
1336 require_once($CFG->dirroot . '/enrol/externallib.php');
1337 return core_enrol_external::get_enrolled_users_returns();