59a749dcec744eacf02b9e83721e3cd715aa124a
[moodle.git] / user / externallib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
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/>.
17 /**
18  * External user API
19  *
20  * @package    core_user
21  * @category   external
22  * @copyright  2009 Petr Skodak
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 require_once("$CFG->libdir/externallib.php");
28 /**
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
36  */
37 class core_user_external extends external_api {
39     /**
40      * Returns description of method parameters
41      *
42      * @return external_function_parameters
43      * @since Moodle 2.2
44      */
45     public static function create_users_parameters() {
46         global $CFG;
48         return new external_function_parameters(
49             array(
50                 'users' => new external_multiple_structure(
51                     new external_single_structure(
52                         array(
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', VALUE_OPTIONAL),
57                             'createpassword' =>
58                                 new external_value(PARAM_BOOL, 'True if password should be created and mailed to user.',
59                                     VALUE_OPTIONAL),
60                             'firstname' =>
61                                 new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
62                             'lastname' =>
63                                 new external_value(PARAM_NOTAGS, 'The family name of the user'),
64                             'email' =>
65                                 new external_value(PARAM_EMAIL, 'A valid and unique email address'),
66                             'auth' =>
67                                 new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT,
68                                     'manual', NULL_NOT_ALLOWED),
69                             'idnumber' =>
70                                 new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution',
71                                     VALUE_DEFAULT, ''),
72                             'lang' =>
73                                 new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_DEFAULT,
74                                     $CFG->lang, NULL_NOT_ALLOWED),
75                             'calendartype' =>
76                                 new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server',
77                                     VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
78                             'theme' =>
79                                 new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server',
80                                     VALUE_OPTIONAL),
81                             'timezone' =>
82                                 new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default',
83                                     VALUE_OPTIONAL),
84                             'mailformat' =>
85                                 new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc',
86                                     VALUE_OPTIONAL),
87                             'description' =>
88                                 new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
89                             'city' =>
90                                 new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
91                             'country' =>
92                                 new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
93                             'firstnamephonetic' =>
94                                 new external_value(PARAM_NOTAGS, 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
95                             'lastnamephonetic' =>
96                                 new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
97                             'middlename' =>
98                                 new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
99                             'alternatename' =>
100                                 new external_value(PARAM_NOTAGS, 'The alternate name of the user', VALUE_OPTIONAL),
101                             'preferences' => new external_multiple_structure(
102                                 new external_single_structure(
103                                     array(
104                                         'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
105                                         'value' => new external_value(PARAM_RAW, 'The value of the preference')
106                                     )
107                                 ), 'User preferences', VALUE_OPTIONAL),
108                             'customfields' => new external_multiple_structure(
109                                 new external_single_structure(
110                                     array(
111                                         'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
112                                         'value' => new external_value(PARAM_RAW, 'The value of the custom field')
113                                     )
114                                 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
115                         )
116                     )
117                 )
118             )
119         );
120     }
122     /**
123      * Create one or more users.
124      *
125      * @throws invalid_parameter_exception
126      * @param array $users An array of users to create.
127      * @return array An array of arrays
128      * @since Moodle 2.2
129      */
130     public static function create_users($users) {
131         global $CFG, $DB;
132         require_once($CFG->dirroot."/lib/weblib.php");
133         require_once($CFG->dirroot."/user/lib.php");
134         require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
136         // Ensure the current user is allowed to run this function.
137         $context = context_system::instance();
138         self::validate_context($context);
139         require_capability('moodle/user:create', $context);
141         // Do basic automatic PARAM checks on incoming data, using params description.
142         // If any problems are found then exceptions are thrown with helpful error messages.
143         $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
145         $availableauths  = core_component::get_plugin_list('auth');
146         unset($availableauths['mnet']);       // These would need mnethostid too.
147         unset($availableauths['webservice']); // We do not want new webservice users for now.
149         $availablethemes = core_component::get_plugin_list('theme');
150         $availablelangs  = get_string_manager()->get_list_of_translations();
152         $transaction = $DB->start_delegated_transaction();
154         $userids = array();
155         $createpassword = false;
156         foreach ($params['users'] as $user) {
157             // Make sure that the username doesn't already exist.
158             if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
159                 throw new invalid_parameter_exception('Username already exists: '.$user['username']);
160             }
162             // Make sure auth is valid.
163             if (empty($availableauths[$user['auth']])) {
164                 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
165             }
167             // Make sure lang is valid.
168             if (empty($availablelangs[$user['lang']])) {
169                 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
170             }
172             // Make sure lang is valid.
173             if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
174                                                                                      // so no default value
175                                                                                      // We need to test if the client sent it
176                                                                                      // => !empty($user['theme']).
177                 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
178             }
180             // Make sure we have a password or have to create one.
181             if (empty($user['password']) && empty($user['createpassword'])) {
182                 throw new invalid_parameter_exception('Invalid password: you must inform a password or set createpassword.');
183             }
185             $user['confirmed'] = true;
186             $user['mnethostid'] = $CFG->mnet_localhost_id;
188             // Start of user info validation.
189             // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
190             if (!validate_email($user['email'])) {
191                 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
192             } else if ($DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
193                 throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
194             }
195             // End of user info validation.
197             $createpassword = !empty($user['createpassword']);
198             unset($user['createpassword']);
199             if ($createpassword) {
200                 $user['password'] = '';
201                 $updatepassword = false;
202             } else {
203                 $updatepassword = true;
204             }
206             // Create the user data now!
207             $user['id'] = user_create_user($user, $updatepassword, false);
209             // Custom fields.
210             if (!empty($user['customfields'])) {
211                 foreach ($user['customfields'] as $customfield) {
212                     // Profile_save_data() saves profile file it's expecting a user with the correct id,
213                     // and custom field to be named profile_field_"shortname".
214                     $user["profile_field_".$customfield['type']] = $customfield['value'];
215                 }
216                 profile_save_data((object) $user);
217             }
219             if ($createpassword) {
220                 $userobject = (object)$user;
221                 setnew_password_and_mail($userobject);
222                 unset_user_preference('create_password', $userobject);
223                 set_user_preference('auth_forcepasswordchange', 1, $userobject);
224             }
226             // Trigger event.
227             \core\event\user_created::create_from_userid($user['id'])->trigger();
229             // Preferences.
230             if (!empty($user['preferences'])) {
231                 foreach ($user['preferences'] as $preference) {
232                     set_user_preference($preference['type'], $preference['value'], $user['id']);
233                 }
234             }
236             $userids[] = array('id' => $user['id'], 'username' => $user['username']);
237         }
239         $transaction->allow_commit();
241         return $userids;
242     }
244     /**
245      * Returns description of method result value
246      *
247      * @return external_description
248      * @since Moodle 2.2
249      */
250     public static function create_users_returns() {
251         return new external_multiple_structure(
252             new external_single_structure(
253                 array(
254                     'id'       => new external_value(PARAM_INT, 'user id'),
255                     'username' => new external_value(PARAM_USERNAME, 'user name'),
256                 )
257             )
258         );
259     }
262     /**
263      * Returns description of method parameters
264      *
265      * @return external_function_parameters
266      * @since Moodle 2.2
267      */
268     public static function delete_users_parameters() {
269         return new external_function_parameters(
270             array(
271                 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
272             )
273         );
274     }
276     /**
277      * Delete users
278      *
279      * @throws moodle_exception
280      * @param array $userids
281      * @return null
282      * @since Moodle 2.2
283      */
284     public static function delete_users($userids) {
285         global $CFG, $DB, $USER;
286         require_once($CFG->dirroot."/user/lib.php");
288         // Ensure the current user is allowed to run this function.
289         $context = context_system::instance();
290         require_capability('moodle/user:delete', $context);
291         self::validate_context($context);
293         $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
295         $transaction = $DB->start_delegated_transaction();
297         foreach ($params['userids'] as $userid) {
298             $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
299             // Must not allow deleting of admins or self!!!
300             if (is_siteadmin($user)) {
301                 throw new moodle_exception('useradminodelete', 'error');
302             }
303             if ($USER->id == $user->id) {
304                 throw new moodle_exception('usernotdeletederror', 'error');
305             }
306             user_delete_user($user);
307         }
309         $transaction->allow_commit();
311         return null;
312     }
314     /**
315      * Returns description of method result value
316      *
317      * @return null
318      * @since Moodle 2.2
319      */
320     public static function delete_users_returns() {
321         return null;
322     }
325     /**
326      * Returns description of method parameters
327      *
328      * @return external_function_parameters
329      * @since Moodle 2.2
330      */
331     public static function update_users_parameters() {
332         return new external_function_parameters(
333             array(
334                 'users' => new external_multiple_structure(
335                     new external_single_structure(
336                         array(
337                             'id' =>
338                                 new external_value(PARAM_INT, 'ID of the user'),
339                             'username' =>
340                                 new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config.',
341                                     VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
342                             'password' =>
343                                 new external_value(PARAM_RAW, 'Plain text password consisting of any characters', VALUE_OPTIONAL,
344                                     '', NULL_NOT_ALLOWED),
345                             'firstname' =>
346                                 new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL, '',
347                                     NULL_NOT_ALLOWED),
348                             'lastname' =>
349                                 new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
350                             'email' =>
351                                 new external_value(PARAM_EMAIL, 'A valid and unique email address', VALUE_OPTIONAL, '',
352                                     NULL_NOT_ALLOWED),
353                             'auth' =>
354                                 new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL, '',
355                                     NULL_NOT_ALLOWED),
356                             'idnumber' =>
357                                 new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution',
358                                     VALUE_OPTIONAL),
359                             'lang' =>
360                                 new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server',
361                                     VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
362                             'calendartype' =>
363                                 new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server',
364                                     VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
365                             'theme' =>
366                                 new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server',
367                                     VALUE_OPTIONAL),
368                             'timezone' =>
369                                 new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default',
370                                     VALUE_OPTIONAL),
371                             'mailformat' =>
372                                 new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc',
373                                     VALUE_OPTIONAL),
374                             'description' =>
375                                 new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
376                             'city' =>
377                                 new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
378                             'country' =>
379                                 new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
380                             'firstnamephonetic' =>
381                                 new external_value(PARAM_NOTAGS, 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
382                             'lastnamephonetic' =>
383                                 new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
384                             'middlename' =>
385                                 new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
386                             'alternatename' =>
387                                 new external_value(PARAM_NOTAGS, 'The alternate name of the user', VALUE_OPTIONAL),
388                             'customfields' => new external_multiple_structure(
389                                 new external_single_structure(
390                                     array(
391                                         'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
392                                         'value' => new external_value(PARAM_RAW, 'The value of the custom field')
393                                     )
394                                 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
395                             'preferences' => new external_multiple_structure(
396                                 new external_single_structure(
397                                     array(
398                                         'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
399                                         'value' => new external_value(PARAM_RAW, 'The value of the preference')
400                                     )
401                                 ), 'User preferences', VALUE_OPTIONAL),
402                         )
403                     )
404                 )
405             )
406         );
407     }
409     /**
410      * Update users
411      *
412      * @param array $users
413      * @return null
414      * @since Moodle 2.2
415      */
416     public static function update_users($users) {
417         global $CFG, $DB;
418         require_once($CFG->dirroot."/user/lib.php");
419         require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
421         // Ensure the current user is allowed to run this function.
422         $context = context_system::instance();
423         require_capability('moodle/user:update', $context);
424         self::validate_context($context);
426         $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
428         $transaction = $DB->start_delegated_transaction();
430         foreach ($params['users'] as $user) {
431             user_update_user($user, true, false);
432             // Update user custom fields.
433             if (!empty($user['customfields'])) {
435                 foreach ($user['customfields'] as $customfield) {
436                     // Profile_save_data() saves profile file it's expecting a user with the correct id,
437                     // and custom field to be named profile_field_"shortname".
438                     $user["profile_field_".$customfield['type']] = $customfield['value'];
439                 }
440                 profile_save_data((object) $user);
441             }
443             // Trigger event.
444             \core\event\user_updated::create_from_userid($user['id'])->trigger();
446             // Preferences.
447             if (!empty($user['preferences'])) {
448                 foreach ($user['preferences'] as $preference) {
449                     set_user_preference($preference['type'], $preference['value'], $user['id']);
450                 }
451             }
452         }
454         $transaction->allow_commit();
456         return null;
457     }
459     /**
460      * Returns description of method result value
461      *
462      * @return null
463      * @since Moodle 2.2
464      */
465     public static function update_users_returns() {
466         return null;
467     }
469     /**
470      * Returns description of method parameters
471      *
472      * @return external_function_parameters
473      * @since Moodle 2.4
474      */
475     public static function get_users_by_field_parameters() {
476         return new external_function_parameters(
477             array(
478                 'field' => new external_value(PARAM_ALPHA, 'the search field can be
479                     \'id\' or \'idnumber\' or \'username\' or \'email\''),
480                 'values' => new external_multiple_structure(
481                         new external_value(PARAM_RAW, 'the value to match'))
482             )
483         );
484     }
486     /**
487      * Get user information for a unique field.
488      *
489      * @throws coding_exception
490      * @throws invalid_parameter_exception
491      * @param string $field
492      * @param array $values
493      * @return array An array of arrays containg user profiles.
494      * @since Moodle 2.4
495      */
496     public static function get_users_by_field($field, $values) {
497         global $CFG, $USER, $DB;
498         require_once($CFG->dirroot . "/user/lib.php");
500         $params = self::validate_parameters(self::get_users_by_field_parameters(),
501                 array('field' => $field, 'values' => $values));
503         // This array will keep all the users that are allowed to be searched,
504         // according to the current user's privileges.
505         $cleanedvalues = array();
507         switch ($field) {
508             case 'id':
509                 $paramtype = PARAM_INT;
510                 break;
511             case 'idnumber':
512                 $paramtype = PARAM_RAW;
513                 break;
514             case 'username':
515                 $paramtype = PARAM_RAW;
516                 break;
517             case 'email':
518                 $paramtype = PARAM_EMAIL;
519                 break;
520             default:
521                 throw new coding_exception('invalid field parameter',
522                         'The search field \'' . $field . '\' is not supported, look at the web service documentation');
523         }
525         // Clean the values.
526         foreach ($values as $value) {
527             $cleanedvalue = clean_param($value, $paramtype);
528             if ( $value != $cleanedvalue) {
529                 throw new invalid_parameter_exception('The field \'' . $field .
530                         '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
531             }
532             $cleanedvalues[] = $cleanedvalue;
533         }
535         // Retrieve the users.
536         $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
538         // Finally retrieve each users information.
539         $returnedusers = array();
540         foreach ($users as $user) {
541             $userdetails = user_get_user_details_courses($user);
543             // Return the user only if the searched field is returned.
544             // Otherwise it means that the $USER was not allowed to search the returned user.
545             if (!empty($userdetails) and !empty($userdetails[$field])) {
546                 $returnedusers[] = $userdetails;
547             }
548         }
550         return $returnedusers;
551     }
553     /**
554      * Returns description of method result value
555      *
556      * @return external_multiple_structure
557      * @since Moodle 2.4
558      */
559     public static function get_users_by_field_returns() {
560         return new external_multiple_structure(self::user_description());
561     }
564     /**
565      * Returns description of get_users() parameters.
566      *
567      * @return external_function_parameters
568      * @since Moodle 2.5
569      */
570     public static function get_users_parameters() {
571         return new external_function_parameters(
572             array(
573                 'criteria' => new external_multiple_structure(
574                     new external_single_structure(
575                         array(
576                             'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
577                                 "id" (int) matching user id,
578                                 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
579                                 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
580                                 "idnumber" (string) matching user idnumber,
581                                 "username" (string) matching user username,
582                                 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
583                                 "auth" (string) matching user auth plugin'),
584                             'value' => new external_value(PARAM_RAW, 'the value to search')
585                         )
586                     ), 'the key/value pairs to be considered in user search. Values can not be empty.
587                         Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
588                         key occurences are forbidden.
589                         The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
590                         the search is still executed on the valid criterias.
591                         You can search without criteria, but the function is not designed for it.
592                         It could very slow or timeout. The function is designed to search some specific users.'
593                 )
594             )
595         );
596     }
598     /**
599      * Retrieve matching user.
600      *
601      * @throws moodle_exception
602      * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
603      * @return array An array of arrays containing user profiles.
604      * @since Moodle 2.5
605      */
606     public static function get_users($criteria = array()) {
607         global $CFG, $USER, $DB;
609         require_once($CFG->dirroot . "/user/lib.php");
611         $params = self::validate_parameters(self::get_users_parameters(),
612                 array('criteria' => $criteria));
614         // Validate the criteria and retrieve the users.
615         $users = array();
616         $warnings = array();
617         $sqlparams = array();
618         $usedkeys = array();
620         // Do not retrieve deleted users.
621         $sql = ' deleted = 0';
623         foreach ($params['criteria'] as $criteriaindex => $criteria) {
625             // Check that the criteria has never been used.
626             if (array_key_exists($criteria['key'], $usedkeys)) {
627                 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
628             } else {
629                 $usedkeys[$criteria['key']] = true;
630             }
632             $invalidcriteria = false;
633             // Clean the parameters.
634             $paramtype = PARAM_RAW;
635             switch ($criteria['key']) {
636                 case 'id':
637                     $paramtype = PARAM_INT;
638                     break;
639                 case 'idnumber':
640                     $paramtype = PARAM_RAW;
641                     break;
642                 case 'username':
643                     $paramtype = PARAM_RAW;
644                     break;
645                 case 'email':
646                     // We use PARAM_RAW to allow searches with %.
647                     $paramtype = PARAM_RAW;
648                     break;
649                 case 'auth':
650                     $paramtype = PARAM_AUTH;
651                     break;
652                 case 'lastname':
653                 case 'firstname':
654                     $paramtype = PARAM_TEXT;
655                     break;
656                 default:
657                     // Send back a warning that this search key is not supported in this version.
658                     // This warning will make the function extandable without breaking clients.
659                     $warnings[] = array(
660                         'item' => $criteria['key'],
661                         'warningcode' => 'invalidfieldparameter',
662                         'message' =>
663                             'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
664                     );
665                     // Do not add this invalid criteria to the created SQL request.
666                     $invalidcriteria = true;
667                     unset($params['criteria'][$criteriaindex]);
668                     break;
669             }
671             if (!$invalidcriteria) {
672                 $cleanedvalue = clean_param($criteria['value'], $paramtype);
674                 $sql .= ' AND ';
676                 // Create the SQL.
677                 switch ($criteria['key']) {
678                     case 'id':
679                     case 'idnumber':
680                     case 'username':
681                     case 'auth':
682                         $sql .= $criteria['key'] . ' = :' . $criteria['key'];
683                         $sqlparams[$criteria['key']] = $cleanedvalue;
684                         break;
685                     case 'email':
686                     case 'lastname':
687                     case 'firstname':
688                         $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
689                         $sqlparams[$criteria['key']] = $cleanedvalue;
690                         break;
691                     default:
692                         break;
693                 }
694             }
695         }
697         $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
699         // Finally retrieve each users information.
700         $returnedusers = array();
701         foreach ($users as $user) {
702             $userdetails = user_get_user_details_courses($user);
704             // Return the user only if all the searched fields are returned.
705             // Otherwise it means that the $USER was not allowed to search the returned user.
706             if (!empty($userdetails)) {
707                 $validuser = true;
709                 foreach ($params['criteria'] as $criteria) {
710                     if (empty($userdetails[$criteria['key']])) {
711                         $validuser = false;
712                     }
713                 }
715                 if ($validuser) {
716                     $returnedusers[] = $userdetails;
717                 }
718             }
719         }
721         return array('users' => $returnedusers, 'warnings' => $warnings);
722     }
724     /**
725      * Returns description of get_users result value.
726      *
727      * @return external_description
728      * @since Moodle 2.5
729      */
730     public static function get_users_returns() {
731         return new external_single_structure(
732             array('users' => new external_multiple_structure(
733                                 self::user_description()
734                              ),
735                   'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
736             )
737         );
738     }
740     /**
741      * Returns description of method parameters
742      *
743      * @return external_function_parameters
744      * @since Moodle 2.2
745      * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
746      * @see core_user_external::get_users_by_field_parameters()
747      */
748     public static function get_users_by_id_parameters() {
749         return new external_function_parameters(
750             array(
751                 'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
752             )
753         );
754     }
756     /**
757      * Get user information
758      * - This function is matching the permissions of /user/profil.php
759      * - It is also matching some permissions from /user/editadvanced.php for the following fields:
760      *   auth, confirmed, idnumber, lang, theme, timezone, mailformat
761      *
762      * @param array $userids  array of user ids
763      * @return array An array of arrays describing users
764      * @since Moodle 2.2
765      * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
766      * @see core_user_external::get_users_by_field()
767      */
768     public static function get_users_by_id($userids) {
769         global $CFG, $USER, $DB;
770         require_once($CFG->dirroot . "/user/lib.php");
772         $params = self::validate_parameters(self::get_users_by_id_parameters(),
773                 array('userids' => $userids));
775         list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
776         $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
777         $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
778         $params['contextlevel'] = CONTEXT_USER;
779         $usersql = "SELECT u.* $uselect
780                       FROM {user} u $ujoin
781                      WHERE u.id $sqluserids";
782         $users = $DB->get_recordset_sql($usersql, $params);
784         $result = array();
785         $hasuserupdatecap = has_capability('moodle/user:update', context_system::instance());
786         foreach ($users as $user) {
787             if (!empty($user->deleted)) {
788                 continue;
789             }
790             context_helper::preload_from_record($user);
791             $usercontext = context_user::instance($user->id, IGNORE_MISSING);
792             self::validate_context($usercontext);
793             $currentuser = ($user->id == $USER->id);
795             if ($userarray  = user_get_user_details($user)) {
796                 // Fields matching permissions from /user/editadvanced.php.
797                 if ($currentuser or $hasuserupdatecap) {
798                     $userarray['auth']       = $user->auth;
799                     $userarray['confirmed']  = $user->confirmed;
800                     $userarray['idnumber']   = $user->idnumber;
801                     $userarray['lang']       = $user->lang;
802                     $userarray['theme']      = $user->theme;
803                     $userarray['timezone']   = $user->timezone;
804                     $userarray['mailformat'] = $user->mailformat;
805                 }
806                 $result[] = $userarray;
807             }
808         }
809         $users->close();
811         return $result;
812     }
814     /**
815      * Returns description of method result value
816      *
817      * @return external_description
818      * @since Moodle 2.2
819      * @deprecated Moodle 2.5 MDL-38030 - Please do not call this function any more.
820      * @see core_user_external::get_users_by_field_returns()
821      */
822     public static function get_users_by_id_returns() {
823         $additionalfields = array (
824             'enrolledcourses' => new external_multiple_structure(
825             new external_single_structure(
826                 array(
827                     'id'  => new external_value(PARAM_INT, 'Id of the course'),
828                     'fullname'  => new external_value(PARAM_RAW, 'Fullname of the course'),
829                     'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
830                 )
831             ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL));
832         return new external_multiple_structure(self::user_description($additionalfields));
833     }
835     /**
836      * Marking the method as deprecated.
837      *
838      * @return bool
839      */
840     public static function get_users_by_id_is_deprecated() {
841         return true;
842     }
844     /**
845      * Returns description of method parameters
846      *
847      * @return external_function_parameters
848      * @since Moodle 2.2
849      */
850     public static function get_course_user_profiles_parameters() {
851         return new external_function_parameters(
852             array(
853                 'userlist' => new external_multiple_structure(
854                     new external_single_structure(
855                         array(
856                             'userid'    => new external_value(PARAM_INT, 'userid'),
857                             'courseid'    => new external_value(PARAM_INT, 'courseid'),
858                         )
859                     )
860                 )
861             )
862         );
863     }
865     /**
866      * Get course participant's details
867      *
868      * @param array $userlist  array of user ids and according course ids
869      * @return array An array of arrays describing course participants
870      * @since Moodle 2.2
871      */
872     public static function get_course_user_profiles($userlist) {
873         global $CFG, $USER, $DB;
874         require_once($CFG->dirroot . "/user/lib.php");
875         $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
877         $userids = array();
878         $courseids = array();
879         foreach ($params['userlist'] as $value) {
880             $userids[] = $value['userid'];
881             $courseids[$value['userid']] = $value['courseid'];
882         }
884         // Cache all courses.
885         $courses = array();
886         list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
887         $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
888         $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
889         $params['contextlevel'] = CONTEXT_COURSE;
890         $coursesql = "SELECT c.* $cselect
891                         FROM {course} c $cjoin
892                        WHERE c.id $sqlcourseids";
893         $rs = $DB->get_recordset_sql($coursesql, $params);
894         foreach ($rs as $course) {
895             // Adding course contexts to cache.
896             context_helper::preload_from_record($course);
897             // Cache courses.
898             $courses[$course->id] = $course;
899         }
900         $rs->close();
902         list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
903         $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
904         $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
905         $params['contextlevel'] = CONTEXT_USER;
906         $usersql = "SELECT u.* $uselect
907                       FROM {user} u $ujoin
908                      WHERE u.id $sqluserids";
909         $users = $DB->get_recordset_sql($usersql, $params);
910         $result = array();
911         foreach ($users as $user) {
912             if (!empty($user->deleted)) {
913                 continue;
914             }
915             context_helper::preload_from_record($user);
916             $course = $courses[$courseids[$user->id]];
917             $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
918             self::validate_context($context);
919             if ($userarray = user_get_user_details($user, $course)) {
920                 $result[] = $userarray;
921             }
922         }
924         $users->close();
926         return $result;
927     }
929     /**
930      * Returns description of method result value
931      *
932      * @return external_description
933      * @since Moodle 2.2
934      */
935     public static function get_course_user_profiles_returns() {
936         $additionalfields = array(
937             'groups' => new external_multiple_structure(
938                 new external_single_structure(
939                     array(
940                         'id'  => new external_value(PARAM_INT, 'group id'),
941                         'name' => new external_value(PARAM_RAW, 'group name'),
942                         'description' => new external_value(PARAM_RAW, 'group description'),
943                         'descriptionformat' => new external_format_value('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             'enrolledcourses' => new external_multiple_structure(
956                 new external_single_structure(
957                     array(
958                         'id'  => new external_value(PARAM_INT, 'Id of the course'),
959                         'fullname'  => new external_value(PARAM_RAW, 'Fullname of the course'),
960                         'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
961                     )
962                 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
963         );
965         return new external_multiple_structure(self::user_description($additionalfields));
966     }
968     /**
969      * Create user return value description.
970      *
971      * @param array $additionalfields some additional field
972      * @return single_structure_description
973      */
974     public static function user_description($additionalfields = array()) {
975         $userfields = array(
976             'id'    => new external_value(PARAM_INT, 'ID of the user'),
977             'username'    => new external_value(PARAM_RAW, 'The username', VALUE_OPTIONAL),
978             'firstname'   => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
979             'lastname'    => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
980             'fullname'    => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
981             'email'       => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
982             'address'     => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL),
983             'phone1'      => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
984             'phone2'      => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
985             'icq'         => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
986             'skype'       => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
987             'yahoo'       => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
988             'aim'         => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
989             'msn'         => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
990             'department'  => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
991             'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
992             'idnumber'    => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
993             'interests'   => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
994             'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
995             'lastaccess'  => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
996             'auth'        => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
997             'confirmed'   => new external_value(PARAM_INT, 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
998             'lang'        => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
999             'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
1000             'theme'       => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
1001             'timezone'    => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
1002             'mailformat'  => new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
1003             'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
1004             'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
1005             'city'        => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
1006             'url'         => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
1007             'country'     => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
1008             'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
1009             'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
1010             'customfields' => new external_multiple_structure(
1011                 new external_single_structure(
1012                     array(
1013                         'type'  => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
1014                         'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
1015                         'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
1016                         'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
1017                     )
1018                 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
1019             'preferences' => new external_multiple_structure(
1020                 new external_single_structure(
1021                     array(
1022                         'name'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
1023                         'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
1024                     )
1025             ), 'Users preferences', VALUE_OPTIONAL)
1026         );
1027         if (!empty($additionalfields)) {
1028             $userfields = array_merge($userfields, $additionalfields);
1029         }
1030         return new external_single_structure($userfields);
1031     }
1033     /**
1034      * Returns description of method parameters
1035      *
1036      * @return external_function_parameters
1037      * @since Moodle 2.6
1038      */
1039     public static function add_user_private_files_parameters() {
1040         return new external_function_parameters(
1041             array(
1042                 'draftid' => new external_value(PARAM_INT, 'draft area id')
1043             )
1044         );
1045     }
1047     /**
1048      * Copy files from a draft area to users private files area.
1049      *
1050      * @throws invalid_parameter_exception
1051      * @param int $draftid Id of a draft area containing files.
1052      * @return array An array of warnings
1053      * @since Moodle 2.6
1054      */
1055     public static function add_user_private_files($draftid) {
1056         global $CFG, $USER, $DB;
1058         require_once($CFG->dirroot . "/user/lib.php");
1059         $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
1061         if (isguestuser()) {
1062             throw new invalid_parameter_exception('Guest users cannot upload files');
1063         }
1065         $context = context_user::instance($USER->id);
1066         require_capability('moodle/user:manageownfiles', $context);
1068         $maxbytes = $CFG->userquota;
1069         $maxareabytes = $CFG->userquota;
1070         if (has_capability('moodle/user:ignoreuserquota', $context)) {
1071             $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
1072             $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
1073         }
1075         $options = array('subdirs' => 1,
1076                          'maxbytes' => $maxbytes,
1077                          'maxfiles' => -1,
1078                          'accepted_types' => '*',
1079                          'areamaxbytes' => $maxareabytes);
1081         file_save_draft_area_files($draftid, $context->id, 'user', 'private', 0, $options);
1083         return null;
1084     }
1086     /**
1087      * Returns description of method result value
1088      *
1089      * @return external_description
1090      * @since Moodle 2.2
1091      */
1092     public static function add_user_private_files_returns() {
1093         return null;
1094     }
1096     /**
1097      * Returns description of method parameters.
1098      *
1099      * @return external_function_parameters
1100      * @since Moodle 2.6
1101      */
1102     public static function add_user_device_parameters() {
1103         return new external_function_parameters(
1104             array(
1105                 'appid'     => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
1106                 'name'      => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
1107                 'model'     => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
1108                 'platform'  => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
1109                 'version'   => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
1110                 'pushid'    => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
1111                 'uuid'      => new external_value(PARAM_RAW, 'the device UUID')
1112             )
1113         );
1114     }
1116     /**
1117      * Add a user device in Moodle database (for PUSH notifications usually).
1118      *
1119      * @throws moodle_exception
1120      * @param string $appid The app id, usually something like com.moodle.moodlemobile.
1121      * @param string $name The device name, occam or iPhone etc.
1122      * @param string $model The device model Nexus4 or iPad1.1 etc.
1123      * @param string $platform The device platform iOs or Android etc.
1124      * @param string $version The device version 6.1.2 or 4.2.2 etc.
1125      * @param string $pushid The device PUSH token/key/identifier/registration id.
1126      * @param string $uuid The device UUID.
1127      * @return array List of possible warnings.
1128      * @since Moodle 2.6
1129      */
1130     public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
1131         global $CFG, $USER, $DB;
1132         require_once($CFG->dirroot . "/user/lib.php");
1134         $params = self::validate_parameters(self::add_user_device_parameters(),
1135                 array('appid' => $appid,
1136                       'name' => $name,
1137                       'model' => $model,
1138                       'platform' => $platform,
1139                       'version' => $version,
1140                       'pushid' => $pushid,
1141                       'uuid' => $uuid
1142                       ));
1144         $warnings = array();
1146         // Prevent duplicate keys for users.
1147         if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
1148             $warnings['warning'][] = array(
1149                 'item' => $params['pushid'],
1150                 'warningcode' => 'existingkeyforthisuser',
1151                 'message' => 'This key is already stored for this user'
1152             );
1153             return $warnings;
1154         }
1156         // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
1157         // Since we don't have a clear way to decide which one is the more appropiate, we update all.
1158         if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
1159                 'appid' => $params['appid'], 'userid' => $USER->id))) {
1161             foreach ($userdevices as $userdevice) {
1162                 $userdevice->version    = $params['version'];   // Maybe the user upgraded the device.
1163                 $userdevice->pushid     = $params['pushid'];
1164                 $userdevice->timemodified  = time();
1165                 $DB->update_record('user_devices', $userdevice);
1166             }
1168         } else {
1169             $userdevice = new stdclass;
1170             $userdevice->userid     = $USER->id;
1171             $userdevice->appid      = $params['appid'];
1172             $userdevice->name       = $params['name'];
1173             $userdevice->model      = $params['model'];
1174             $userdevice->platform   = $params['platform'];
1175             $userdevice->version    = $params['version'];
1176             $userdevice->pushid     = $params['pushid'];
1177             $userdevice->uuid       = $params['uuid'];
1178             $userdevice->timecreated  = time();
1179             $userdevice->timemodified = $userdevice->timecreated;
1181             if (!$DB->insert_record('user_devices', $userdevice)) {
1182                 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
1183             }
1184         }
1186         return $warnings;
1187     }
1189     /**
1190      * Returns description of method result value.
1191      *
1192      * @return external_multiple_structure
1193      * @since Moodle 2.6
1194      */
1195     public static function add_user_device_returns() {
1196         return new external_multiple_structure(
1197            new external_warnings()
1198         );
1199     }
1201     /**
1202      * Returns description of method parameters.
1203      *
1204      * @return external_function_parameters
1205      * @since Moodle 2.9
1206      */
1207     public static function remove_user_device_parameters() {
1208         return new external_function_parameters(
1209             array(
1210                 'uuid'  => new external_value(PARAM_RAW, 'the device UUID'),
1211                 'appid' => new external_value(PARAM_NOTAGS,
1212                                                 'the app id, if empty devices matching the UUID for the user will be removed',
1213                                                 VALUE_DEFAULT, ''),
1214             )
1215         );
1216     }
1218     /**
1219      * Remove a user device from the Moodle database (for PUSH notifications usually).
1220      *
1221      * @param string $uuid The device UUID.
1222      * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
1223      * @return array List of possible warnings and removal status.
1224      * @since Moodle 2.9
1225      */
1226     public static function remove_user_device($uuid, $appid = "") {
1227         global $CFG;
1228         require_once($CFG->dirroot . "/user/lib.php");
1230         $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
1232         $context = context_system::instance();
1233         self::validate_context($context);
1235         // Warnings array, it can be empty at the end but is mandatory.
1236         $warnings = array();
1238         $removed = user_remove_user_device($params['uuid'], $params['appid']);
1240         if (!$removed) {
1241             $warnings[] = array(
1242                 'item' => $params['uuid'],
1243                 'warningcode' => 'devicedoesnotexist',
1244                 'message' => 'The device doesn\'t exists in the database'
1245             );
1246         }
1248         $result = array(
1249             'removed' => $removed,
1250             'warnings' => $warnings
1251         );
1253         return $result;
1254     }
1256     /**
1257      * Returns description of method result value.
1258      *
1259      * @return external_multiple_structure
1260      * @since Moodle 2.9
1261      */
1262     public static function remove_user_device_returns() {
1263         return new external_single_structure(
1264             array(
1265                 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
1266                 'warnings' => new external_warnings(),
1267             )
1268         );
1269     }
1271     /**
1272      * Returns description of method parameters
1273      *
1274      * @return external_function_parameters
1275      * @since Moodle 2.9
1276      */
1277     public static function view_user_list_parameters() {
1278         return new external_function_parameters(
1279             array(
1280                 'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site')
1281             )
1282         );
1283     }
1285     /**
1286      * Trigger the user_list_viewed event.
1287      *
1288      * @param int $courseid id of course
1289      * @return array of warnings and status result
1290      * @since Moodle 2.9
1291      * @throws moodle_exception
1292      */
1293     public static function view_user_list($courseid) {
1294         global $CFG;
1295         require_once($CFG->dirroot . "/user/lib.php");
1297         $params = self::validate_parameters(self::view_user_list_parameters(),
1298                                             array(
1299                                                 'courseid' => $courseid
1300                                             ));
1302         $warnings = array();
1304         if (empty($params['courseid'])) {
1305             $params['courseid'] = SITEID;
1306         }
1308         $course = get_course($params['courseid']);
1310         if ($course->id == SITEID) {
1311             $context = context_system::instance();
1312         } else {
1313             $context = context_course::instance($course->id);
1314         }
1315         self::validate_context($context);
1317         if ($course->id == SITEID) {
1318             require_capability('moodle/site:viewparticipants', $context);
1319         } else {
1320             require_capability('moodle/course:viewparticipants', $context);
1321         }
1323         user_list_view($course, $context);
1325         $result = array();
1326         $result['status'] = true;
1327         $result['warnings'] = $warnings;
1328         return $result;
1329     }
1331     /**
1332      * Returns description of method result value
1333      *
1334      * @return external_description
1335      * @since Moodle 2.9
1336      */
1337     public static function view_user_list_returns() {
1338         return new external_single_structure(
1339             array(
1340                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1341                 'warnings' => new external_warnings()
1342             )
1343         );
1344     }
1346     /**
1347      * Returns description of method parameters
1348      *
1349      * @return external_function_parameters
1350      * @since Moodle 2.9
1351      */
1352     public static function view_user_profile_parameters() {
1353         return new external_function_parameters(
1354             array(
1355                 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1356                 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
1357             )
1358         );
1359     }
1361     /**
1362      * Trigger the user profile viewed event.
1363      *
1364      * @param int $userid id of user
1365      * @param int $courseid id of course
1366      * @return array of warnings and status result
1367      * @since Moodle 2.9
1368      * @throws moodle_exception
1369      */
1370     public static function view_user_profile($userid, $courseid = 0) {
1371         global $CFG, $USER;
1372         require_once($CFG->dirroot . "/user/profile/lib.php");
1374         $params = self::validate_parameters(self::view_user_profile_parameters(),
1375                                             array(
1376                                                 'userid' => $userid,
1377                                                 'courseid' => $courseid
1378                                             ));
1380         $warnings = array();
1382         if (empty($params['userid'])) {
1383             $params['userid'] = $USER->id;
1384         }
1386         if (empty($params['courseid'])) {
1387             $params['courseid'] = SITEID;
1388         }
1390         $course = get_course($params['courseid']);
1391         $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1393         if ($user->deleted) {
1394             throw new moodle_exception('userdeleted');
1395         }
1396         if (isguestuser($user)) {
1397             // Can not view profile of guest - thre is nothing to see there.
1398             throw new moodle_exception('invaliduserid');
1399         }
1401         if ($course->id == SITEID) {
1402             $coursecontext = context_system::instance();;
1403         } else {
1404             $coursecontext = context_course::instance($course->id);
1405         }
1406         self::validate_context($coursecontext);
1408         $currentuser = $USER->id == $user->id;
1409         $usercontext = context_user::instance($user->id);
1411         if (!$currentuser and
1412                 !has_capability('moodle/user:viewdetails', $coursecontext) and
1413                 !has_capability('moodle/user:viewdetails', $usercontext)) {
1414             throw new moodle_exception('cannotviewprofile');
1415         }
1417         // Case like user/profile.php.
1418         if ($course->id == SITEID) {
1419             profile_view($user, $usercontext);
1420         } else {
1421             // Case like user/view.php.
1422             if (!$currentuser and !is_enrolled($coursecontext, $user->id)) {
1423                 throw new moodle_exception('notenrolledprofile');
1424             }
1426             profile_view($user, $coursecontext, $course);
1427         }
1429         $result = array();
1430         $result['status'] = true;
1431         $result['warnings'] = $warnings;
1432         return $result;
1433     }
1435     /**
1436      * Returns description of method result value
1437      *
1438      * @return external_description
1439      * @since Moodle 2.9
1440      */
1441     public static function view_user_profile_returns() {
1442         return new external_single_structure(
1443             array(
1444                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1445                 'warnings' => new external_warnings()
1446             )
1447         );
1448     }
1452  /**
1453   * Deprecated user external functions
1454   *
1455   * @package    core_user
1456   * @copyright  2009 Petr Skodak
1457   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1458   * @since Moodle 2.0
1459   * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
1460   * @see core_user_external
1461   */
1462 class moodle_user_external extends external_api {
1464     /**
1465      * Returns description of method parameters
1466      *
1467      * @return external_function_parameters
1468      * @since Moodle 2.0
1469      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1470      * @see core_user_external::create_users_parameters()
1471      */
1472     public static function create_users_parameters() {
1473         return core_user_external::create_users_parameters();
1474     }
1476     /**
1477      * Create one or more users
1478      *
1479      * @param array $users  An array of users to create.
1480      * @return array An array of arrays
1481      * @since Moodle 2.0
1482      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1483      * @see core_user_external::create_users()
1484      */
1485     public static function create_users($users) {
1486         return core_user_external::create_users($users);
1487     }
1489     /**
1490      * Returns description of method result value
1491      *
1492      * @return external_description
1493      * @since Moodle 2.0
1494      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1495      * @see core_user_external::create_users_returns()
1496      */
1497     public static function create_users_returns() {
1498         return core_user_external::create_users_returns();
1499     }
1501     /**
1502      * Marking the method as deprecated.
1503      *
1504      * @return bool
1505      */
1506     public static function create_users_is_deprecated() {
1507         return true;
1508     }
1510     /**
1511      * Returns description of method parameters
1512      *
1513      * @return external_function_parameters
1514      * @since Moodle 2.0
1515      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1516      * @see core_user_external::delete_users_parameters()
1517      */
1518     public static function delete_users_parameters() {
1519         return core_user_external::delete_users_parameters();
1520     }
1522     /**
1523      * Delete users
1524      *
1525      * @param array $userids
1526      * @return null
1527      * @since Moodle 2.0
1528      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1529      * @see core_user_external::delete_users()
1530      */
1531     public static function delete_users($userids) {
1532         return core_user_external::delete_users($userids);
1533     }
1535     /**
1536      * Returns description of method result value
1537      *
1538      * @return null
1539      * @since Moodle 2.0
1540      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1541      * @see core_user_external::delete_users_returns()
1542      */
1543     public static function delete_users_returns() {
1544         return core_user_external::delete_users_returns();
1545     }
1547     /**
1548      * Marking the method as deprecated.
1549      *
1550      * @return bool
1551      */
1552     public static function delete_users_is_deprecated() {
1553         return true;
1554     }
1556     /**
1557      * Returns description of method parameters
1558      *
1559      * @return external_function_parameters
1560      * @since Moodle 2.0
1561      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1562      * @see core_user_external::update_users_parameters()
1563      */
1564     public static function update_users_parameters() {
1565         return core_user_external::update_users_parameters();
1566     }
1568     /**
1569      * Update users
1570      *
1571      * @param array $users
1572      * @return null
1573      * @since Moodle 2.0
1574      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1575      * @see core_user_external::update_users()
1576      */
1577     public static function update_users($users) {
1578         return core_user_external::update_users($users);
1579     }
1581     /**
1582      * Returns description of method result value
1583      *
1584      * @return null
1585      * @since Moodle 2.0
1586      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1587      * @see core_user_external::update_users_returns()
1588      */
1589     public static function update_users_returns() {
1590         return core_user_external::update_users_returns();
1591     }
1593     /**
1594      * Marking the method as deprecated.
1595      *
1596      * @return bool
1597      */
1598     public static function update_users_is_deprecated() {
1599         return true;
1600     }
1602     /**
1603      * Returns description of method parameters
1604      *
1605      * @return external_function_parameters
1606      * @since Moodle 2.0
1607      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1608      * @see core_user_external::get_users_by_id_parameters()
1609      */
1610     public static function get_users_by_id_parameters() {
1611         return core_user_external::get_users_by_id_parameters();
1612     }
1614     /**
1615      * Get user information
1616      * - This function is matching the permissions of /user/profil.php
1617      * - It is also matching some permissions from /user/editadvanced.php for the following fields:
1618      *   auth, confirmed, idnumber, lang, theme, timezone, mailformat
1619      *
1620      * @param array $userids  array of user ids
1621      * @return array An array of arrays describing users
1622      * @since Moodle 2.0
1623      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1624      * @see core_user_external::get_users_by_id()
1625      */
1626     public static function get_users_by_id($userids) {
1627         return core_user_external::get_users_by_id($userids);
1628     }
1630     /**
1631      * Returns description of method result value
1632      *
1633      * @return external_description
1634      * @since Moodle 2.0
1635      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1636      * @see core_user_external::get_users_by_id_returns()
1637      */
1638     public static function get_users_by_id_returns() {
1639         return core_user_external::get_users_by_id_returns();
1640     }
1642     /**
1643      * Marking the method as deprecated.
1644      *
1645      * @return bool
1646      */
1647     public static function get_users_by_id_is_deprecated() {
1648         return true;
1649     }
1651     /**
1652      * Returns description of method parameters
1653      *
1654      * @return external_function_parameters
1655      * @since Moodle 2.1
1656      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1657      * @see core_user_external::get_course_user_profiles_parameters()
1658      */
1659     public static function get_course_participants_by_id_parameters() {
1660         return core_user_external::get_course_user_profiles_parameters();
1661     }
1663     /**
1664      * Get course participant's details
1665      *
1666      * @param array $userlist  array of user ids and according course ids
1667      * @return array An array of arrays describing course participants
1668      * @since Moodle 2.1
1669      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1670      * @see core_user_external::get_course_user_profiles()
1671      */
1672     public static function get_course_participants_by_id($userlist) {
1673         return core_user_external::get_course_user_profiles($userlist);
1674     }
1676     /**
1677      * Returns description of method result value
1678      *
1679      * @return external_description
1680      * @since Moodle 2.1
1681      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1682      * @see core_user_external::get_course_user_profiles_returns()
1683      */
1684     public static function get_course_participants_by_id_returns() {
1685         return core_user_external::get_course_user_profiles_returns();
1686     }
1688     /**
1689      * Marking the method as deprecated.
1690      *
1691      * @return bool
1692      */
1693     public static function get_course_participants_by_id_is_deprecated() {
1694         return true;
1695     }
1697     /**
1698      * Returns description of method parameters
1699      *
1700      * @return external_function_parameters
1701      * @since Moodle 2.1
1702      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1703      * @see core_enrol_external::get_enrolled_users_parameters()
1704      */
1705     public static function get_users_by_courseid_parameters() {
1706         global $CFG;
1707         require_once($CFG->dirroot . '/enrol/externallib.php');
1708         return core_enrol_external::get_enrolled_users_parameters();
1709     }
1711     /**
1712      * Get course participants details
1713      *
1714      * @param int $courseid  course id
1715      * @param array $options options {
1716      *                                'name' => option name
1717      *                                'value' => option value
1718      *                               }
1719      * @return array An array of users
1720      * @since Moodle 2.1
1721      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1722      * @see core_enrol_external::get_enrolled_users()
1723      */
1724     public static function get_users_by_courseid($courseid, $options = array()) {
1725         global $CFG;
1726         require_once($CFG->dirroot . '/enrol/externallib.php');
1727         return core_enrol_external::get_enrolled_users($courseid, $options);
1728     }
1729     /**
1730      * Returns description of method result value
1731      *
1732      * @return external_description
1733      * @since Moodle 2.1
1734      * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1735      * @see core_enrol_external::get_enrolled_users_returns()
1736      */
1737     public static function get_users_by_courseid_returns() {
1738         global $CFG;
1739         require_once($CFG->dirroot . '/enrol/externallib.php');
1740         return core_enrol_external::get_enrolled_users_returns();
1741     }
1743     /**
1744      * Marking the method as deprecated.
1745      *
1746      * @return bool
1747      */
1748     public static function get_users_by_courseid_is_deprecated() {
1749         return true;
1750     }