Removing relics of the previous plan/tasks/steps based implementation
[moodle.git] / user / externallib.php
blob24720257c34a559918b4f95fe0777d068ab93b50
1 <?php
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.
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/>.
18 /**
19 * External user API
21 * @package moodlecore
22 * @subpackage webservice
23 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 require_once("$CFG->libdir/externallib.php");
29 class moodle_user_external extends external_api {
31 /**
32 * Returns description of method parameters
33 * @return external_function_parameters
35 public static function create_users_parameters() {
36 global $CFG;
38 return new external_function_parameters(
39 array(
40 'users' => new external_multiple_structure(
41 new external_single_structure(
42 array(
43 'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config'),
44 'password' => new external_value(PARAM_RAW, 'Plain text password consisting of any characters'),
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'),
48 'auth' => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT, 'manual', NULL_NOT_ALLOWED),
49 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_DEFAULT, ''),
50 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_DEFAULT, $CFG->lang, NULL_NOT_ALLOWED),
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),
54 'description' => new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
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),
57 'preferences' => new external_multiple_structure(
58 new external_single_structure(
59 array(
60 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
61 'value' => new external_value(PARAM_RAW, 'The value of the preference')
63 ), 'User preferences', VALUE_OPTIONAL),
64 'customfields' => new external_multiple_structure(
65 new external_single_structure(
66 array(
67 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
68 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
70 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
78 /**
79 * Create one or more users
81 * @param array $users An array of users to create.
82 * @return array An array of arrays
84 public static function create_users($users) {
85 global $CFG, $DB;
86 require_once($CFG->dirroot."/user/lib.php");
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
91 // Ensure the current user is allowed to run this function
92 $context = get_context_instance(CONTEXT_SYSTEM);
93 self::validate_context($context);
94 require_capability('moodle/user:create', $context);
96 // Do basic automatic PARAM checks on incoming data, using params description
97 // If any problems are found then exceptions are thrown with helpful error messages
98 $params = self::validate_parameters(self::create_users_parameters(), array('users'=>$users));
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
104 $availablethemes = get_plugin_list('theme');
105 $availablelangs = get_string_manager()->get_list_of_translations();
107 $transaction = $DB->start_delegated_transaction();
109 $userids = array();
110 foreach ($params['users'] as $user) {
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']);
116 // Make sure auth is valid
117 if (empty($availableauths[$user['auth']])) {
118 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
121 // Make sure lang is valid
122 if (empty($availablelangs[$user['lang']])) {
123 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
126 // Make sure lang is valid
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'])
131 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
134 // make sure there is no data loss during truncation
135 $truncated = truncate_userinfo($user);
136 foreach ($truncated as $key=>$value) {
137 if ($truncated[$key] !== $user[$key]) {
138 throw new invalid_parameter_exception('Property: '.$key.' is too long: '.$user[$key]);
142 $user['confirmed'] = true;
143 $user['mnethostid'] = $CFG->mnet_localhost_id;
144 $user['id'] = user_create_user($user);
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"
153 profile_save_data((object) $user);
156 //preferences
157 if (!empty($user['preferences'])) {
158 foreach($user['preferences'] as $preference) {
159 set_user_preference($preference['type'], $preference['value'],$user['id']);
163 $userids[] = array('id'=>$user['id'], 'username'=>$user['username']);
166 $transaction->allow_commit();
168 return $userids;
172 * Returns description of method result value
173 * @return external_description
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'),
188 * Returns description of method parameters
189 * @return external_function_parameters
191 public static function delete_users_parameters() {
192 return new external_function_parameters(
193 array(
194 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
199 public static function delete_users($userids) {
200 global $CFG, $DB, $USER;
201 require_once($CFG->dirroot."/user/lib.php");
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);
208 $params = self::validate_parameters(self::delete_users_parameters(), array('userids'=>$userids));
210 $transaction = $DB->start_delegated_transaction();
212 foreach ($params['userids'] as $userid) {
213 $user = $DB->get_record('user', array('id'=>$userid, 'deleted'=>0), '*', MUST_EXIST);
214 // must not allow deleting of admins or self!!!
215 if (is_siteadmin($user)) {
216 throw new moodle_exception('useradminodelete', 'error');
218 if ($USER->id == $user->id) {
219 throw new moodle_exception('usernotdeletederror', 'error');
221 user_delete_user($user);
224 $transaction->allow_commit();
226 return null;
230 * Returns description of method result value
231 * @return external_description
233 public static function delete_users_returns() {
234 return null;
239 * Returns description of method parameters
240 * @return external_function_parameters
242 public static function update_users_parameters() {
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),
257 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
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),
261 'description' => new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
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),
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')
270 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
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')
277 ), 'User preferences', VALUE_OPTIONAL),
285 public static function update_users($users) {
286 global $CFG, $DB;
287 require_once($CFG->dirroot."/user/lib.php");
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
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);
297 $params = self::validate_parameters(self::update_users_parameters(), array('users'=>$users));
299 $transaction = $DB->start_delegated_transaction();
301 foreach ($params['users'] as $user) {
302 user_update_user($user);
303 //update user custom fields
304 if(!empty($user['customfields'])) {
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"
311 profile_save_data((object) $user);
314 //preferences
315 if (!empty($user['preferences'])) {
316 foreach($user['preferences'] as $preference) {
317 set_user_preference($preference['type'], $preference['value'],$user['id']);
322 $transaction->allow_commit();
324 return null;
328 * Returns description of method result value
329 * @return external_description
331 public static function update_users_returns() {
332 return null;
336 * Returns description of method parameters
337 * @return external_function_parameters
339 public static function get_users_by_id_parameters() {
340 return new external_function_parameters(
341 array(
342 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
348 * Get user information
350 * @param array $userids array of user ids
351 * @return array An array of arrays describing users
353 public static function get_users_by_id($userids) {
354 global $CFG;
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");
361 $params = self::validate_parameters(self::get_users_by_id_parameters(),
362 array('userids'=>$userids));
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
367 $users = user_get_users_by_id($params['userids']);
368 $result = array();
369 foreach ($users as $user) {
371 $context = get_context_instance(CONTEXT_USER, $user->id);
372 require_capability('moodle/user:viewalldetails', $context);
373 self::validate_context($context);
375 if (empty($user->deleted)) {
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;
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;
394 $userarray['descriptionformat'] = $user->descriptionformat;
395 $userarray['city'] = $user->city;
396 $userarray['country'] = $user->country;
397 $userarray['customfields'] = array();
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);
404 $result[] = $userarray;
408 return $result;
412 * Returns description of method result value
413 * @return external_description
415 public static function get_users_by_id_returns() {
416 return new external_multiple_structure(
417 new external_single_structure(
418 array(
419 'id' => new external_value(PARAM_NUMBER, 'ID of the user'),
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'),
423 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost'),
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'),
427 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server'),
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'),
431 'description' => new external_value(PARAM_RAW, 'User profile description'),
432 'descriptionformat' => new external_value(PARAM_INT, 'User profile description format'),
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'),
435 'customfields' => new external_multiple_structure(
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')
441 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)