MDL-48716 webservices: New ws core_user_remove_user_device
[moodle.git] / user / externallib.php
CommitLineData
ef22c1b6 1<?php
ef22c1b6 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.
13//
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/>.
16
17/**
18 * External user API
19 *
4615817d
JM
20 * @package core_user
21 * @category external
22 * @copyright 2009 Petr Skodak
ef22c1b6 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26require_once("$CFG->libdir/externallib.php");
27
5d1017e1 28/**
4615817d
JM
29 * User external functions
30 *
31 * @package core_user
32 * @category external
33 * @copyright 2011 Jerome Mouneyrac
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 * @since Moodle 2.2
5d1017e1
JM
36 */
37class core_user_external extends external_api {
ef22c1b6 38
7b472b32
PS
39 /**
40 * Returns description of method parameters
4615817d 41 *
7b472b32 42 * @return external_function_parameters
4615817d 43 * @since Moodle 2.2
7b472b32 44 */
d4e13355 45 public static function create_users_parameters() {
667b496a
PS
46 global $CFG;
47
35b9a80a 48 return new external_function_parameters(
49 array(
50 'users' => new external_multiple_structure(
51 new external_single_structure(
52 array(
a2ed6e69
SH
53 'username' =>
54 new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config.'),
55 'password' =>
56 new external_value(PARAM_RAW, 'Plain text password consisting of any characters'),
57 'firstname' =>
58 new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
59 'lastname' =>
60 new external_value(PARAM_NOTAGS, 'The family name of the user'),
61 'email' =>
62 new external_value(PARAM_EMAIL, 'A valid and unique email address'),
63 'auth' =>
64 new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT,
65 'manual', NULL_NOT_ALLOWED),
66 'idnumber' =>
67 new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution',
68 VALUE_DEFAULT, ''),
69 'lang' =>
70 new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_DEFAULT,
71 $CFG->lang, NULL_NOT_ALLOWED),
72 'calendartype' =>
73 new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server',
74 VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
75 'theme' =>
76 new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server',
77 VALUE_OPTIONAL),
78 'timezone' =>
79 new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default',
80 VALUE_OPTIONAL),
81 'mailformat' =>
82 new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc',
83 VALUE_OPTIONAL),
84 'description' =>
85 new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
86 'city' =>
87 new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
88 'country' =>
89 new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
90 'firstnamephonetic' =>
91 new external_value(PARAM_NOTAGS, 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
92 'lastnamephonetic' =>
93 new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
94 'middlename' =>
95 new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
96 'alternatename' =>
97 new external_value(PARAM_NOTAGS, 'The alternate name of the user', VALUE_OPTIONAL),
98 'preferences' => new external_multiple_structure(
35b9a80a 99 new external_single_structure(
100 array(
7b472b32 101 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
35b9a80a 102 'value' => new external_value(PARAM_RAW, 'The value of the preference')
103 )
fb79269b 104 ), 'User preferences', VALUE_OPTIONAL),
35b9a80a 105 'customfields' => new external_multiple_structure(
106 new external_single_structure(
107 array(
7b472b32 108 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
35b9a80a 109 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
110 )
6bb31e40 111 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
35b9a80a 112 )
113 )
114 )
115 )
116 );
625f0a24 117 }
118
d4e13355 119 /**
a2ed6e69 120 * Create one or more users.
5de592b1 121 *
a2ed6e69 122 * @throws invalid_parameter_exception
4615817d 123 * @param array $users An array of users to create.
71864f15 124 * @return array An array of arrays
4615817d 125 * @since Moodle 2.2
5de592b1 126 */
7b472b32 127 public static function create_users($users) {
ef22c1b6 128 global $CFG, $DB;
25eb9090 129 require_once($CFG->dirroot."/lib/weblib.php");
fb79269b 130 require_once($CFG->dirroot."/user/lib.php");
a2ed6e69 131 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
109b453b 132
a2ed6e69 133 // Ensure the current user is allowed to run this function.
43731030 134 $context = context_system::instance();
ef22c1b6 135 self::validate_context($context);
fb79269b 136 require_capability('moodle/user:create', $context);
d9ad0103 137
a2ed6e69
SH
138 // Do basic automatic PARAM checks on incoming data, using params description.
139 // If any problems are found then exceptions are thrown with helpful error messages.
140 $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
109b453b 141
bd3b3bba 142 $availableauths = core_component::get_plugin_list('auth');
a2ed6e69
SH
143 unset($availableauths['mnet']); // These would need mnethostid too.
144 unset($availableauths['webservice']); // We do not want new webservice users for now.
667b496a 145
bd3b3bba 146 $availablethemes = core_component::get_plugin_list('theme');
1f96e907 147 $availablelangs = get_string_manager()->get_list_of_translations();
5de592b1 148
38b76f3c 149 $transaction = $DB->start_delegated_transaction();
5de592b1 150
fb79269b 151 $userids = array();
7b472b32 152 foreach ($params['users'] as $user) {
a2ed6e69
SH
153 // Make sure that the username doesn't already exist.
154 if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
667b496a 155 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
ef22c1b6 156 }
ef22c1b6 157
a2ed6e69 158 // Make sure auth is valid.
667b496a
PS
159 if (empty($availableauths[$user['auth']])) {
160 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
ef22c1b6 161 }
162
a2ed6e69 163 // Make sure lang is valid.
667b496a
PS
164 if (empty($availablelangs[$user['lang']])) {
165 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
ef22c1b6 166 }
167
a2ed6e69
SH
168 // Make sure lang is valid.
169 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
170 // so no default value
fb79269b 171 // We need to test if the client sent it
a2ed6e69 172 // => !empty($user['theme']).
667b496a 173 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
ef22c1b6 174 }
5de592b1 175
fb79269b 176 $user['confirmed'] = true;
a1988186 177 $user['mnethostid'] = $CFG->mnet_localhost_id;
30a4fb1b 178
25eb9090 179 // Start of user info validation.
a2ed6e69 180 // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
25eb9090
AB
181 if (!validate_email($user['email'])) {
182 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
a2ed6e69 183 } else if ($DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
25eb9090
AB
184 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
185 }
186 // End of user info validation.
187
a2ed6e69 188 // Create the user data now!
2b55cb1b 189 $user['id'] = user_create_user($user, true, false);
25eb9090 190
a2ed6e69
SH
191 // Custom fields.
192 if (!empty($user['customfields'])) {
193 foreach ($user['customfields'] as $customfield) {
194 // Profile_save_data() saves profile file it's expecting a user with the correct id,
195 // and custom field to be named profile_field_"shortname".
196 $user["profile_field_".$customfield['type']] = $customfield['value'];
30a4fb1b 197 }
198 profile_save_data((object) $user);
199 }
667b496a 200
2b55cb1b
RT
201 // Trigger event.
202 \core\event\user_created::create_from_userid($user['id'])->trigger();
203
a2ed6e69 204 // Preferences.
d9ad0103 205 if (!empty($user['preferences'])) {
a2ed6e69
SH
206 foreach ($user['preferences'] as $preference) {
207 set_user_preference($preference['type'], $preference['value'], $user['id']);
d9ad0103 208 }
209 }
d4e13355 210
a2ed6e69 211 $userids[] = array('id' => $user['id'], 'username' => $user['username']);
ef22c1b6 212 }
213
38b76f3c 214 $transaction->allow_commit();
667b496a 215
fb79269b 216 return $userids;
ef22c1b6 217 }
218
a2ed6e69 219 /**
7b472b32 220 * Returns description of method result value
4615817d 221 *
7b472b32 222 * @return external_description
4615817d 223 * @since Moodle 2.2
7b472b32
PS
224 */
225 public static function create_users_returns() {
226 return new external_multiple_structure(
227 new external_single_structure(
228 array(
229 'id' => new external_value(PARAM_INT, 'user id'),
45b4464c 230 'username' => new external_value(PARAM_USERNAME, 'user name'),
7b472b32
PS
231 )
232 )
233 );
d4e13355 234 }
235
236
930680cb
PS
237 /**
238 * Returns description of method parameters
4615817d 239 *
930680cb 240 * @return external_function_parameters
4615817d 241 * @since Moodle 2.2
930680cb 242 */
d4e13355 243 public static function delete_users_parameters() {
930680cb
PS
244 return new external_function_parameters(
245 array(
246 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
247 )
248 );
d4e13355 249 }
930680cb 250
5d1017e1
JM
251 /**
252 * Delete users
4615817d 253 *
a2ed6e69 254 * @throws moodle_exception
5d1017e1 255 * @param array $userids
e6acc551 256 * @return null
4615817d 257 * @since Moodle 2.2
5d1017e1 258 */
38b76f3c 259 public static function delete_users($userids) {
b73a28be 260 global $CFG, $DB, $USER;
fb79269b 261 require_once($CFG->dirroot."/user/lib.php");
38b76f3c 262
a2ed6e69 263 // Ensure the current user is allowed to run this function.
43731030 264 $context = context_system::instance();
38b76f3c
PS
265 require_capability('moodle/user:delete', $context);
266 self::validate_context($context);
267
a2ed6e69 268 $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
38b76f3c
PS
269
270 $transaction = $DB->start_delegated_transaction();
38b76f3c
PS
271
272 foreach ($params['userids'] as $userid) {
a2ed6e69
SH
273 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
274 // Must not allow deleting of admins or self!!!
4f622c38
PS
275 if (is_siteadmin($user)) {
276 throw new moodle_exception('useradminodelete', 'error');
277 }
278 if ($USER->id == $user->id) {
279 throw new moodle_exception('usernotdeletederror', 'error');
b73a28be 280 }
fb79269b 281 user_delete_user($user);
38b76f3c
PS
282 }
283
284 $transaction->allow_commit();
285
286 return null;
ef22c1b6 287 }
930680cb 288
a2ed6e69 289 /**
930680cb 290 * Returns description of method result value
4615817d
JM
291 *
292 * @return null
293 * @since Moodle 2.2
930680cb 294 */
d4e13355 295 public static function delete_users_returns() {
930680cb 296 return null;
d4e13355 297 }
ef22c1b6 298
299
930680cb
PS
300 /**
301 * Returns description of method parameters
4615817d 302 *
930680cb 303 * @return external_function_parameters
4615817d 304 * @since Moodle 2.2
930680cb 305 */
d4e13355 306 public static function update_users_parameters() {
2336a843 307 return new external_function_parameters(
fb79269b 308 array(
309 'users' => new external_multiple_structure(
310 new external_single_structure(
311 array(
a2ed6e69
SH
312 'id' =>
313 new external_value(PARAM_INT, 'ID of the user'),
314 'username' =>
315 new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config.',
316 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
317 'password' =>
318 new external_value(PARAM_RAW, 'Plain text password consisting of any characters', VALUE_OPTIONAL,
319 '', NULL_NOT_ALLOWED),
320 'firstname' =>
321 new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL, '',
322 NULL_NOT_ALLOWED),
323 'lastname' =>
324 new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
325 'email' =>
326 new external_value(PARAM_EMAIL, 'A valid and unique email address', VALUE_OPTIONAL, '',
327 NULL_NOT_ALLOWED),
328 'auth' =>
329 new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL, '',
330 NULL_NOT_ALLOWED),
331 'idnumber' =>
332 new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution',
333 VALUE_OPTIONAL),
334 'lang' =>
335 new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server',
336 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
337 'calendartype' =>
338 new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server',
339 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
340 'theme' =>
341 new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server',
342 VALUE_OPTIONAL),
343 'timezone' =>
344 new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default',
345 VALUE_OPTIONAL),
346 'mailformat' =>
347 new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc',
348 VALUE_OPTIONAL),
349 'description' =>
350 new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
351 'city' =>
352 new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
353 'country' =>
354 new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
355 'firstnamephonetic' =>
356 new external_value(PARAM_NOTAGS, 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
357 'lastnamephonetic' =>
358 new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
359 'middlename' =>
360 new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
361 'alternatename' =>
362 new external_value(PARAM_NOTAGS, 'The alternate name of the user', VALUE_OPTIONAL),
363 'customfields' => new external_multiple_structure(
fb79269b 364 new external_single_structure(
365 array(
366 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
367 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
368 )
6bb31e40 369 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
d9ad0103 370 'preferences' => new external_multiple_structure(
371 new external_single_structure(
372 array(
373 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
374 'value' => new external_value(PARAM_RAW, 'The value of the preference')
375 )
376 ), 'User preferences', VALUE_OPTIONAL),
fb79269b 377 )
378 )
379 )
380 )
381 );
d4e13355 382 }
38b76f3c 383
5d1017e1
JM
384 /**
385 * Update users
4615817d 386 *
5d1017e1 387 * @param array $users
e6acc551 388 * @return null
4615817d 389 * @since Moodle 2.2
5d1017e1 390 */
38b76f3c
PS
391 public static function update_users($users) {
392 global $CFG, $DB;
fb79269b 393 require_once($CFG->dirroot."/user/lib.php");
a2ed6e69 394 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
38b76f3c 395
a2ed6e69 396 // Ensure the current user is allowed to run this function.
43731030 397 $context = context_system::instance();
38b76f3c
PS
398 require_capability('moodle/user:update', $context);
399 self::validate_context($context);
400
a2ed6e69 401 $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
38b76f3c
PS
402
403 $transaction = $DB->start_delegated_transaction();
404
405 foreach ($params['users'] as $user) {
2b55cb1b 406 user_update_user($user, true, false);
a2ed6e69
SH
407 // Update user custom fields.
408 if (!empty($user['customfields'])) {
9baf3a7b 409
a2ed6e69
SH
410 foreach ($user['customfields'] as $customfield) {
411 // Profile_save_data() saves profile file it's expecting a user with the correct id,
412 // and custom field to be named profile_field_"shortname".
413 $user["profile_field_".$customfield['type']] = $customfield['value'];
9baf3a7b 414 }
415 profile_save_data((object) $user);
416 }
d9ad0103 417
2b55cb1b
RT
418 // Trigger event.
419 \core\event\user_updated::create_from_userid($user['id'])->trigger();
420
a2ed6e69 421 // Preferences.
d9ad0103 422 if (!empty($user['preferences'])) {
a2ed6e69
SH
423 foreach ($user['preferences'] as $preference) {
424 set_user_preference($preference['type'], $preference['value'], $user['id']);
d9ad0103 425 }
426 }
38b76f3c
PS
427 }
428
429 $transaction->allow_commit();
430
431 return null;
ef22c1b6 432 }
930680cb 433
a2ed6e69 434 /**
930680cb 435 * Returns description of method result value
4615817d
JM
436 *
437 * @return null
438 * @since Moodle 2.2
930680cb 439 */
d4e13355 440 public static function update_users_returns() {
930680cb 441 return null;
d4e13355 442 }
443
a2ed6e69
SH
444 /**
445 * Returns description of method parameters
446 *
447 * @return external_function_parameters
448 * @since Moodle 2.4
449 */
c70b9853 450 public static function get_users_by_field_parameters() {
86477112
FS
451 return new external_function_parameters(
452 array(
c70b9853
JM
453 'field' => new external_value(PARAM_ALPHA, 'the search field can be
454 \'id\' or \'idnumber\' or \'username\' or \'email\''),
455 'values' => new external_multiple_structure(
456 new external_value(PARAM_RAW, 'the value to match'))
86477112
FS
457 )
458 );
459 }
460
461 /**
c70b9853 462 * Get user information for a unique field.
86477112 463 *
a2ed6e69
SH
464 * @throws coding_exception
465 * @throws invalid_parameter_exception
c70b9853
JM
466 * @param string $field
467 * @param array $values
468 * @return array An array of arrays containg user profiles.
469 * @since Moodle 2.4
86477112 470 */
c70b9853 471 public static function get_users_by_field($field, $values) {
86477112
FS
472 global $CFG, $USER, $DB;
473 require_once($CFG->dirroot . "/user/lib.php");
474
c70b9853
JM
475 $params = self::validate_parameters(self::get_users_by_field_parameters(),
476 array('field' => $field, 'values' => $values));
477
478 // This array will keep all the users that are allowed to be searched,
479 // according to the current user's privileges.
480 $cleanedvalues = array();
481
482 switch ($field) {
483 case 'id':
484 $paramtype = PARAM_INT;
485 break;
486 case 'idnumber':
487 $paramtype = PARAM_RAW;
488 break;
489 case 'username':
ec80bc6b 490 $paramtype = PARAM_RAW;
c70b9853
JM
491 break;
492 case 'email':
493 $paramtype = PARAM_EMAIL;
494 break;
495 default:
496 throw new coding_exception('invalid field parameter',
497 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
86477112
FS
498 }
499
a2ed6e69 500 // Clean the values.
c70b9853
JM
501 foreach ($values as $value) {
502 $cleanedvalue = clean_param($value, $paramtype);
503 if ( $value != $cleanedvalue) {
504 throw new invalid_parameter_exception('The field \'' . $field .
505 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
506 }
507 $cleanedvalues[] = $cleanedvalue;
86477112
FS
508 }
509
a2ed6e69 510 // Retrieve the users.
c70b9853 511 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
86477112 512
a2ed6e69 513 // Finally retrieve each users information.
c70b9853 514 $returnedusers = array();
86477112 515 foreach ($users as $user) {
86477112
FS
516 $userdetails = user_get_user_details_courses($user);
517
a2ed6e69
SH
518 // Return the user only if the searched field is returned.
519 // Otherwise it means that the $USER was not allowed to search the returned user.
c70b9853
JM
520 if (!empty($userdetails) and !empty($userdetails[$field])) {
521 $returnedusers[] = $userdetails;
86477112
FS
522 }
523 }
86477112 524
c70b9853 525 return $returnedusers;
86477112
FS
526 }
527
528 /**
529 * Returns description of method result value
530 *
c70b9853
JM
531 * @return external_multiple_structure
532 * @since Moodle 2.4
86477112 533 */
c70b9853 534 public static function get_users_by_field_returns() {
85e6bf8e 535 return new external_multiple_structure(self::user_description());
b0365ea5
JM
536 }
537
538
539 /**
bb1105ae 540 * Returns description of get_users() parameters.
b0365ea5
JM
541 *
542 * @return external_function_parameters
bb1105ae 543 * @since Moodle 2.5
b0365ea5
JM
544 */
545 public static function get_users_parameters() {
546 return new external_function_parameters(
547 array(
548 'criteria' => new external_multiple_structure(
549 new external_single_structure(
550 array(
bb1105ae
JM
551 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
552 "id" (int) matching user id,
553 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
554 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
555 "idnumber" (string) matching user idnumber,
556 "username" (string) matching user username,
557 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
558 "auth" (string) matching user auth plugin'),
559 'value' => new external_value(PARAM_RAW, 'the value to search')
b0365ea5
JM
560 )
561 ), 'the key/value pairs to be considered in user search. Values can not be empty.
bb1105ae 562 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
85e6bf8e 563 key occurences are forbidden.
0c34e803 564 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
85e6bf8e
JM
565 the search is still executed on the valid criterias.
566 You can search without criteria, but the function is not designed for it.
567 It could very slow or timeout. The function is designed to search some specific users.'
86477112
FS
568 )
569 )
570 );
571 }
572
b0365ea5 573 /**
bb1105ae 574 * Retrieve matching user.
b0365ea5 575 *
a2ed6e69 576 * @throws moodle_exception
bb1105ae
JM
577 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
578 * @return array An array of arrays containing user profiles.
579 * @since Moodle 2.5
b0365ea5
JM
580 */
581 public static function get_users($criteria = array()) {
582 global $CFG, $USER, $DB;
583
584 require_once($CFG->dirroot . "/user/lib.php");
585
586 $params = self::validate_parameters(self::get_users_parameters(),
587 array('criteria' => $criteria));
588
bb1105ae 589 // Validate the criteria and retrieve the users.
b0365ea5
JM
590 $users = array();
591 $warnings = array();
b0365ea5 592 $sqlparams = array();
85e6bf8e
JM
593 $usedkeys = array();
594
595 // Do not retrieve deleted users.
596 $sql = ' deleted = 0';
b0365ea5 597
0c34e803 598 foreach ($params['criteria'] as $criteriaindex => $criteria) {
85e6bf8e
JM
599
600 // Check that the criteria has never been used.
601 if (array_key_exists($criteria['key'], $usedkeys)) {
602 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
603 } else {
604 $usedkeys[$criteria['key']] = true;
605 }
606
0c34e803 607 $invalidcriteria = false;
bb1105ae 608 // Clean the parameters.
b0365ea5
JM
609 $paramtype = PARAM_RAW;
610 switch ($criteria['key']) {
611 case 'id':
612 $paramtype = PARAM_INT;
613 break;
614 case 'idnumber':
615 $paramtype = PARAM_RAW;
616 break;
617 case 'username':
ec80bc6b 618 $paramtype = PARAM_RAW;
b0365ea5
JM
619 break;
620 case 'email':
bb1105ae 621 // We use PARAM_RAW to allow searches with %.
b0365ea5
JM
622 $paramtype = PARAM_RAW;
623 break;
624 case 'auth':
625 $paramtype = PARAM_AUTH;
626 break;
627 case 'lastname':
628 case 'firstname':
629 $paramtype = PARAM_TEXT;
630 break;
631 default:
bb1105ae
JM
632 // Send back a warning that this search key is not supported in this version.
633 // This warning will make the function extandable without breaking clients.
b0365ea5 634 $warnings[] = array(
0c34e803 635 'item' => $criteria['key'],
b0365ea5 636 'warningcode' => 'invalidfieldparameter',
a2ed6e69
SH
637 'message' =>
638 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
b0365ea5 639 );
0c34e803
JM
640 // Do not add this invalid criteria to the created SQL request.
641 $invalidcriteria = true;
642 unset($params['criteria'][$criteriaindex]);
643 break;
b0365ea5 644 }
b0365ea5 645
0c34e803
JM
646 if (!$invalidcriteria) {
647 $cleanedvalue = clean_param($criteria['value'], $paramtype);
b0365ea5 648
85e6bf8e 649 $sql .= ' AND ';
0c34e803
JM
650
651 // Create the SQL.
652 switch ($criteria['key']) {
653 case 'id':
654 case 'idnumber':
655 case 'username':
656 case 'auth':
657 $sql .= $criteria['key'] . ' = :' . $criteria['key'];
658 $sqlparams[$criteria['key']] = $cleanedvalue;
659 break;
660 case 'email':
661 case 'lastname':
662 case 'firstname':
663 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
664 $sqlparams[$criteria['key']] = $cleanedvalue;
665 break;
666 default:
667 break;
668 }
b0365ea5
JM
669 }
670 }
671
672 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
673
bb1105ae 674 // Finally retrieve each users information.
b0365ea5
JM
675 $returnedusers = array();
676 foreach ($users as $user) {
b0365ea5
JM
677 $userdetails = user_get_user_details_courses($user);
678
679 // Return the user only if all the searched fields are returned.
680 // Otherwise it means that the $USER was not allowed to search the returned user.
681 if (!empty($userdetails)) {
682 $validuser = true;
683
a2ed6e69 684 foreach ($params['criteria'] as $criteria) {
b0365ea5
JM
685 if (empty($userdetails[$criteria['key']])) {
686 $validuser = false;
687 }
688 }
689
690 if ($validuser) {
691 $returnedusers[] = $userdetails;
692 }
693 }
694 }
695
696 return array('users' => $returnedusers, 'warnings' => $warnings);
697 }
698
699 /**
bb1105ae 700 * Returns description of get_users result value.
b0365ea5
JM
701 *
702 * @return external_description
bb1105ae 703 * @since Moodle 2.5
b0365ea5
JM
704 */
705 public static function get_users_returns() {
706 return new external_single_structure(
707 array('users' => new external_multiple_structure(
85e6bf8e 708 self::user_description()
b0365ea5 709 ),
bb1105ae 710 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
b0365ea5
JM
711 )
712 );
713 }
714
7b472b32
PS
715 /**
716 * Returns description of method parameters
4615817d 717 *
7b472b32 718 * @return external_function_parameters
4615817d 719 * @since Moodle 2.2
41f5285f
JM
720 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
721 * @see core_user_external::get_users_by_field_parameters()
7b472b32 722 */
fb79269b 723 public static function get_users_by_id_parameters() {
71864f15 724 return new external_function_parameters(
a2ed6e69
SH
725 array(
726 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
727 )
71864f15 728 );
d4e13355 729 }
7b472b32 730
71864f15
PS
731 /**
732 * Get user information
b4c74367
JM
733 * - This function is matching the permissions of /user/profil.php
734 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
735 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
4615817d 736 *
71864f15
PS
737 * @param array $userids array of user ids
738 * @return array An array of arrays describing users
4615817d 739 * @since Moodle 2.2
41f5285f
JM
740 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
741 * @see core_user_external::get_users_by_field()
71864f15 742 */
fb79269b 743 public static function get_users_by_id($userids) {
b4c74367 744 global $CFG, $USER, $DB;
109b453b 745 require_once($CFG->dirroot . "/user/lib.php");
fb79269b 746
109b453b 747 $params = self::validate_parameters(self::get_users_by_id_parameters(),
a2ed6e69 748 array('userids' => $userids));
5de592b1 749
0d352dbc 750 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2e4c0c91
FM
751 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
752 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
753 $params['contextlevel'] = CONTEXT_USER;
ea4e96c2
DC
754 $usersql = "SELECT u.* $uselect
755 FROM {user} u $ujoin
756 WHERE u.id $sqluserids";
757 $users = $DB->get_recordset_sql($usersql, $params);
d4e13355 758
109b453b 759 $result = array();
0601e0ee 760 $hasuserupdatecap = has_capability('moodle/user:update', context_system::instance());
d4e13355 761 foreach ($users as $user) {
ea4e96c2
DC
762 if (!empty($user->deleted)) {
763 continue;
764 }
db314f34 765 context_helper::preload_from_record($user);
43731030 766 $usercontext = context_user::instance($user->id, IGNORE_MISSING);
01479290 767 self::validate_context($usercontext);
b4c74367
JM
768 $currentuser = ($user->id == $USER->id);
769
01479290 770 if ($userarray = user_get_user_details($user)) {
a2ed6e69 771 // Fields matching permissions from /user/editadvanced.php.
01479290
DC
772 if ($currentuser or $hasuserupdatecap) {
773 $userarray['auth'] = $user->auth;
774 $userarray['confirmed'] = $user->confirmed;
775 $userarray['idnumber'] = $user->idnumber;
776 $userarray['lang'] = $user->lang;
777 $userarray['theme'] = $user->theme;
778 $userarray['timezone'] = $user->timezone;
779 $userarray['mailformat'] = $user->mailformat;
b4c74367 780 }
01479290 781 $result[] = $userarray;
ea4e96c2 782 }
fb79269b 783 }
ea4e96c2 784 $users->close();
71864f15
PS
785
786 return $result;
d4e13355 787 }
7b472b32 788
109b453b 789 /**
7b472b32 790 * Returns description of method result value
4615817d 791 *
7b472b32 792 * @return external_description
4615817d 793 * @since Moodle 2.2
41f5285f
JM
794 * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
795 * @see core_user_external::get_users_by_field_returns()
7b472b32 796 */
fb79269b 797 public static function get_users_by_id_returns() {
bb1105ae
JM
798 $additionalfields = array (
799 'enrolledcourses' => new external_multiple_structure(
503c14a6
DW
800 new external_single_structure(
801 array(
802 'id' => new external_value(PARAM_INT, 'Id of the course'),
803 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
804 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
805 )
806 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL));
85e6bf8e 807 return new external_multiple_structure(self::user_description($additionalfields));
ea4e96c2 808 }
bb1105ae 809
5bb0ee2a
DM
810 /**
811 * Marking the method as deprecated.
812 *
813 * @return bool
814 */
815 public static function get_users_by_id_is_deprecated() {
816 return true;
817 }
818
ea4e96c2
DC
819 /**
820 * Returns description of method parameters
4615817d 821 *
ea4e96c2 822 * @return external_function_parameters
4615817d 823 * @since Moodle 2.2
ea4e96c2 824 */
5d1017e1 825 public static function get_course_user_profiles_parameters() {
ea4e96c2
DC
826 return new external_function_parameters(
827 array(
828 'userlist' => new external_multiple_structure(
829 new external_single_structure(
830 array(
831 'userid' => new external_value(PARAM_INT, 'userid'),
832 'courseid' => new external_value(PARAM_INT, 'courseid'),
109b453b 833 )
ea4e96c2 834 )
71864f15 835 )
ea4e96c2
DC
836 )
837 );
838 }
839
840 /**
841 * Get course participant's details
4615817d 842 *
ea4e96c2
DC
843 * @param array $userlist array of user ids and according course ids
844 * @return array An array of arrays describing course participants
4615817d 845 * @since Moodle 2.2
ea4e96c2 846 */
5d1017e1 847 public static function get_course_user_profiles($userlist) {
ea4e96c2
DC
848 global $CFG, $USER, $DB;
849 require_once($CFG->dirroot . "/user/lib.php");
a2ed6e69 850 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
ea4e96c2
DC
851
852 $userids = array();
853 $courseids = array();
854 foreach ($params['userlist'] as $value) {
855 $userids[] = $value['userid'];
856 $courseids[$value['userid']] = $value['courseid'];
857 }
858
a2ed6e69 859 // Cache all courses.
ea4e96c2 860 $courses = array();
0d352dbc 861 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
2e4c0c91
FM
862 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
863 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
864 $params['contextlevel'] = CONTEXT_COURSE;
ecfc06d8 865 $coursesql = "SELECT c.* $cselect
ea4e96c2
DC
866 FROM {course} c $cjoin
867 WHERE c.id $sqlcourseids";
868 $rs = $DB->get_recordset_sql($coursesql, $params);
869 foreach ($rs as $course) {
a2ed6e69 870 // Adding course contexts to cache.
db314f34 871 context_helper::preload_from_record($course);
a2ed6e69 872 // Cache courses.
ea4e96c2
DC
873 $courses[$course->id] = $course;
874 }
875 $rs->close();
876
0d352dbc 877 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2e4c0c91
FM
878 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
879 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
880 $params['contextlevel'] = CONTEXT_USER;
ea4e96c2
DC
881 $usersql = "SELECT u.* $uselect
882 FROM {user} u $ujoin
883 WHERE u.id $sqluserids";
884 $users = $DB->get_recordset_sql($usersql, $params);
885 $result = array();
886 foreach ($users as $user) {
887 if (!empty($user->deleted)) {
888 continue;
889 }
db314f34 890 context_helper::preload_from_record($user);
ea4e96c2 891 $course = $courses[$courseids[$user->id]];
43731030 892 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
ea4e96c2 893 self::validate_context($context);
01479290
DC
894 if ($userarray = user_get_user_details($user, $course)) {
895 $result[] = $userarray;
ea4e96c2 896 }
01479290 897 }
ea4e96c2 898
01479290 899 $users->close();
ea4e96c2 900
01479290
DC
901 return $result;
902 }
ea4e96c2 903
01479290
DC
904 /**
905 * Returns description of method result value
4615817d 906 *
01479290 907 * @return external_description
4615817d 908 * @since Moodle 2.2
01479290 909 */
5d1017e1 910 public static function get_course_user_profiles_returns() {
b0365ea5 911 $additionalfields = array(
a2ed6e69
SH
912 'groups' => new external_multiple_structure(
913 new external_single_structure(
914 array(
915 'id' => new external_value(PARAM_INT, 'group id'),
916 'name' => new external_value(PARAM_RAW, 'group name'),
917 'description' => new external_value(PARAM_RAW, 'group description'),
918 'descriptionformat' => new external_format_value('description'),
919 )
920 ), 'user groups', VALUE_OPTIONAL),
921 'roles' => new external_multiple_structure(
922 new external_single_structure(
923 array(
924 'roleid' => new external_value(PARAM_INT, 'role id'),
925 'name' => new external_value(PARAM_RAW, 'role name'),
926 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
927 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
928 )
929 ), 'user roles', VALUE_OPTIONAL),
930 'enrolledcourses' => new external_multiple_structure(
931 new external_single_structure(
932 array(
933 'id' => new external_value(PARAM_INT, 'Id of the course'),
934 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
935 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
936 )
937 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
938 );
b0365ea5 939
85e6bf8e 940 return new external_multiple_structure(self::user_description($additionalfields));
b0365ea5
JM
941 }
942
943 /**
944 * Create user return value description.
945 *
bb1105ae 946 * @param array $additionalfields some additional field
b0365ea5
JM
947 * @return single_structure_description
948 */
bb1105ae 949 public static function user_description($additionalfields = array()) {
b0365ea5 950 $userfields = array(
a2ed6e69
SH
951 'id' => new external_value(PARAM_INT, 'ID of the user'),
952 'username' => new external_value(PARAM_RAW, 'The username', VALUE_OPTIONAL),
953 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
954 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
955 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
956 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
957 'address' => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL),
958 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
959 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
960 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
961 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
962 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
963 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
964 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
965 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
966 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
967 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
968 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
969 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
970 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
971 'auth' => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
972 'confirmed' => new external_value(PARAM_INT, 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
973 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
974 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
975 'theme' => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
976 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
977 'mailformat' => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
978 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
979 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
980 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
981 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
982 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
983 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
984 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
985 'customfields' => new external_multiple_structure(
986 new external_single_structure(
987 array(
988 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
989 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
990 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
991 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
992 )
993 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
994 'preferences' => new external_multiple_structure(
995 new external_single_structure(
996 array(
997 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
998 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
999 )
1000 ), 'Users preferences', VALUE_OPTIONAL)
1001 );
b0365ea5
JM
1002 if (!empty($additionalfields)) {
1003 $userfields = array_merge($userfields, $additionalfields);
1004 }
1005 return new external_single_structure($userfields);
01479290 1006 }
b0365ea5 1007
9ffa4cb3
DW
1008 /**
1009 * Returns description of method parameters
1010 *
1011 * @return external_function_parameters
1012 * @since Moodle 2.6
1013 */
1014 public static function add_user_private_files_parameters() {
1015 return new external_function_parameters(
1016 array(
1017 'draftid' => new external_value(PARAM_INT, 'draft area id')
1018 )
1019 );
1020 }
1021
1022 /**
1023 * Copy files from a draft area to users private files area.
1024 *
a2ed6e69 1025 * @throws invalid_parameter_exception
9ffa4cb3
DW
1026 * @param int $draftid Id of a draft area containing files.
1027 * @return array An array of warnings
1028 * @since Moodle 2.6
1029 */
1030 public static function add_user_private_files($draftid) {
1031 global $CFG, $USER, $DB;
1032
1033 require_once($CFG->dirroot . "/user/lib.php");
a2ed6e69 1034 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
9ffa4cb3
DW
1035
1036 if (isguestuser()) {
1037 throw new invalid_parameter_exception('Guest users cannot upload files');
1038 }
1039
1040 $context = context_user::instance($USER->id);
1041 require_capability('moodle/user:manageownfiles', $context);
1042
1043 $maxbytes = $CFG->userquota;
1044 $maxareabytes = $CFG->userquota;
1045 if (has_capability('moodle/user:ignoreuserquota', $context)) {
1046 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1047 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1048 }
1049
1050 $options = array('subdirs' => 1,
1051 'maxbytes' => $maxbytes,
1052 'maxfiles' => -1,
1053 'accepted_types' => '*',
1054 'areamaxbytes' => $maxareabytes);
1055
1056 file_save_draft_area_files($draftid, $context->id, 'user', 'private', 0, $options);
1057
1058 return null;
1059 }
1060
1061 /**
1062 * Returns description of method result value
1063 *
1064 * @return external_description
1065 * @since Moodle 2.2
1066 */
1067 public static function add_user_private_files_returns() {
1068 return null;
1069 }
1070
6a403810
JL
1071 /**
1072 * Returns description of method parameters.
1073 *
1074 * @return external_function_parameters
1075 * @since Moodle 2.6
1076 */
1077 public static function add_user_device_parameters() {
1078 return new external_function_parameters(
1079 array(
1080 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1081 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1082 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1083 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1084 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1085 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1086 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
1087 )
1088 );
1089 }
1090
1091 /**
1092 * Add a user device in Moodle database (for PUSH notifications usually).
1093 *
a2ed6e69 1094 * @throws moodle_exception
6a403810
JL
1095 * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1096 * @param string $name The device name, occam or iPhone etc.
1097 * @param string $model The device model Nexus4 or iPad1.1 etc.
1098 * @param string $platform The device platform iOs or Android etc.
1099 * @param string $version The device version 6.1.2 or 4.2.2 etc.
1100 * @param string $pushid The device PUSH token/key/identifier/registration id.
1101 * @param string $uuid The device UUID.
1102 * @return array List of possible warnings.
1103 * @since Moodle 2.6
1104 */
1105 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1106 global $CFG, $USER, $DB;
1107 require_once($CFG->dirroot . "/user/lib.php");
1108
1109 $params = self::validate_parameters(self::add_user_device_parameters(),
1110 array('appid' => $appid,
1111 'name' => $name,
1112 'model' => $model,
1113 'platform' => $platform,
1114 'version' => $version,
1115 'pushid' => $pushid,
1116 'uuid' => $uuid
1117 ));
1118
1119 $warnings = array();
1120
1121 // Prevent duplicate keys for users.
1122 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1123 $warnings['warning'][] = array(
1124 'item' => $params['pushid'],
1125 'warningcode' => 'existingkeyforthisuser',
1126 'message' => 'This key is already stored for this user'
1127 );
1128 return $warnings;
1129 }
1130
6a403810
JL
1131 $userdevice = new stdclass;
1132 $userdevice->userid = $USER->id;
1133 $userdevice->appid = $params['appid'];
1134 $userdevice->name = $params['name'];
1135 $userdevice->model = $params['model'];
1136 $userdevice->platform = $params['platform'];
1137 $userdevice->version = $params['version'];
1138 $userdevice->pushid = $params['pushid'];
1139 $userdevice->uuid = $params['uuid'];
1140 $userdevice->timecreated = time();
1141 $userdevice->timemodified = $userdevice->timecreated;
1142
1143 if (!$DB->insert_record('user_devices', $userdevice)) {
1144 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1145 }
1146
1147 return $warnings;
1148 }
1149
1150 /**
1151 * Returns description of method result value.
1152 *
1153 * @return external_multiple_structure
1154 * @since Moodle 2.6
1155 */
1156 public static function add_user_device_returns() {
1157 return new external_multiple_structure(
1158 new external_warnings()
1159 );
1160 }
1161
3221718e
JL
1162 /**
1163 * Returns description of method parameters.
1164 *
1165 * @return external_function_parameters
1166 * @since Moodle 2.9
1167 */
1168 public static function remove_user_device_parameters() {
1169 return new external_function_parameters(
1170 array(
1171 'uuid' => new external_value(PARAM_RAW, 'the device UUID'),
1172 'appid' => new external_value(PARAM_NOTAGS,
1173 'the app id, if empty devices matching the UUID for the user will be removed',
1174 VALUE_DEFAULT, ''),
1175 )
1176 );
1177 }
1178
1179 /**
1180 * Remove a user device from the Moodle database (for PUSH notifications usually).
1181 *
1182 * @param string $uuid The device UUID.
1183 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1184 * @return array List of possible warnings and removal status.
1185 * @since Moodle 2.9
1186 */
1187 public static function remove_user_device($uuid, $appid = "") {
1188 global $CFG;
1189 require_once($CFG->dirroot . "/user/lib.php");
1190
1191 $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1192
1193 $context = context_system::instance();
1194 self::validate_context($context);
1195
1196 // Warnings array, it can be empty at the end but is mandatory.
1197 $warnings = array();
1198
1199 $removed = user_remove_user_device($params['uuid'], $params['appid']);
1200
1201 if (!$removed) {
1202 $warnings[] = array(
1203 'item' => $params['uuid'],
1204 'warningcode' => 'devicedoesnotexist',
1205 'message' => 'The device doesn\'t exists in the database'
1206 );
1207 }
1208
1209 $result = array(
1210 'removed' => $removed,
1211 'warnings' => $warnings
1212 );
1213
1214 return $result;
1215 }
1216
1217 /**
1218 * Returns description of method result value.
1219 *
1220 * @return external_multiple_structure
1221 * @since Moodle 2.9
1222 */
1223 public static function remove_user_device_returns() {
1224 return new external_single_structure(
1225 array(
1226 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
1227 'warnings' => new external_warnings(),
1228 )
1229 );
1230 }
1231
5d1017e1
JM
1232}
1233
4615817d 1234 /**
a2ed6e69
SH
1235 * Deprecated user external functions
1236 *
1237 * @package core_user
1238 * @copyright 2009 Petr Skodak
1239 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1240 * @since Moodle 2.0
1241 * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
1242 * @see core_user_external
1243 */
5d1017e1
JM
1244class moodle_user_external extends external_api {
1245
1246 /**
1247 * Returns description of method parameters
4615817d 1248 *
5d1017e1 1249 * @return external_function_parameters
4615817d
JM
1250 * @since Moodle 2.0
1251 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1252 * @see core_user_external::create_users_parameters()
5d1017e1
JM
1253 */
1254 public static function create_users_parameters() {
1255 return core_user_external::create_users_parameters();
1256 }
1257
1258 /**
1259 * Create one or more users
4615817d 1260 *
5d1017e1
JM
1261 * @param array $users An array of users to create.
1262 * @return array An array of arrays
4615817d
JM
1263 * @since Moodle 2.0
1264 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1265 * @see core_user_external::create_users()
5d1017e1
JM
1266 */
1267 public static function create_users($users) {
1268 return core_user_external::create_users($users);
1269 }
1270
a2ed6e69 1271 /**
5d1017e1 1272 * Returns description of method result value
4615817d 1273 *
5d1017e1 1274 * @return external_description
4615817d
JM
1275 * @since Moodle 2.0
1276 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1277 * @see core_user_external::create_users_returns()
5d1017e1
JM
1278 */
1279 public static function create_users_returns() {
1280 return core_user_external::create_users_returns();
1281 }
1282
3c1aa6fd
DM
1283 /**
1284 * Marking the method as deprecated.
1285 *
1286 * @return bool
1287 */
1288 public static function create_users_is_deprecated() {
1289 return true;
1290 }
5d1017e1
JM
1291
1292 /**
1293 * Returns description of method parameters
4615817d 1294 *
5d1017e1 1295 * @return external_function_parameters
4615817d
JM
1296 * @since Moodle 2.0
1297 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1298 * @see core_user_external::delete_users_parameters()
5d1017e1
JM
1299 */
1300 public static function delete_users_parameters() {
1301 return core_user_external::delete_users_parameters();
1302 }
1303
1304 /**
1305 * Delete users
4615817d 1306 *
5d1017e1 1307 * @param array $userids
e6acc551 1308 * @return null
4615817d
JM
1309 * @since Moodle 2.0
1310 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1311 * @see core_user_external::delete_users()
5d1017e1
JM
1312 */
1313 public static function delete_users($userids) {
1314 return core_user_external::delete_users($userids);
1315 }
1316
a2ed6e69 1317 /**
5d1017e1 1318 * Returns description of method result value
4615817d
JM
1319 *
1320 * @return null
1321 * @since Moodle 2.0
1322 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1323 * @see core_user_external::delete_users_returns()
5d1017e1
JM
1324 */
1325 public static function delete_users_returns() {
1326 return core_user_external::delete_users_returns();
1327 }
1328
3c1aa6fd
DM
1329 /**
1330 * Marking the method as deprecated.
1331 *
1332 * @return bool
1333 */
1334 public static function delete_users_is_deprecated() {
1335 return true;
1336 }
5d1017e1
JM
1337
1338 /**
1339 * Returns description of method parameters
4615817d 1340 *
5d1017e1 1341 * @return external_function_parameters
4615817d
JM
1342 * @since Moodle 2.0
1343 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1344 * @see core_user_external::update_users_parameters()
5d1017e1
JM
1345 */
1346 public static function update_users_parameters() {
1347 return core_user_external::update_users_parameters();
1348 }
1349
1350 /**
1351 * Update users
4615817d 1352 *
5d1017e1 1353 * @param array $users
e6acc551 1354 * @return null
4615817d
JM
1355 * @since Moodle 2.0
1356 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1357 * @see core_user_external::update_users()
5d1017e1
JM
1358 */
1359 public static function update_users($users) {
1360 return core_user_external::update_users($users);
1361 }
1362
a2ed6e69 1363 /**
5d1017e1 1364 * Returns description of method result value
4615817d
JM
1365 *
1366 * @return null
1367 * @since Moodle 2.0
1368 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1369 * @see core_user_external::update_users_returns()
5d1017e1
JM
1370 */
1371 public static function update_users_returns() {
1372 return core_user_external::update_users_returns();
1373 }
1374
3c1aa6fd
DM
1375 /**
1376 * Marking the method as deprecated.
1377 *
1378 * @return bool
1379 */
1380 public static function update_users_is_deprecated() {
1381 return true;
1382 }
1383
5d1017e1
JM
1384 /**
1385 * Returns description of method parameters
4615817d 1386 *
5d1017e1 1387 * @return external_function_parameters
4615817d
JM
1388 * @since Moodle 2.0
1389 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1390 * @see core_user_external::get_users_by_id_parameters()
5d1017e1
JM
1391 */
1392 public static function get_users_by_id_parameters() {
1393 return core_user_external::get_users_by_id_parameters();
1394 }
1395
1396 /**
1397 * Get user information
1398 * - This function is matching the permissions of /user/profil.php
1399 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
1400 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
4615817d 1401 *
5d1017e1
JM
1402 * @param array $userids array of user ids
1403 * @return array An array of arrays describing users
4615817d
JM
1404 * @since Moodle 2.0
1405 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1406 * @see core_user_external::get_users_by_id()
5d1017e1
JM
1407 */
1408 public static function get_users_by_id($userids) {
1409 return core_user_external::get_users_by_id($userids);
1410 }
1411
1412 /**
1413 * Returns description of method result value
4615817d 1414 *
5d1017e1 1415 * @return external_description
4615817d
JM
1416 * @since Moodle 2.0
1417 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1418 * @see core_user_external::get_users_by_id_returns()
5d1017e1
JM
1419 */
1420 public static function get_users_by_id_returns() {
bb1105ae 1421 return core_user_external::get_users_by_id_returns();
5d1017e1 1422 }
3c1aa6fd
DM
1423
1424 /**
1425 * Marking the method as deprecated.
1426 *
1427 * @return bool
1428 */
1429 public static function get_users_by_id_is_deprecated() {
1430 return true;
1431 }
1432
5d1017e1
JM
1433 /**
1434 * Returns description of method parameters
4615817d 1435 *
5d1017e1 1436 * @return external_function_parameters
4615817d
JM
1437 * @since Moodle 2.1
1438 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1439 * @see core_user_external::get_course_user_profiles_parameters()
5d1017e1
JM
1440 */
1441 public static function get_course_participants_by_id_parameters() {
1442 return core_user_external::get_course_user_profiles_parameters();
1443 }
1444
1445 /**
1446 * Get course participant's details
4615817d 1447 *
5d1017e1
JM
1448 * @param array $userlist array of user ids and according course ids
1449 * @return array An array of arrays describing course participants
4615817d
JM
1450 * @since Moodle 2.1
1451 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1452 * @see core_user_external::get_course_user_profiles()
5d1017e1
JM
1453 */
1454 public static function get_course_participants_by_id($userlist) {
1455 return core_user_external::get_course_user_profiles($userlist);
1456 }
1457
1458 /**
1459 * Returns description of method result value
4615817d 1460 *
5d1017e1 1461 * @return external_description
4615817d
JM
1462 * @since Moodle 2.1
1463 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1464 * @see core_user_external::get_course_user_profiles_returns()
5d1017e1
JM
1465 */
1466 public static function get_course_participants_by_id_returns() {
1467 return core_user_external::get_course_user_profiles_returns();
1468 }
ea4e96c2 1469
3c1aa6fd
DM
1470 /**
1471 * Marking the method as deprecated.
1472 *
1473 * @return bool
1474 */
1475 public static function get_course_participants_by_id_is_deprecated() {
1476 return true;
1477 }
1478
01479290
DC
1479 /**
1480 * Returns description of method parameters
4615817d 1481 *
01479290 1482 * @return external_function_parameters
4615817d
JM
1483 * @since Moodle 2.1
1484 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1485 * @see core_enrol_external::get_enrolled_users_parameters()
01479290
DC
1486 */
1487 public static function get_users_by_courseid_parameters() {
5d1017e1
JM
1488 global $CFG;
1489 require_once($CFG->dirroot . '/enrol/externallib.php');
1490 return core_enrol_external::get_enrolled_users_parameters();
01479290 1491 }
ea4e96c2 1492
01479290
DC
1493 /**
1494 * Get course participants details
4615817d 1495 *
01479290
DC
1496 * @param int $courseid course id
1497 * @param array $options options {
4615817d
JM
1498 * 'name' => option name
1499 * 'value' => option value
1500 * }
01479290 1501 * @return array An array of users
4615817d
JM
1502 * @since Moodle 2.1
1503 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1504 * @see core_enrol_external::get_enrolled_users()
01479290 1505 */
3c1aa6fd 1506 public static function get_users_by_courseid($courseid, $options = array()) {
5d1017e1
JM
1507 global $CFG;
1508 require_once($CFG->dirroot . '/enrol/externallib.php');
1509 return core_enrol_external::get_enrolled_users($courseid, $options);
ea4e96c2 1510 }
ea4e96c2
DC
1511 /**
1512 * Returns description of method result value
4615817d 1513 *
ea4e96c2 1514 * @return external_description
4615817d
JM
1515 * @since Moodle 2.1
1516 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
4615817d 1517 * @see core_enrol_external::get_enrolled_users_returns()
ea4e96c2 1518 */
01479290 1519 public static function get_users_by_courseid_returns() {
5d1017e1
JM
1520 global $CFG;
1521 require_once($CFG->dirroot . '/enrol/externallib.php');
1522 return core_enrol_external::get_enrolled_users_returns();
5de592b1 1523 }
3c1aa6fd
DM
1524
1525 /**
1526 * Marking the method as deprecated.
1527 *
1528 * @return bool
1529 */
1530 public static function get_users_by_courseid_is_deprecated() {
1531 return true;
1532 }
b0365ea5 1533}