weekly release 2.1dev
[moodle.git] / user / externallib.php
CommitLineData
ef22c1b6 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * External user API
20 *
21 * @package moodlecore
22 * @subpackage webservice
551f4420 23 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
ef22c1b6 24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27require_once("$CFG->libdir/externallib.php");
28
29class moodle_user_external extends external_api {
30
7b472b32
PS
31 /**
32 * Returns description of method parameters
33 * @return external_function_parameters
34 */
d4e13355 35 public static function create_users_parameters() {
667b496a
PS
36 global $CFG;
37
35b9a80a 38 return new external_function_parameters(
39 array(
40 'users' => new external_multiple_structure(
41 new external_single_structure(
42 array(
7b472b32 43 'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config'),
667b496a 44 'password' => new external_value(PARAM_RAW, 'Plain text password consisting of any characters'),
7b472b32
PS
45 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
46 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user'),
47 'email' => new external_value(PARAM_EMAIL, 'A valid and unique email address'),
fb79269b 48 'auth' => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT, 'manual', NULL_NOT_ALLOWED),
610a447e 49 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_DEFAULT, ''),
3a915b06 50 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_DEFAULT, $CFG->lang, NULL_NOT_ALLOWED),
fb79269b 51 'theme' => new external_value(PARAM_SAFEDIR, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
52 'timezone' => new external_value(PARAM_ALPHANUMEXT, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
53 'mailformat' => new external_value(PARAM_INTEGER, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
d9ad0103 54 'description' => new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
fb79269b 55 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
56 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
35b9a80a 57 'preferences' => new external_multiple_structure(
58 new external_single_structure(
59 array(
7b472b32 60 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
35b9a80a 61 'value' => new external_value(PARAM_RAW, 'The value of the preference')
62 )
fb79269b 63 ), 'User preferences', VALUE_OPTIONAL),
35b9a80a 64 'customfields' => new external_multiple_structure(
65 new external_single_structure(
66 array(
7b472b32 67 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
35b9a80a 68 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
69 )
6bb31e40 70 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
35b9a80a 71 )
72 )
73 )
74 )
75 );
625f0a24 76 }
77
d4e13355 78 /**
5de592b1 79 * Create one or more users
80 *
71864f15
PS
81 * @param array $users An array of users to create.
82 * @return array An array of arrays
5de592b1 83 */
7b472b32 84 public static function create_users($users) {
ef22c1b6 85 global $CFG, $DB;
fb79269b 86 require_once($CFG->dirroot."/user/lib.php");
30a4fb1b 87 require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function
88 //TODO: move the functions somewhere else as
89 //they are "user" related
109b453b 90
5de592b1 91 // Ensure the current user is allowed to run this function
ef22c1b6 92 $context = get_context_instance(CONTEXT_SYSTEM);
ef22c1b6 93 self::validate_context($context);
fb79269b 94 require_capability('moodle/user:create', $context);
d9ad0103 95
5de592b1 96 // Do basic automatic PARAM checks on incoming data, using params description
5de592b1 97 // If any problems are found then exceptions are thrown with helpful error messages
7b472b32 98 $params = self::validate_parameters(self::create_users_parameters(), array('users'=>$users));
109b453b 99
667b496a
PS
100 $availableauths = get_plugin_list('auth');
101 unset($availableauths['mnet']); // these would need mnethostid too
102 unset($availableauths['webservice']); // we do not want new webservice users for now
103
104 $availablethemes = get_plugin_list('theme');
1f96e907 105 $availablelangs = get_string_manager()->get_list_of_translations();
5de592b1 106
38b76f3c 107 $transaction = $DB->start_delegated_transaction();
5de592b1 108
fb79269b 109 $userids = array();
7b472b32 110 foreach ($params['users'] as $user) {
667b496a
PS
111 // Make sure that the username doesn't already exist
112 if ($DB->record_exists('user', array('username'=>$user['username'], 'mnethostid'=>$CFG->mnet_localhost_id))) {
113 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
ef22c1b6 114 }
ef22c1b6 115
667b496a
PS
116 // Make sure auth is valid
117 if (empty($availableauths[$user['auth']])) {
118 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
ef22c1b6 119 }
120
667b496a
PS
121 // Make sure lang is valid
122 if (empty($availablelangs[$user['lang']])) {
123 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
ef22c1b6 124 }
125
667b496a 126 // Make sure lang is valid
fb79269b 127 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { //theme is VALUE_OPTIONAL,
128 // so no default value.
129 // We need to test if the client sent it
130 // => !empty($user['theme'])
667b496a 131 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
ef22c1b6 132 }
5de592b1 133
38b76f3c
PS
134 // make sure there is no data loss during truncation
135 $truncated = truncate_userinfo($user);
136 foreach ($truncated as $key=>$value) {
610a447e 137 if ($truncated[$key] !== $user[$key]) {
138 throw new invalid_parameter_exception('Property: '.$key.' is too long: '.$user[$key]);
139 }
38b76f3c 140 }
5de592b1 141
fb79269b 142 $user['confirmed'] = true;
a1988186 143 $user['mnethostid'] = $CFG->mnet_localhost_id;
30a4fb1b 144 $user['id'] = user_create_user($user);
145
146 // custom fields
147 if(!empty($user['customfields'])) {
148 foreach($user['customfields'] as $customfield) {
149 $user["profile_field_".$customfield['type']] = $customfield['value']; //profile_save_data() saves profile file
150 //it's expecting a user with the correct id,
151 //and custom field to be named profile_field_"shortname"
152 }
153 profile_save_data((object) $user);
154 }
667b496a 155
d9ad0103 156 //preferences
157 if (!empty($user['preferences'])) {
158 foreach($user['preferences'] as $preference) {
159 set_user_preference($preference['type'], $preference['value'],$user['id']);
160 }
161 }
d4e13355 162
c4c352dd 163 $userids[] = array('id'=>$user['id'], 'username'=>$user['username']);
ef22c1b6 164 }
165
38b76f3c 166 $transaction->allow_commit();
667b496a 167
fb79269b 168 return $userids;
ef22c1b6 169 }
170
7b472b32
PS
171 /**
172 * Returns description of method result value
173 * @return external_description
174 */
175 public static function create_users_returns() {
176 return new external_multiple_structure(
177 new external_single_structure(
178 array(
179 'id' => new external_value(PARAM_INT, 'user id'),
180 'username' => new external_value(PARAM_RAW, 'user name'),
181 )
182 )
183 );
d4e13355 184 }
185
186
930680cb
PS
187 /**
188 * Returns description of method parameters
189 * @return external_function_parameters
190 */
d4e13355 191 public static function delete_users_parameters() {
930680cb
PS
192 return new external_function_parameters(
193 array(
194 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
195 )
196 );
d4e13355 197 }
930680cb 198
38b76f3c 199 public static function delete_users($userids) {
b73a28be 200 global $CFG, $DB, $USER;
fb79269b 201 require_once($CFG->dirroot."/user/lib.php");
38b76f3c
PS
202
203 // Ensure the current user is allowed to run this function
204 $context = get_context_instance(CONTEXT_SYSTEM);
205 require_capability('moodle/user:delete', $context);
206 self::validate_context($context);
207
fb79269b 208 $params = self::validate_parameters(self::delete_users_parameters(), array('userids'=>$userids));
38b76f3c
PS
209
210 $transaction = $DB->start_delegated_transaction();
38b76f3c
PS
211
212 foreach ($params['userids'] as $userid) {
213 $user = $DB->get_record('user', array('id'=>$userid, 'deleted'=>0), '*', MUST_EXIST);
b73a28be 214 // must not allow deleting of admins or self!!!
4f622c38
PS
215 if (is_siteadmin($user)) {
216 throw new moodle_exception('useradminodelete', 'error');
217 }
218 if ($USER->id == $user->id) {
219 throw new moodle_exception('usernotdeletederror', 'error');
b73a28be 220 }
fb79269b 221 user_delete_user($user);
38b76f3c
PS
222 }
223
224 $transaction->allow_commit();
225
226 return null;
ef22c1b6 227 }
930680cb
PS
228
229 /**
230 * Returns description of method result value
231 * @return external_description
232 */
d4e13355 233 public static function delete_users_returns() {
930680cb 234 return null;
d4e13355 235 }
ef22c1b6 236
237
930680cb
PS
238 /**
239 * Returns description of method parameters
240 * @return external_function_parameters
241 */
d4e13355 242 public static function update_users_parameters() {
fb79269b 243 global $CFG;
244 return new external_function_parameters(
245 array(
246 'users' => new external_multiple_structure(
247 new external_single_structure(
248 array(
249 'id' => new external_value(PARAM_NUMBER, 'ID of the user'),
250 'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
251 'password' => new external_value(PARAM_RAW, 'Plain text password consisting of any characters', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
252 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
253 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
254 'email' => new external_value(PARAM_EMAIL, 'A valid and unique email address', VALUE_OPTIONAL, '',NULL_NOT_ALLOWED),
255 'auth' => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
256 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
3a915b06 257 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
fb79269b 258 'theme' => new external_value(PARAM_SAFEDIR, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
259 'timezone' => new external_value(PARAM_ALPHANUMEXT, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
260 'mailformat' => new external_value(PARAM_INTEGER, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
d9ad0103 261 'description' => new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
fb79269b 262 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
263 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
fb79269b 264 'customfields' => new external_multiple_structure(
265 new external_single_structure(
266 array(
267 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
268 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
269 )
6bb31e40 270 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
d9ad0103 271 'preferences' => new external_multiple_structure(
272 new external_single_structure(
273 array(
274 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
275 'value' => new external_value(PARAM_RAW, 'The value of the preference')
276 )
277 ), 'User preferences', VALUE_OPTIONAL),
fb79269b 278 )
279 )
280 )
281 )
282 );
d4e13355 283 }
38b76f3c
PS
284
285 public static function update_users($users) {
286 global $CFG, $DB;
fb79269b 287 require_once($CFG->dirroot."/user/lib.php");
9baf3a7b 288 require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function
289 //TODO: move the functions somewhere else as
290 //they are "user" related
38b76f3c
PS
291
292 // Ensure the current user is allowed to run this function
293 $context = get_context_instance(CONTEXT_SYSTEM);
294 require_capability('moodle/user:update', $context);
295 self::validate_context($context);
296
297 $params = self::validate_parameters(self::update_users_parameters(), array('users'=>$users));
298
299 $transaction = $DB->start_delegated_transaction();
300
301 foreach ($params['users'] as $user) {
fb79269b 302 user_update_user($user);
9baf3a7b 303 //update user custom fields
304 if(!empty($user['customfields'])) {
305
306 foreach($user['customfields'] as $customfield) {
307 $user["profile_field_".$customfield['type']] = $customfield['value']; //profile_save_data() saves profile file
308 //it's expecting a user with the correct id,
309 //and custom field to be named profile_field_"shortname"
310 }
311 profile_save_data((object) $user);
312 }
d9ad0103 313
314 //preferences
315 if (!empty($user['preferences'])) {
316 foreach($user['preferences'] as $preference) {
317 set_user_preference($preference['type'], $preference['value'],$user['id']);
318 }
319 }
38b76f3c
PS
320 }
321
322 $transaction->allow_commit();
323
324 return null;
ef22c1b6 325 }
930680cb
PS
326
327 /**
328 * Returns description of method result value
329 * @return external_description
330 */
d4e13355 331 public static function update_users_returns() {
930680cb 332 return null;
d4e13355 333 }
334
7b472b32
PS
335 /**
336 * Returns description of method parameters
337 * @return external_function_parameters
338 */
fb79269b 339 public static function get_users_by_id_parameters() {
71864f15 340 return new external_function_parameters(
109b453b 341 array(
342 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
343 )
71864f15 344 );
d4e13355 345 }
7b472b32 346
71864f15
PS
347 /**
348 * Get user information
349 *
350 * @param array $userids array of user ids
351 * @return array An array of arrays describing users
352 */
fb79269b 353 public static function get_users_by_id($userids) {
354 global $CFG;
109b453b 355 require_once($CFG->dirroot . "/user/lib.php");
356 //required for customfields related function
357 //TODO: move the functions somewhere else as
358 //they are "user" related
359 require_once($CFG->dirroot . "/user/profile/lib.php");
fb79269b 360
109b453b 361 $params = self::validate_parameters(self::get_users_by_id_parameters(),
362 array('userids'=>$userids));
5de592b1 363
109b453b 364 //TODO: check if there is any performance issue: we do one DB request to retrieve
365 // all user, then for each user the profile_load_data does at least two DB requests
d4e13355 366
fb79269b 367 $users = user_get_users_by_id($params['userids']);
109b453b 368 $result = array();
d4e13355 369 foreach ($users as $user) {
109b453b 370
6d153e67 371 $context = get_context_instance(CONTEXT_USER, $user->id);
372 require_capability('moodle/user:viewalldetails', $context);
373 self::validate_context($context);
374
fb79269b 375 if (empty($user->deleted)) {
376
109b453b 377 $userarray = array();
378 //we want to return an array not an object
379 /// now we transfert all profile_field_xxx into the customfields
380 // external_multiple_structure required by description
381 $userarray['id'] = $user->id;
382 $userarray['username'] = $user->username;
383 $userarray['firstname'] = $user->firstname;
384 $userarray['lastname'] = $user->lastname;
385 $userarray['email'] = $user->email;
386 $userarray['auth'] = $user->auth;
387 $userarray['confirmed'] = $user->confirmed;
388 $userarray['idnumber'] = $user->idnumber;
109b453b 389 $userarray['lang'] = $user->lang;
390 $userarray['theme'] = $user->theme;
391 $userarray['timezone'] = $user->timezone;
392 $userarray['mailformat'] = $user->mailformat;
393 $userarray['description'] = $user->description;
17f15dac 394 $userarray['descriptionformat'] = $user->descriptionformat;
109b453b 395 $userarray['city'] = $user->city;
396 $userarray['country'] = $user->country;
0f31850a 397 $userarray['customfields'] = array();
fb79269b 398 $customfields = profile_user_record($user->id);
399 $customfields = (array) $customfields;
400 foreach ($customfields as $key => $value) {
401 $userarray['customfields'][] = array('type' => $key, 'value' => $value);
402 }
403
404 $result[] = $userarray;
405 }
fb79269b 406 }
71864f15
PS
407
408 return $result;
d4e13355 409 }
7b472b32 410
109b453b 411 /**
7b472b32
PS
412 * Returns description of method result value
413 * @return external_description
414 */
fb79269b 415 public static function get_users_by_id_returns() {
71864f15 416 return new external_multiple_structure(
109b453b 417 new external_single_structure(
418 array(
fb79269b 419 'id' => new external_value(PARAM_NUMBER, 'ID of the user'),
71864f15
PS
420 'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config'),
421 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
422 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user'),
109b453b 423 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost'),
40e85c92
PS
424 'auth' => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc'),
425 'confirmed' => new external_value(PARAM_NUMBER, 'Active user: 1 if confirmed, 0 otherwise'),
426 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution'),
3a915b06 427 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server'),
40e85c92
PS
428 'theme' => new external_value(PARAM_SAFEDIR, 'Theme name such as "standard", must exist on server'),
429 'timezone' => new external_value(PARAM_ALPHANUMEXT, 'Timezone code such as Australia/Perth, or 99 for default'),
430 'mailformat' => new external_value(PARAM_INTEGER, 'Mail format code is 0 for plain text, 1 for HTML etc'),
17f15dac 431 'description' => new external_value(PARAM_RAW, 'User profile description'),
432 'descriptionformat' => new external_value(PARAM_INT, 'User profile description format'),
40e85c92
PS
433 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user'),
434 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ'),
71864f15 435 'customfields' => new external_multiple_structure(
109b453b 436 new external_single_structure(
437 array(
438 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
439 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
440 )
6bb31e40 441 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
109b453b 442 )
71864f15 443 )
71864f15 444 );
5de592b1 445 }
5de592b1 446}