on-demand release 2.1beta
[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),
ccc77f91 52 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
fb79269b 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),
ccc77f91 259 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
fb79269b 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
b4c74367
JM
349 * - This function is matching the permissions of /user/profil.php
350 * - It is also matching some permissions from /user/editadvanced.php for the following fields:
351 * auth, confirmed, idnumber, lang, theme, timezone, mailformat
71864f15
PS
352 * @param array $userids array of user ids
353 * @return array An array of arrays describing users
354 */
fb79269b 355 public static function get_users_by_id($userids) {
b4c74367 356 global $CFG, $USER, $DB;
109b453b 357 require_once($CFG->dirroot . "/user/lib.php");
b4c74367 358 require_once($CFG->dirroot . "/user/profile/lib.php"); //custom field library
7a5f3a3c 359 require_once($CFG->dirroot . "/lib/filelib.php"); // file handling on description and friends
b4c74367
JM
360
361 $isadmin = is_siteadmin($USER);
fb79269b 362
109b453b 363 $params = self::validate_parameters(self::get_users_by_id_parameters(),
364 array('userids'=>$userids));
5de592b1 365
ea4e96c2
DC
366 list($uselect, $ujoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
367 list($sqluserids, $params) = $DB->get_in_or_equal($userids);
368 $usersql = "SELECT u.* $uselect
369 FROM {user} u $ujoin
370 WHERE u.id $sqluserids";
371 $users = $DB->get_recordset_sql($usersql, $params);
d4e13355 372
109b453b 373 $result = array();
d4e13355 374 foreach ($users as $user) {
ea4e96c2
DC
375 if (!empty($user->deleted)) {
376 continue;
377 }
378 context_instance_preload($user);
379 // cached
380 $context = get_context_instance(CONTEXT_USER, $user->id);
b4c74367
JM
381 $hasviewdetailscap = has_capability('moodle/user:viewdetails', $context);
382 $hasuserupdatecap = has_capability('moodle/user:update', get_system_context());
383
6d153e67 384 self::validate_context($context);
385
b4c74367
JM
386 $currentuser = ($user->id == $USER->id);
387
ea4e96c2
DC
388 if (!$currentuser && !$hasviewdetailscap && !has_coursecontact_role($user->id)) {
389 throw new moodle_exception('usernotavailable', 'error');
390 }
fb79269b 391
ea4e96c2 392 $userarray = array();
b4c74367 393
ea4e96c2
DC
394 //basic fields
395 $userarray['id'] = $user->id;
396 if ($isadmin) {
397 $userarray['username'] = $user->username;
398 }
399 if ($isadmin or has_capability('moodle/site:viewfullnames', $context)) {
400 $userarray['firstname'] = $user->firstname;
401 $userarray['lastname'] = $user->lastname;
402 }
403 $userarray['fullname'] = fullname($user);
404
405 //fields matching permissions from /user/editadvanced.php
406 if ($currentuser or $hasuserupdatecap) {
407 $userarray['auth'] = $user->auth;
408 $userarray['confirmed'] = $user->confirmed;
409 $userarray['idnumber'] = $user->idnumber;
410 $userarray['lang'] = $user->lang;
411 $userarray['theme'] = $user->theme;
412 $userarray['timezone'] = $user->timezone;
413 $userarray['mailformat'] = $user->mailformat;
414 }
b4c74367 415
ea4e96c2
DC
416 //Custom fields (matching /user/profil/lib.php - profile_display_fields code logic)
417 $fields = $DB->get_recordset_sql("SELECT f.*
418 FROM {user_info_field} f
419 JOIN {user_info_category} c
420 ON f.categoryid=c.id
421 ORDER BY c.sortorder ASC, f.sortorder ASC");
422 foreach ($fields as $field) {
423 require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
424 $newfield = 'profile_field_'.$field->datatype;
425 $formfield = new $newfield($field->id, $user->id);
426 if ($formfield->is_visible() and !$formfield->is_empty()) {
427 $userarray['customfields'][] =
428 array('name' => $formfield->field->name, 'value' => $formfield->data,
429 'type' => $field->datatype, 'shortname' => $formfield->field->shortname);
b4c74367 430 }
ea4e96c2
DC
431 }
432 $fields->close();
433
434 //image profiles urls (public, no permission required in fact)
435 $profileimageurl = moodle_url::make_pluginfile_url($context->id, 'user', 'icon', NULL, '/', 'f1');
436 $userarray['profileimageurl'] = $profileimageurl->out(false);
437 $profileimageurlsmall = moodle_url::make_pluginfile_url($context->id, 'user', 'icon', NULL, '/', 'f2');
438 $userarray['profileimageurlsmall'] = $profileimageurlsmall->out(false);
439
440 //hidden user field
441 if (has_capability('moodle/user:viewhiddendetails', $context)) {
442 $hiddenfields = array();
443 } else {
444 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
445 }
b4c74367 446
ea4e96c2
DC
447 if (isset($user->description) && (!isset($hiddenfields['description']) or $isadmin)) {
448 if (empty($CFG->profilesforenrolledusersonly) || $currentuser) {
449 $user->description = file_rewrite_pluginfile_urls($user->description, 'pluginfile.php', $context->id, 'user', 'profile', null);
450 $userarray['description'] = $user->description;
451 $userarray['descriptionformat'] = $user->descriptionformat;
b4c74367 452 }
ea4e96c2 453 }
b4c74367 454
ea4e96c2
DC
455 if ((! isset($hiddenfields['country']) or $isadmin) && $user->country) {
456 $userarray['country'] = $user->country;
457 }
b4c74367 458
ea4e96c2
DC
459 if ((! isset($hiddenfields['city']) or $isadmin) && $user->city) {
460 $userarray['city'] = $user->city;
461 }
fb79269b 462
ea4e96c2
DC
463 if (has_capability('moodle/user:viewhiddendetails', $context)) {
464 if ($user->address) {
465 $userarray['address'] = $user->address;
b4c74367 466 }
ea4e96c2
DC
467 if ($user->phone1) {
468 $userarray['phone1'] = $user->phone1;
b4c74367 469 }
ea4e96c2
DC
470 if ($user->phone2) {
471 $userarray['phone2'] = $user->phone2;
b4c74367 472 }
ea4e96c2 473 }
b4c74367 474
ea4e96c2
DC
475 if ($currentuser
476 or $user->maildisplay == 1
477 or has_capability('moodle/course:useremail', $context)
478 or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER))) {
479 $userarray['email'] = $user->email;;
480 }
b4c74367 481
ea4e96c2
DC
482 if ($user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
483 $url = $user->url;
484 if (strpos($user->url, '://') === false) {
485 $url = 'http://'. $url;
b4c74367 486 }
ea4e96c2
DC
487 $user->url = clean_param($user->url, PARAM_URL);
488 $userarray['url'] = $user->url;
489 }
b4c74367 490
ea4e96c2
DC
491 if ($user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
492 $userarray['icq'] = $user->icq;
493 }
b4c74367 494
ea4e96c2
DC
495 if ($user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
496 $userarray['skype'] = $user->skype;
497 }
498 if ($user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
499 $userarray['yahoo'] = $user->yahoo;
500 }
501 if ($user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
502 $userarray['aim'] = $user->aim;
503 }
504 if ($user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
505 $userarray['msn'] = $user->msn;
506 }
b4c74367 507
ea4e96c2
DC
508 if ((!isset($hiddenfields['firstaccess'])) or $isadmin) {
509 if ($user->firstaccess) {
510 $userarray['firstaccess'] = $user->firstaccess;
511 } else {
512 $userarray['firstaccess'] = 0;
b4c74367 513 }
ea4e96c2
DC
514 }
515 if ((!isset($hiddenfields['lastaccess'])) or $isadmin) {
516 if ($user->lastaccess) {
517 $userarray['lastaccess'] = $user->lastaccess;
518 } else {
519 $userarray['lastaccess'] = 0;
b4c74367 520 }
ea4e96c2
DC
521 }
522 /// Printing tagged interests
523 if (!empty($CFG->usetags)) {
524 require_once($CFG->dirroot . '/tag/lib.php');
525 if ($interests = tag_get_tags_csv('user', $user->id, TAG_RETURN_TEXT) ) {
526 $userarray['interests'] = $interests;
b4c74367 527 }
ea4e96c2 528 }
b4c74367 529
ea4e96c2
DC
530 //Departement/Institution are not displayed on any profile, however you can get them from editing profile.
531 if ($isadmin or $currentuser) {
532 if ($user->institution) {
533 $userarray['institution'] = $user->institution;
b4c74367 534 }
ea4e96c2
DC
535 if (isset($user->department)) { //isset because it's ok to have department 0
536 $userarray['department'] = $user->department;
b4c74367 537 }
ea4e96c2 538 }
b4c74367 539
ea4e96c2
DC
540 //list of courses where the user is enrolled
541 $enrolledcourses = array();
542 if (!isset($hiddenfields['mycourses'])) {
543 if ($mycourses = enrol_get_users_courses($user->id, true, NULL, 'visible DESC,sortorder ASC')) {
544 $courselisting = '';
545 foreach ($mycourses as $mycourse) {
546 if ($mycourse->category) {
547 if ($mycourse->visible == 0) {
548 $ccontext = get_context_instance(CONTEXT_COURSE, $mycourse->id);
549 if (!has_capability('moodle/course:viewhiddencourses', $ccontext)) {
550 continue;
b4c74367 551 }
b4c74367 552 }
ea4e96c2
DC
553 $enrolledcourse = array();
554 $enrolledcourse['id'] = $mycourse->id;
555 $enrolledcourse['fullname'] = $mycourse->fullname;
556 $enrolledcourses[] = $enrolledcourse;
b4c74367 557 }
b4c74367 558 }
ea4e96c2 559 $userarray['enrolledcourses'] = $enrolledcourses;
b4c74367 560 }
fb79269b 561 }
b4c74367 562
ea4e96c2
DC
563 //user preferences
564 if ($currentuser) {
565 $preferences = array();
566 $userpreferences = get_user_preferences();
567 foreach($userpreferences as $prefname => $prefvalue) {
568 $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
569 }
570 $userarray['preferences'] = $preferences;
571 }
b4c74367 572 $result[] = $userarray;
fb79269b 573 }
ea4e96c2 574 $users->close();
71864f15
PS
575
576 return $result;
d4e13355 577 }
7b472b32 578
109b453b 579 /**
7b472b32
PS
580 * Returns description of method result value
581 * @return external_description
582 */
fb79269b 583 public static function get_users_by_id_returns() {
71864f15 584 return new external_multiple_structure(
ea4e96c2
DC
585 new external_single_structure(
586 array(
fb79269b 587 'id' => new external_value(PARAM_NUMBER, 'ID of the user'),
b4c74367
JM
588 'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL),
589 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
590 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
591 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
592 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
593 'address' => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
594 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
595 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
596 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
597 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
598 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
599 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
600 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
601 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
602 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
603 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
604 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
605 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
606 'auth' => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
607 'confirmed' => new external_value(PARAM_NUMBER, 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
608 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
609 'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
610 'theme' => new external_value(PARAM_SAFEDIR, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
b4e29077 611 'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
b4c74367
JM
612 'mailformat' => new external_value(PARAM_INTEGER, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
613 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
614 'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
615 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
616 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
617 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
618 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
619 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
71864f15 620 'customfields' => new external_multiple_structure(
ea4e96c2
DC
621 new external_single_structure(
622 array(
623 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
624 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
625 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
626 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
627 )
628 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
b4c74367 629 'preferences' => new external_multiple_structure(
ea4e96c2
DC
630 new external_single_structure(
631 array(
632 'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
633 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
634 )
635 ), 'User preferences', VALUE_OPTIONAL),
b4c74367 636 'enrolledcourses' => new external_multiple_structure(
ea4e96c2
DC
637 new external_single_structure(
638 array(
639 'id' => new external_value(PARAM_INT, 'Id of the course'),
640 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course')
641 )
642 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
643 )
644 )
645 );
646 }
647 /**
648 * Returns description of method parameters
649 * @return external_function_parameters
650 */
651 public static function get_course_participants_by_id_parameters() {
652 return new external_function_parameters(
653 array(
654 'userlist' => new external_multiple_structure(
655 new external_single_structure(
656 array(
657 'userid' => new external_value(PARAM_INT, 'userid'),
658 'courseid' => new external_value(PARAM_INT, 'courseid'),
109b453b 659 )
ea4e96c2 660 )
71864f15 661 )
ea4e96c2
DC
662 )
663 );
664 }
665
666 /**
667 * Get course participant's details
668 * @param array $userlist array of user ids and according course ids
669 * @return array An array of arrays describing course participants
670 */
671 public static function get_course_participants_by_id($userlist) {
672 global $CFG, $USER, $DB;
673 require_once($CFG->dirroot . "/user/lib.php");
674 require_once($CFG->dirroot . "/user/profile/lib.php"); //custom field library
675 require_once($CFG->dirroot . "/lib/filelib.php"); // file handling on description and friends
676
677 $isadmin = is_siteadmin($USER);
678
679 $params = self::validate_parameters(self::get_course_participants_by_id_parameters(), array('userlist'=>$userlist));
680
681 $userids = array();
682 $courseids = array();
683 foreach ($params['userlist'] as $value) {
684 $userids[] = $value['userid'];
685 $courseids[$value['userid']] = $value['courseid'];
686 }
687
688 // cache all courses
689 $courses = array();
690 list($cselect, $cjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
691 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids));
692 $coursesql = "SELECT c.* $uselect
693 FROM {course} c $cjoin
694 WHERE c.id $sqlcourseids";
695 $rs = $DB->get_recordset_sql($coursesql, $params);
696 foreach ($rs as $course) {
697 // adding course contexts to cache
698 context_instance_preload($course);
699 // cache courses
700 $courses[$course->id] = $course;
701 }
702 $rs->close();
703
704 list($uselect, $ujoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
705 list($sqluserids, $params) = $DB->get_in_or_equal($userids);
706 $usersql = "SELECT u.* $uselect
707 FROM {user} u $ujoin
708 WHERE u.id $sqluserids";
709 $users = $DB->get_recordset_sql($usersql, $params);
710 $result = array();
711 foreach ($users as $user) {
712 if (!empty($user->deleted)) {
713 continue;
714 }
715 context_instance_preload($user);
716 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
717 $course = $courses[$courseids[$user->id]];
718 $context = get_context_instance(CONTEXT_COURSE, $courseids[$user->id]);
719 $hasviewdetailscap = has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext);
720
721 self::validate_context($context);
722
723 $currentuser = ($user->id == $USER->id);
724
725 if (!$currentuser && !$hasviewdetailscap && !has_coursecontact_role($user->id)) {
726 throw new moodle_exception('usernotavailable', 'error');
727 }
728 $userarray = array();
729
730 //basic fields
731 $userarray['id'] = $user->id;
732 if ($isadmin) {
733 $userarray['username'] = $user->username;
734 }
735 if ($isadmin or has_capability('moodle/site:viewfullnames', $context)) {
736 $userarray['firstname'] = $user->firstname;
737 $userarray['lastname'] = $user->lastname;
738 }
739 $userarray['fullname'] = fullname($user);
740
741 //Custom fields (matching /user/profile/lib.php - profile_display_fields code logic)
742 $userarray['customfields'] = array();
743
744 $fields = $DB->get_recordset_sql("SELECT f.*
745 FROM {user_info_field} f
746 JOIN {user_info_category} c
747 ON f.categoryid=c.id
748 ORDER BY c.sortorder ASC, f.sortorder ASC");
749 foreach ($fields as $field) {
750 require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
751 $newfield = 'profile_field_'.$field->datatype;
752 $formfield = new $newfield($field->id, $user->id);
753 if ($formfield->is_visible() and !$formfield->is_empty()) {
754 $userarray['customfields'][] =
755 array('name' => $formfield->field->name, 'value' => $formfield->data,
756 'type' => $field->datatype, 'shortname' => $formfield->field->shortname);
757 }
758 }
759 $fields->close();
760
761 //image profiles urls (public, no permission required in fact)
762 $profileimageurl = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', 'f1');
763 $userarray['profileimageurl'] = $profileimageurl->out(false);
764 $profileimageurlsmall = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', 'f2');
765 $userarray['profileimageurlsmall'] = $profileimageurlsmall->out(false);
766
767 //hidden user field
768 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
769 $hiddenfields = array();
770 } else {
771 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
772 }
773
774 if (isset($user->description) && (!isset($hiddenfields['description']) or $isadmin)) {
775 if (empty($CFG->profilesforenrolledusersonly) || $currentuser) {
776 $user->description = file_rewrite_pluginfile_urls($user->description, 'pluginfile.php', $context->id, 'user', 'profile', null);
777 $userarray['description'] = $user->description;
778 $userarray['descriptionformat'] = $user->descriptionformat;
779 }
780 }
781
782 if ((! isset($hiddenfields['country']) or $isadmin) && $user->country) {
783 $userarray['country'] = $user->country;
784 }
785
786 if ((! isset($hiddenfields['city']) or $isadmin) && $user->city) {
787 $userarray['city'] = $user->city;
788 }
789
790 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
791 if ($user->address) {
792 $userarray['address'] = $user->address;
793 }
794 if ($user->phone1) {
795 $userarray['phone1'] = $user->phone1;
796 }
797 if ($user->phone2) {
798 $userarray['phone2'] = $user->phone2;
799 }
800 }
801
802 if ($currentuser
803 or $user->maildisplay == 1
804 or has_capability('moodle/course:useremail', $context)
805 or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER))) {
806 $userarray['email'] = $user->email;;
807 }
808
809 if ($user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
810 $url = $user->url;
811 if (strpos($user->url, '://') === false) {
812 $url = 'http://'. $url;
813 }
814 $user->url = clean_param($user->url, PARAM_URL);
815 $userarray['url'] = $user->url;
816 }
817
818 if ($user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
819 $userarray['icq'] = $user->icq;
820 }
821
822 if ($user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
823 $userarray['skype'] = $user->skype;
824 }
825 if ($user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
826 $userarray['yahoo'] = $user->yahoo;
827 }
828 if ($user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
829 $userarray['aim'] = $user->aim;
830 }
831 if ($user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
832 $userarray['msn'] = $user->msn;
833 }
834
835 if ((!isset($hiddenfields['firstaccess'])) or $isadmin) {
836 if ($user->firstaccess) {
837 $userarray['firstaccess'] = $user->firstaccess;
838 } else {
839 $userarray['firstaccess'] = 0;
840 }
841 }
842 if ((!isset($hiddenfields['lastaccess'])) or $isadmin) {
843 if ($user->lastaccess) {
844 $userarray['lastaccess'] = $user->lastaccess;
845 } else {
846 $userarray['lastaccess'] = 0;
847 }
848 }
849 /// Printing tagged interests
850 if (!empty($CFG->usetags)) {
851 require_once($CFG->dirroot . '/tag/lib.php');
852 if ($interests = tag_get_tags_csv('user', $user->id, TAG_RETURN_TEXT) ) {
853 $userarray['interests'] = $interests;
854 }
855 }
856
857 //Departement/Institution are not displayed on any profile, however you can get them from editing profile.
858 if ($isadmin or $currentuser) {
859 if ($user->institution) {
860 $userarray['institution'] = $user->institution;
861 }
862 if (isset($user->department)) { //isset because it's ok to have department 0
863 $userarray['department'] = $user->department;
864 }
865 }
866
867 // not a big secret
868 $userarray['roles'] = array();
869 $roles = get_user_roles($context, $user->id, false);
870 foreach ($roles as $role) {
871 $userarray['roles'][] = array(
872 'roleid' => $role->roleid,
873 'name' => $role->name,
874 'shortname' => $role->shortname,
875 'sortorder' => $role->sortorder
876 );
877 }
878
879 // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group
880 if (has_capability('moodle/site:accessallgroups', $context)) {
881 $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name,g.description');
882 foreach ($usergroups as $group) {
883 $group->description = file_rewrite_pluginfile_urls($group->description, 'pluginfile.php', $context->id, 'group', 'description', $group->id);
884 $userarray['groups'][] = array('id'=>$group->id, 'name'=>$group->name, 'description'=>$group->description);
885 }
886 }
887 $result[] = $userarray;
888 }
889
890 $users->close();
891
892 return $result;
893 }
894
895 /**
896 * Returns description of method result value
897 * @return external_description
898 */
899 public static function get_course_participants_by_id_returns() {
900 return new external_multiple_structure(
901 new external_single_structure(
902 array(
903 'id' => new external_value(PARAM_NUMBER, 'ID of the user'),
904 'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL),
905 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
906 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
907 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
908 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
909 'address' => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
910 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
911 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
912 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
913 'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
914 'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
915 'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
916 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
917 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
918 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
919 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
920 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
921 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
922 'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
923 'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
924 'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
925 'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
926 'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
927 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
928 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
929 'customfields' => new external_multiple_structure(
930 new external_single_structure(
931 array(
932 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
933 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
934 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
935 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
936 )
937 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
938 'groups' => new external_multiple_structure(
939 new external_single_structure(
940 array(
941 'id' => new external_value(PARAM_INT, 'group id'),
942 'name' => new external_value(PARAM_RAW, 'group name'),
943 'description' => new external_value(PARAM_RAW, 'group description'),
944 )
945 ), 'user groups', VALUE_OPTIONAL),
946 'roles' => new external_multiple_structure(
947 new external_single_structure(
948 array(
949 'roleid' => new external_value(PARAM_INT, 'role id'),
950 'name' => new external_value(PARAM_RAW, 'role name'),
951 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
952 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
953 )
954 ), 'user roles', VALUE_OPTIONAL),
955 )
956 )
71864f15 957 );
5de592b1 958 }
5de592b1 959}