forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
externallib.php
2041 lines (1827 loc) · 85.6 KB
/
externallib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* External user API
*
* @package core_user
* @category external
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once("$CFG->libdir/externallib.php");
/**
* User external functions
*
* @package core_user
* @category external
* @copyright 2011 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.2
*/
class core_user_external extends external_api {
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.2
*/
public static function create_users_parameters() {
global $CFG;
$userfields = [
'createpassword' => new external_value(PARAM_BOOL, 'True if password should be created and mailed to user.',
VALUE_OPTIONAL),
// General.
'username' => new external_value(core_user::get_property_type('username'),
'Username policy is defined in Moodle security config.'),
'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
VALUE_DEFAULT, 'manual', core_user::get_property_null('auth')),
'password' => new external_value(core_user::get_property_type('password'),
'Plain text password consisting of any characters', VALUE_OPTIONAL),
'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user'),
'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user'),
'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address'),
'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email display', VALUE_OPTIONAL),
'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
'country' => new external_value(core_user::get_property_type('country'),
'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
'timezone' => new external_value(core_user::get_property_type('timezone'),
'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML',
VALUE_OPTIONAL),
// Additional names.
'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'),
'The first name(s) phonetically of the user', VALUE_OPTIONAL),
'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'),
'The family name phonetically of the user', VALUE_OPTIONAL),
'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user',
VALUE_OPTIONAL),
'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user',
VALUE_OPTIONAL),
// Interests.
'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL),
// Optional.
'idnumber' => new external_value(core_user::get_property_type('idnumber'),
'An arbitrary ID code number perhaps from the institution', VALUE_DEFAULT, ''),
'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
// Other user preferences stored in the user table.
'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
VALUE_DEFAULT, core_user::get_property_default('lang'), core_user::get_property_null('lang')),
'calendartype' => new external_value(core_user::get_property_type('calendartype'),
'Calendar type such as "gregorian", must exist on server', VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
'theme' => new external_value(core_user::get_property_type('theme'),
'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
'mailformat' => new external_value(core_user::get_property_type('mailformat'),
'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
// Custom user profile fields.
'customfields' => new external_multiple_structure(
new external_single_structure(
[
'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
'value' => new external_value(PARAM_RAW, 'The value of the custom field')
]
), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
// User preferences.
'preferences' => new external_multiple_structure(
new external_single_structure(
[
'type' => new external_value(PARAM_RAW, 'The name of the preference'),
'value' => new external_value(PARAM_RAW, 'The value of the preference')
]
), 'User preferences', VALUE_OPTIONAL),
];
return new external_function_parameters(
[
'users' => new external_multiple_structure(
new external_single_structure($userfields)
)
]
);
}
/**
* Create one or more users.
*
* @throws invalid_parameter_exception
* @param array $users An array of users to create.
* @return array An array of arrays
* @since Moodle 2.2
*/
public static function create_users($users) {
global $CFG, $DB;
require_once($CFG->dirroot."/lib/weblib.php");
require_once($CFG->dirroot."/user/lib.php");
require_once($CFG->dirroot."/user/editlib.php");
require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
// Ensure the current user is allowed to run this function.
$context = context_system::instance();
self::validate_context($context);
require_capability('moodle/user:create', $context);
// Do basic automatic PARAM checks on incoming data, using params description.
// If any problems are found then exceptions are thrown with helpful error messages.
$params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
$availableauths = core_component::get_plugin_list('auth');
unset($availableauths['mnet']); // These would need mnethostid too.
unset($availableauths['webservice']); // We do not want new webservice users for now.
$availablethemes = core_component::get_plugin_list('theme');
$availablelangs = get_string_manager()->get_list_of_translations();
$transaction = $DB->start_delegated_transaction();
$userids = array();
foreach ($params['users'] as $user) {
// Make sure that the username, firstname and lastname are not blank.
foreach (array('username', 'firstname', 'lastname') as $fieldname) {
if (trim($user[$fieldname]) === '') {
throw new invalid_parameter_exception('The field '.$fieldname.' cannot be blank');
}
}
// Make sure that the username doesn't already exist.
if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
throw new invalid_parameter_exception('Username already exists: '.$user['username']);
}
// Make sure auth is valid.
if (empty($availableauths[$user['auth']])) {
throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
}
// Make sure lang is valid.
if (empty($availablelangs[$user['lang']])) {
throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
}
// Make sure lang is valid.
if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
// so no default value
// We need to test if the client sent it
// => !empty($user['theme']).
throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
}
// Make sure we have a password or have to create one.
$authplugin = get_auth_plugin($user['auth']);
if ($authplugin->is_internal() && empty($user['password']) && empty($user['createpassword'])) {
throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
}
$user['confirmed'] = true;
$user['mnethostid'] = $CFG->mnet_localhost_id;
// Start of user info validation.
// Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
if (!validate_email($user['email'])) {
throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
} else if (empty($CFG->allowaccountssameemail)) {
// Make a case-insensitive query for the given email address.
$select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid';
$params = array(
'email' => $user['email'],
'mnethostid' => $user['mnethostid']
);
// If there are other user(s) that already have the same email, throw an error.
if ($DB->record_exists_select('user', $select, $params)) {
throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
}
}
// End of user info validation.
$createpassword = !empty($user['createpassword']);
unset($user['createpassword']);
$updatepassword = false;
if ($authplugin->is_internal()) {
if ($createpassword) {
$user['password'] = '';
} else {
$updatepassword = true;
}
} else {
$user['password'] = AUTH_PASSWORD_NOT_CACHED;
}
// Create the user data now!
$user['id'] = user_create_user($user, $updatepassword, false);
$userobject = (object)$user;
// Set user interests.
if (!empty($user['interests'])) {
$trimmedinterests = array_map('trim', explode(',', $user['interests']));
$interests = array_filter($trimmedinterests, function($value) {
return !empty($value);
});
useredit_update_interests($userobject, $interests);
}
// Custom fields.
if (!empty($user['customfields'])) {
foreach ($user['customfields'] as $customfield) {
// Profile_save_data() saves profile file it's expecting a user with the correct id,
// and custom field to be named profile_field_"shortname".
$user["profile_field_".$customfield['type']] = $customfield['value'];
}
profile_save_data((object) $user);
}
if ($createpassword) {
setnew_password_and_mail($userobject);
unset_user_preference('create_password', $userobject);
set_user_preference('auth_forcepasswordchange', 1, $userobject);
}
// Trigger event.
\core\event\user_created::create_from_userid($user['id'])->trigger();
// Preferences.
if (!empty($user['preferences'])) {
$userpref = (object)$user;
foreach ($user['preferences'] as $preference) {
$userpref->{'preference_'.$preference['type']} = $preference['value'];
}
useredit_update_user_preference($userpref);
}
$userids[] = array('id' => $user['id'], 'username' => $user['username']);
}
$transaction->allow_commit();
return $userids;
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 2.2
*/
public static function create_users_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(core_user::get_property_type('id'), 'user id'),
'username' => new external_value(core_user::get_property_type('username'), 'user name'),
)
)
);
}
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.2
*/
public static function delete_users_parameters() {
return new external_function_parameters(
array(
'userids' => new external_multiple_structure(new external_value(core_user::get_property_type('id'), 'user ID')),
)
);
}
/**
* Delete users
*
* @throws moodle_exception
* @param array $userids
* @return null
* @since Moodle 2.2
*/
public static function delete_users($userids) {
global $CFG, $DB, $USER;
require_once($CFG->dirroot."/user/lib.php");
// Ensure the current user is allowed to run this function.
$context = context_system::instance();
require_capability('moodle/user:delete', $context);
self::validate_context($context);
$params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
$transaction = $DB->start_delegated_transaction();
foreach ($params['userids'] as $userid) {
$user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
// Must not allow deleting of admins or self!!!
if (is_siteadmin($user)) {
throw new moodle_exception('useradminodelete', 'error');
}
if ($USER->id == $user->id) {
throw new moodle_exception('usernotdeletederror', 'error');
}
user_delete_user($user);
}
$transaction->allow_commit();
return null;
}
/**
* Returns description of method result value
*
* @return null
* @since Moodle 2.2
*/
public static function delete_users_returns() {
return null;
}
/**
* Returns description of method parameters.
*
* @return external_function_parameters
* @since Moodle 3.2
*/
public static function update_user_preferences_parameters() {
return new external_function_parameters(
array(
'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
'emailstop' => new external_value(core_user::get_property_type('emailstop'),
'Enable or disable notifications for this user', VALUE_DEFAULT, null),
'preferences' => new external_multiple_structure(
new external_single_structure(
array(
'type' => new external_value(PARAM_RAW, 'The name of the preference'),
'value' => new external_value(PARAM_RAW, 'The value of the preference, do not set this field if you
want to remove (unset) the current value.', VALUE_DEFAULT, null),
)
), 'User preferences', VALUE_DEFAULT, array()
)
)
);
}
/**
* Update the user's preferences.
*
* @param int $userid
* @param bool|null $emailstop
* @param array $preferences
* @return null
* @since Moodle 3.2
*/
public static function update_user_preferences($userid = 0, $emailstop = null, $preferences = array()) {
global $USER, $CFG;
require_once($CFG->dirroot . '/user/lib.php');
require_once($CFG->dirroot . '/user/editlib.php');
require_once($CFG->dirroot . '/message/lib.php');
if (empty($userid)) {
$userid = $USER->id;
}
$systemcontext = context_system::instance();
self::validate_context($systemcontext);
$params = array(
'userid' => $userid,
'emailstop' => $emailstop,
'preferences' => $preferences
);
$params = self::validate_parameters(self::update_user_preferences_parameters(), $params);
$preferences = $params['preferences'];
// Preferences.
if (!empty($preferences)) {
$userpref = ['id' => $userid];
foreach ($preferences as $preference) {
/*
* Rename user message provider preferences to avoid orphan settings on old app versions.
* @todo Remove this "translation" block on MDL-73284.
*/
if (preg_match('/message_provider_.*_loggedin/', $preference['type']) ||
preg_match('/message_provider_.*_loggedoff/', $preference['type'])) {
$nameparts = explode('_', $preference['type']);
array_pop($nameparts);
$preference['type'] = implode('_', $nameparts).'_enabled';
}
$userpref['preference_' . $preference['type']] = $preference['value'];
}
useredit_update_user_preference($userpref);
}
// Check if they want to update the email.
if ($emailstop !== null) {
$otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST);
core_user::require_active_user($otheruser);
if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) {
$user = new stdClass();
$user->id = $userid;
$user->emailstop = $emailstop;
user_update_user($user);
// Update the $USER if we should.
if ($userid == $USER->id) {
$USER->emailstop = $emailstop;
}
}
}
return null;
}
/**
* Returns description of method result value
*
* @return null
* @since Moodle 3.2
*/
public static function update_user_preferences_returns() {
return null;
}
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.2
*/
public static function update_users_parameters() {
$userfields = [
'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
// General.
'username' => new external_value(core_user::get_property_type('username'),
'Username policy is defined in Moodle security config.', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
'suspended' => new external_value(core_user::get_property_type('suspended'),
'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
'password' => new external_value(core_user::get_property_type('password'),
'Plain text password consisting of any characters', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user',
VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user',
VALUE_OPTIONAL),
'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL,
'', NULL_NOT_ALLOWED),
'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email display', VALUE_OPTIONAL),
'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
'country' => new external_value(core_user::get_property_type('country'),
'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
'timezone' => new external_value(core_user::get_property_type('timezone'),
'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML',
VALUE_OPTIONAL),
// User picture.
'userpicture' => new external_value(PARAM_INT,
'The itemid where the new user picture has been uploaded to, 0 to delete', VALUE_OPTIONAL),
// Additional names.
'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'),
'The first name(s) phonetically of the user', VALUE_OPTIONAL),
'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'),
'The family name phonetically of the user', VALUE_OPTIONAL),
'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user',
VALUE_OPTIONAL),
'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user',
VALUE_OPTIONAL),
// Interests.
'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL),
// Optional.
'idnumber' => new external_value(core_user::get_property_type('idnumber'),
'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
'institution' => new external_value(core_user::get_property_type('institution'), 'Institution', VALUE_OPTIONAL),
'department' => new external_value(core_user::get_property_type('department'), 'Department', VALUE_OPTIONAL),
'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone', VALUE_OPTIONAL),
'phone2' => new external_value(core_user::get_property_type('phone2'), 'Mobile phone', VALUE_OPTIONAL),
'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
// Other user preferences stored in the user table.
'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
'calendartype' => new external_value(core_user::get_property_type('calendartype'),
'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
'theme' => new external_value(core_user::get_property_type('theme'),
'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
'mailformat' => new external_value(core_user::get_property_type('mailformat'),
'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
// Custom user profile fields.
'customfields' => new external_multiple_structure(
new external_single_structure(
[
'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
'value' => new external_value(PARAM_RAW, 'The value of the custom field')
]
), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
// User preferences.
'preferences' => new external_multiple_structure(
new external_single_structure(
[
'type' => new external_value(PARAM_RAW, 'The name of the preference'),
'value' => new external_value(PARAM_RAW, 'The value of the preference')
]
), 'User preferences', VALUE_OPTIONAL),
];
return new external_function_parameters(
[
'users' => new external_multiple_structure(
new external_single_structure($userfields)
)
]
);
}
/**
* Update users
*
* @param array $users
* @return null
* @since Moodle 2.2
*/
public static function update_users($users) {
global $CFG, $DB, $USER;
require_once($CFG->dirroot."/user/lib.php");
require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
require_once($CFG->dirroot.'/user/editlib.php');
// Ensure the current user is allowed to run this function.
$context = context_system::instance();
require_capability('moodle/user:update', $context);
self::validate_context($context);
$params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
$filemanageroptions = array('maxbytes' => $CFG->maxbytes,
'subdirs' => 0,
'maxfiles' => 1,
'accepted_types' => 'optimised_image');
$warnings = array();
foreach ($params['users'] as $user) {
// Catch any exception while updating a user and return it as a warning.
try {
$transaction = $DB->start_delegated_transaction();
// First check the user exists.
if (!$existinguser = core_user::get_user($user['id'])) {
throw new moodle_exception('invaliduserid', '', '', null,
'Invalid user ID');
}
// Check if we are trying to update an admin.
if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
throw new moodle_exception('usernotupdatedadmin', '', '', null,
'Cannot update admin accounts');
}
// Other checks (deleted, remote or guest users).
if ($existinguser->deleted) {
throw new moodle_exception('usernotupdateddeleted', '', '', null,
'User is a deleted user');
}
if (is_mnet_remote_user($existinguser)) {
throw new moodle_exception('usernotupdatedremote', '', '', null,
'User is a remote user');
}
if (isguestuser($existinguser->id)) {
throw new moodle_exception('usernotupdatedguest', '', '', null,
'Cannot update guest account');
}
// Check duplicated emails.
if (isset($user['email']) && $user['email'] !== $existinguser->email) {
if (!validate_email($user['email'])) {
throw new moodle_exception('useremailinvalid', '', '', null,
'Invalid email address');
} else if (empty($CFG->allowaccountssameemail)) {
// Make a case-insensitive query for the given email address
// and make sure to exclude the user being updated.
$select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid';
$params = array(
'email' => $user['email'],
'mnethostid' => $CFG->mnet_localhost_id,
'userid' => $user['id']
);
// Skip if there are other user(s) that already have the same email.
if ($DB->record_exists_select('user', $select, $params)) {
throw new moodle_exception('useremailduplicate', '', '', null,
'Duplicate email address');
}
}
}
user_update_user($user, true, false);
$userobject = (object)$user;
// Update user picture if it was specified for this user.
if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
$userobject->deletepicture = null;
if ($user['userpicture'] == 0) {
$userobject->deletepicture = true;
} else {
$userobject->imagefile = $user['userpicture'];
}
core_user::update_picture($userobject, $filemanageroptions);
}
// Update user interests.
if (!empty($user['interests'])) {
$trimmedinterests = array_map('trim', explode(',', $user['interests']));
$interests = array_filter($trimmedinterests, function($value) {
return !empty($value);
});
useredit_update_interests($userobject, $interests);
}
// Update user custom fields.
if (!empty($user['customfields'])) {
foreach ($user['customfields'] as $customfield) {
// Profile_save_data() saves profile file it's expecting a user with the correct id,
// and custom field to be named profile_field_"shortname".
$user["profile_field_".$customfield['type']] = $customfield['value'];
}
profile_save_data((object) $user);
}
// Trigger event.
\core\event\user_updated::create_from_userid($user['id'])->trigger();
// Preferences.
if (!empty($user['preferences'])) {
$userpref = clone($existinguser);
foreach ($user['preferences'] as $preference) {
$userpref->{'preference_'.$preference['type']} = $preference['value'];
}
useredit_update_user_preference($userpref);
}
if (isset($user['suspended']) and $user['suspended']) {
\core\session\manager::kill_user_sessions($user['id']);
}
$transaction->allow_commit();
} catch (Exception $e) {
try {
$transaction->rollback($e);
} catch (Exception $e) {
$warning = [];
$warning['item'] = 'user';
$warning['itemid'] = $user['id'];
if ($e instanceof moodle_exception) {
$warning['warningcode'] = $e->errorcode;
} else {
$warning['warningcode'] = $e->getCode();
}
$warning['message'] = $e->getMessage();
$warnings[] = $warning;
}
}
}
return ['warnings' => $warnings];
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 2.2
*/
public static function update_users_returns() {
return new external_single_structure(
array(
'warnings' => new external_warnings()
)
);
}
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.4
*/
public static function get_users_by_field_parameters() {
return new external_function_parameters(
array(
'field' => new external_value(PARAM_ALPHA, 'the search field can be
\'id\' or \'idnumber\' or \'username\' or \'email\''),
'values' => new external_multiple_structure(
new external_value(PARAM_RAW, 'the value to match'))
)
);
}
/**
* Get user information for a unique field.
*
* @throws coding_exception
* @throws invalid_parameter_exception
* @param string $field
* @param array $values
* @return array An array of arrays containg user profiles.
* @since Moodle 2.4
*/
public static function get_users_by_field($field, $values) {
global $CFG, $USER, $DB;
require_once($CFG->dirroot . "/user/lib.php");
$params = self::validate_parameters(self::get_users_by_field_parameters(),
array('field' => $field, 'values' => $values));
// This array will keep all the users that are allowed to be searched,
// according to the current user's privileges.
$cleanedvalues = array();
switch ($field) {
case 'id':
$paramtype = core_user::get_property_type('id');
break;
case 'idnumber':
$paramtype = core_user::get_property_type('idnumber');
break;
case 'username':
$paramtype = core_user::get_property_type('username');
break;
case 'email':
$paramtype = core_user::get_property_type('email');
break;
default:
throw new coding_exception('invalid field parameter',
'The search field \'' . $field . '\' is not supported, look at the web service documentation');
}
// Clean the values.
foreach ($values as $value) {
$cleanedvalue = clean_param($value, $paramtype);
if ( $value != $cleanedvalue) {
throw new invalid_parameter_exception('The field \'' . $field .
'\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
}
$cleanedvalues[] = $cleanedvalue;
}
// Retrieve the users.
$users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
$context = context_system::instance();
self::validate_context($context);
// Finally retrieve each users information.
$returnedusers = array();
foreach ($users as $user) {
$userdetails = user_get_user_details_courses($user);
// Return the user only if the searched field is returned.
// Otherwise it means that the $USER was not allowed to search the returned user.
if (!empty($userdetails) and !empty($userdetails[$field])) {
$returnedusers[] = $userdetails;
}
}
return $returnedusers;
}
/**
* Returns description of method result value
*
* @return external_multiple_structure
* @since Moodle 2.4
*/
public static function get_users_by_field_returns() {
return new external_multiple_structure(self::user_description());
}
/**
* Returns description of get_users() parameters.
*
* @return external_function_parameters
* @since Moodle 2.5
*/
public static function get_users_parameters() {
return new external_function_parameters(
array(
'criteria' => new external_multiple_structure(
new external_single_structure(
array(
'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
"id" (int) matching user id,
"lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
"firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
"idnumber" (string) matching user idnumber,
"username" (string) matching user username,
"email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
"auth" (string) matching user auth plugin'),
'value' => new external_value(PARAM_RAW, 'the value to search')
)
), 'the key/value pairs to be considered in user search. Values can not be empty.
Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
key occurences are forbidden.
The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
the search is still executed on the valid criterias.
You can search without criteria, but the function is not designed for it.
It could very slow or timeout. The function is designed to search some specific users.'
)
)
);
}
/**
* Retrieve matching user.
*
* @throws moodle_exception
* @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
* @return array An array of arrays containing user profiles.
* @since Moodle 2.5
*/
public static function get_users($criteria = array()) {
global $CFG, $USER, $DB;
require_once($CFG->dirroot . "/user/lib.php");
$params = self::validate_parameters(self::get_users_parameters(),
array('criteria' => $criteria));
// Validate the criteria and retrieve the users.
$users = array();
$warnings = array();
$sqlparams = array();
$usedkeys = array();
// Do not retrieve deleted users.
$sql = ' deleted = 0';
foreach ($params['criteria'] as $criteriaindex => $criteria) {
// Check that the criteria has never been used.
if (array_key_exists($criteria['key'], $usedkeys)) {
throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
} else {
$usedkeys[$criteria['key']] = true;
}
$invalidcriteria = false;
// Clean the parameters.
$paramtype = PARAM_RAW;
switch ($criteria['key']) {
case 'id':
$paramtype = core_user::get_property_type('id');
break;
case 'idnumber':
$paramtype = core_user::get_property_type('idnumber');
break;
case 'username':
$paramtype = core_user::get_property_type('username');
break;
case 'email':
// We use PARAM_RAW to allow searches with %.
$paramtype = core_user::get_property_type('email');
break;
case 'auth':
$paramtype = core_user::get_property_type('auth');
break;
case 'lastname':
case 'firstname':
$paramtype = core_user::get_property_type('firstname');
break;
default:
// Send back a warning that this search key is not supported in this version.
// This warning will make the function extandable without breaking clients.
$warnings[] = array(
'item' => $criteria['key'],
'warningcode' => 'invalidfieldparameter',
'message' =>
'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
);
// Do not add this invalid criteria to the created SQL request.
$invalidcriteria = true;
unset($params['criteria'][$criteriaindex]);
break;
}
if (!$invalidcriteria) {
$cleanedvalue = clean_param($criteria['value'], $paramtype);
$sql .= ' AND ';
// Create the SQL.
switch ($criteria['key']) {
case 'id':
case 'idnumber':
case 'username':
case 'auth':
$sql .= $criteria['key'] . ' = :' . $criteria['key'];
$sqlparams[$criteria['key']] = $cleanedvalue;
break;
case 'email':
case 'lastname':
case 'firstname':
$sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
$sqlparams[$criteria['key']] = $cleanedvalue;
break;
default:
break;
}
}
}
$users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
// Finally retrieve each users information.
$returnedusers = array();
foreach ($users as $user) {
$userdetails = user_get_user_details_courses($user);
// Return the user only if all the searched fields are returned.
// Otherwise it means that the $USER was not allowed to search the returned user.
if (!empty($userdetails)) {
$validuser = true;
foreach ($params['criteria'] as $criteria) {
if (empty($userdetails[$criteria['key']])) {
$validuser = false;
}
}
if ($validuser) {
$returnedusers[] = $userdetails;
}
}
}
return array('users' => $returnedusers, 'warnings' => $warnings);
}
/**
* Returns description of get_users result value.
*
* @return external_description
* @since Moodle 2.5
*/
public static function get_users_returns() {
return new external_single_structure(
array('users' => new external_multiple_structure(
self::user_description()
),
'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
)
);
}
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.2
*/
public static function get_course_user_profiles_parameters() {
return new external_function_parameters(
array(