forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
externallib_test.php
1793 lines (1512 loc) · 76.4 KB
/
externallib_test.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/>.
/**
* User external PHPunit tests
*
* @package core_user
* @category external
* @copyright 2012 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.4
*/
namespace core_user;
use core_external\external_api;
use core_files_external;
use core_user_external;
use externallib_advanced_testcase;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
require_once($CFG->dirroot . '/user/externallib.php');
require_once($CFG->dirroot . '/files/externallib.php');
class externallib_test extends externallib_advanced_testcase {
/**
* Test get_users
*/
public function test_get_users() {
global $USER, $CFG;
$this->resetAfterTest(true);
$course = self::getDataGenerator()->create_course();
$user1 = array(
'username' => 'usernametest1',
'idnumber' => 'idnumbertest1',
'firstname' => 'First Name User Test 1',
'lastname' => 'Last Name User Test 1',
'email' => '[email protected]',
'address' => '2 Test Street Perth 6000 WA',
'phone1' => '01010101010',
'phone2' => '02020203',
'department' => 'Department of user 1',
'institution' => 'Institution of user 1',
'description' => 'This is a description for user 1',
'descriptionformat' => FORMAT_MOODLE,
'city' => 'Perth',
'country' => 'AU'
);
$user1 = self::getDataGenerator()->create_user($user1);
set_config('usetags', 1);
require_once($CFG->dirroot . '/user/editlib.php');
$user1->interests = array('Cinema', 'Tennis', 'Dance', 'Guitar', 'Cooking');
useredit_update_interests($user1, $user1->interests);
$user2 = self::getDataGenerator()->create_user(
array('username' => 'usernametest2', 'idnumber' => 'idnumbertest2'));
$generatedusers = array();
$generatedusers[$user1->id] = $user1;
$generatedusers[$user2->id] = $user2;
$context = \context_course::instance($course->id);
$roleid = $this->assignUserCapability('moodle/user:viewdetails', $context->id);
// Enrol the users in the course.
$this->getDataGenerator()->enrol_user($user1->id, $course->id, $roleid);
$this->getDataGenerator()->enrol_user($user2->id, $course->id, $roleid);
$this->getDataGenerator()->enrol_user($USER->id, $course->id, $roleid);
// call as admin and receive all possible fields.
$this->setAdminUser();
$searchparams = array(
array('key' => 'invalidkey', 'value' => 'invalidkey'),
array('key' => 'email', 'value' => $user1->email),
array('key' => 'firstname', 'value' => $user1->firstname));
// Call the external function.
$result = core_user_external::get_users($searchparams);
// We need to execute the return values cleaning process to simulate the web service server
$result = external_api::clean_returnvalue(core_user_external::get_users_returns(), $result);
// Check we retrieve the good total number of enrolled users + no error on capability.
$expectedreturnedusers = 1;
$returnedusers = $result['users'];
$this->assertEquals($expectedreturnedusers, count($returnedusers));
foreach($returnedusers as $returneduser) {
$generateduser = ($returneduser['id'] == $USER->id) ?
$USER : $generatedusers[$returneduser['id']];
$this->assertEquals($generateduser->username, $returneduser['username']);
if (!empty($generateduser->idnumber)) {
$this->assertEquals($generateduser->idnumber, $returneduser['idnumber']);
}
$this->assertEquals($generateduser->firstname, $returneduser['firstname']);
$this->assertEquals($generateduser->lastname, $returneduser['lastname']);
if ($generateduser->email != $USER->email) { // Don't check the tmp modified $USER email.
$this->assertEquals($generateduser->email, $returneduser['email']);
}
if (!empty($generateduser->address)) {
$this->assertEquals($generateduser->address, $returneduser['address']);
}
if (!empty($generateduser->phone1)) {
$this->assertEquals($generateduser->phone1, $returneduser['phone1']);
}
if (!empty($generateduser->phone2)) {
$this->assertEquals($generateduser->phone2, $returneduser['phone2']);
}
if (!empty($generateduser->department)) {
$this->assertEquals($generateduser->department, $returneduser['department']);
}
if (!empty($generateduser->institution)) {
$this->assertEquals($generateduser->institution, $returneduser['institution']);
}
if (!empty($generateduser->description)) {
$this->assertEquals($generateduser->description, $returneduser['description']);
}
if (!empty($generateduser->descriptionformat)) {
$this->assertEquals(FORMAT_HTML, $returneduser['descriptionformat']);
}
if (!empty($generateduser->city)) {
$this->assertEquals($generateduser->city, $returneduser['city']);
}
if (!empty($generateduser->country)) {
$this->assertEquals($generateduser->country, $returneduser['country']);
}
if (!empty($CFG->usetags) and !empty($generateduser->interests)) {
$this->assertEquals(implode(', ', $generateduser->interests), $returneduser['interests']);
}
}
// Test the invalid key warning.
$warnings = $result['warnings'];
$this->assertEquals(count($warnings), 1);
$warning = array_pop($warnings);
$this->assertEquals($warning['item'], 'invalidkey');
$this->assertEquals($warning['warningcode'], 'invalidfieldparameter');
// Test sending twice the same search field.
try {
$searchparams = array(
array('key' => 'firstname', 'value' => 'Canard'),
array('key' => 'email', 'value' => $user1->email),
array('key' => 'firstname', 'value' => $user1->firstname));
// Call the external function.
$result = core_user_external::get_users($searchparams);
$this->fail('Expecting \'keyalreadyset\' moodle_exception to be thrown.');
} catch (\moodle_exception $e) {
$this->assertEquals('keyalreadyset', $e->errorcode);
} catch (\Exception $e) {
$this->fail('Expecting \'keyalreadyset\' moodle_exception to be thrown.');
}
}
/**
* Test get_users_by_field
*/
public function test_get_users_by_field() {
global $USER, $CFG;
$this->resetAfterTest(true);
$generator = self::getDataGenerator();
// Create complex user profile field supporting multi-lang.
filter_set_global_state('multilang', TEXTFILTER_ON);
$statuses = 'UE\nSE\n<span lang="en" class="multilang">Other</span><span lang="es" class="multilang">Otro</span>';
$generator->create_custom_profile_field(
[
'datatype' => 'menu',
'shortname' => 'employmentstatus', 'name' => 'Employment status',
'param1' => $statuses
]
);
$course = $generator->create_course();
$user1 = array(
'username' => 'usernametest1',
'idnumber' => 'idnumbertest1',
'firstname' => 'First Name User Test 1',
'lastname' => 'Last Name User Test 1',
'email' => '[email protected]',
'address' => '2 Test Street Perth 6000 WA',
'phone1' => '01010101010',
'phone2' => '02020203',
'department' => 'Department of user 1',
'institution' => 'Institution of user 1',
'description' => 'This is a description for user 1',
'descriptionformat' => FORMAT_MOODLE,
'city' => 'Perth',
'country' => 'AU',
'profile_field_jobposition' => 'Manager',
'profile_field_employmentstatus' => explode('\n', $statuses)[2],
);
$user1 = $generator->create_user($user1);
if (!empty($CFG->usetags)) {
require_once($CFG->dirroot . '/user/editlib.php');
$user1->interests = array('Cinema', 'Tennis', 'Dance', 'Guitar', 'Cooking');
useredit_update_interests($user1, $user1->interests);
}
$user2 = $generator->create_user(
array('username' => 'usernametest2', 'idnumber' => 'idnumbertest2'));
$generatedusers = array();
$generatedusers[$user1->id] = $user1;
$generatedusers[$user2->id] = $user2;
$context = \context_course::instance($course->id);
$roleid = $this->assignUserCapability('moodle/user:viewdetails', $context->id);
// Enrol the users in the course.
$generator->enrol_user($user1->id, $course->id, $roleid, 'manual');
$generator->enrol_user($user2->id, $course->id, $roleid, 'manual');
$generator->enrol_user($USER->id, $course->id, $roleid, 'manual');
// call as admin and receive all possible fields.
$this->setAdminUser();
$fieldstosearch = array('id', 'idnumber', 'username', 'email');
foreach ($fieldstosearch as $fieldtosearch) {
// Call the external function.
$returnedusers = core_user_external::get_users_by_field($fieldtosearch,
array($USER->{$fieldtosearch}, $user1->{$fieldtosearch}, $user2->{$fieldtosearch}));
$returnedusers = external_api::clean_returnvalue(core_user_external::get_users_by_field_returns(), $returnedusers);
// Expected result differ following the searched field
// Admin user in the PHPunit framework doesn't have an idnumber.
if ($fieldtosearch == 'idnumber') {
$expectedreturnedusers = 2;
} else {
$expectedreturnedusers = 3;
}
// Check we retrieve the good total number of enrolled users + no error on capability.
$this->assertEquals($expectedreturnedusers, count($returnedusers));
foreach($returnedusers as $returneduser) {
$generateduser = ($returneduser['id'] == $USER->id) ?
$USER : $generatedusers[$returneduser['id']];
$this->assertEquals($generateduser->username, $returneduser['username']);
if (!empty($generateduser->idnumber)) {
$this->assertEquals($generateduser->idnumber, $returneduser['idnumber']);
}
$this->assertEquals($generateduser->firstname, $returneduser['firstname']);
$this->assertEquals($generateduser->lastname, $returneduser['lastname']);
if ($generateduser->email != $USER->email) { //don't check the tmp modified $USER email
$this->assertEquals($generateduser->email, $returneduser['email']);
}
if (!empty($generateduser->address)) {
$this->assertEquals($generateduser->address, $returneduser['address']);
}
if (!empty($generateduser->phone1)) {
$this->assertEquals($generateduser->phone1, $returneduser['phone1']);
}
if (!empty($generateduser->phone2)) {
$this->assertEquals($generateduser->phone2, $returneduser['phone2']);
}
if (!empty($generateduser->department)) {
$this->assertEquals($generateduser->department, $returneduser['department']);
}
if (!empty($generateduser->institution)) {
$this->assertEquals($generateduser->institution, $returneduser['institution']);
}
if (!empty($generateduser->description)) {
$this->assertEquals($generateduser->description, $returneduser['description']);
}
if (!empty($generateduser->descriptionformat) and isset($returneduser['descriptionformat'])) {
$this->assertEquals($generateduser->descriptionformat, $returneduser['descriptionformat']);
}
if (!empty($generateduser->city)) {
$this->assertEquals($generateduser->city, $returneduser['city']);
}
if (!empty($generateduser->country)) {
$this->assertEquals($generateduser->country, $returneduser['country']);
}
if (!empty($CFG->usetags) and !empty($generateduser->interests)) {
$this->assertEquals(implode(', ', $generateduser->interests), $returneduser['interests']);
}
// Default language and no theme were used for the user.
$this->assertEquals($CFG->lang, $returneduser['lang']);
$this->assertEmpty($returneduser['theme']);
if ($returneduser['id'] == $user1->id) {
$this->assertCount(1, $returneduser['customfields']);
$dbvalue = explode('\n', $statuses)[2];
$this->assertEquals($dbvalue, $returneduser['customfields'][0]['value']);
$this->assertEquals('Other', $returneduser['customfields'][0]['displayvalue']);
}
}
}
// Test that no result are returned for search by username if we are not admin
$this->setGuestUser();
// Call the external function.
$returnedusers = core_user_external::get_users_by_field('username',
array($USER->username, $user1->username, $user2->username));
$returnedusers = external_api::clean_returnvalue(core_user_external::get_users_by_field_returns(), $returnedusers);
// Only the own $USER username should be returned
$this->assertEquals(1, count($returnedusers));
// And finally test as one of the enrolled users.
$this->setUser($user1);
// Call the external function.
$returnedusers = core_user_external::get_users_by_field('username',
array($USER->username, $user1->username, $user2->username));
$returnedusers = external_api::clean_returnvalue(core_user_external::get_users_by_field_returns(), $returnedusers);
// Only the own $USER username should be returned still.
$this->assertEquals(1, count($returnedusers));
}
public function get_course_user_profiles_setup($capability) {
global $USER, $CFG;
$this->resetAfterTest(true);
$return = new \stdClass();
// Create the course and fetch its context.
$return->course = self::getDataGenerator()->create_course();
$return->user1 = array(
'username' => 'usernametest1',
'idnumber' => 'idnumbertest1',
'firstname' => 'First Name User Test 1',
'lastname' => 'Last Name User Test 1',
'email' => '[email protected]',
'address' => '2 Test Street Perth 6000 WA',
'phone1' => '01010101010',
'phone2' => '02020203',
'department' => 'Department of user 1',
'institution' => 'Institution of user 1',
'description' => 'This is a description for user 1',
'descriptionformat' => FORMAT_MOODLE,
'city' => 'Perth',
'country' => 'AU'
);
$return->user1 = self::getDataGenerator()->create_user($return->user1);
if (!empty($CFG->usetags)) {
require_once($CFG->dirroot . '/user/editlib.php');
$return->user1->interests = array('Cinema', 'Tennis', 'Dance', 'Guitar', 'Cooking');
useredit_update_interests($return->user1, $return->user1->interests);
}
$return->user2 = self::getDataGenerator()->create_user();
$context = \context_course::instance($return->course->id);
$return->roleid = $this->assignUserCapability($capability, $context->id);
// Enrol the users in the course.
$this->getDataGenerator()->enrol_user($return->user1->id, $return->course->id, $return->roleid, 'manual');
$this->getDataGenerator()->enrol_user($return->user2->id, $return->course->id, $return->roleid, 'manual');
$this->getDataGenerator()->enrol_user($USER->id, $return->course->id, $return->roleid, 'manual');
$group1 = $this->getDataGenerator()->create_group(['courseid' => $return->course->id, 'name' => 'G1']);
$group2 = $this->getDataGenerator()->create_group(['courseid' => $return->course->id, 'name' => 'G2']);
groups_add_member($group1->id, $return->user1->id);
groups_add_member($group2->id, $return->user2->id);
return $return;
}
/**
* Test get_course_user_profiles
*/
public function test_get_course_user_profiles() {
global $USER, $CFG;
$this->resetAfterTest(true);
$data = $this->get_course_user_profiles_setup('moodle/user:viewdetails');
// Call the external function.
$enrolledusers = core_user_external::get_course_user_profiles(array(
array('userid' => $USER->id, 'courseid' => $data->course->id)));
// We need to execute the return values cleaning process to simulate the web service server.
$enrolledusers = external_api::clean_returnvalue(core_user_external::get_course_user_profiles_returns(), $enrolledusers);
// Check we retrieve the good total number of enrolled users + no error on capability.
$this->assertEquals(1, count($enrolledusers));
}
public function test_get_user_course_profile_as_admin() {
global $USER, $CFG;
global $USER, $CFG;
$this->resetAfterTest(true);
$data = $this->get_course_user_profiles_setup('moodle/user:viewdetails');
// Do the same call as admin to receive all possible fields.
$this->setAdminUser();
$USER->email = "[email protected]";
// Call the external function.
$enrolledusers = core_user_external::get_course_user_profiles(array(
array('userid' => $data->user1->id, 'courseid' => $data->course->id)));
// We need to execute the return values cleaning process to simulate the web service server.
$enrolledusers = external_api::clean_returnvalue(core_user_external::get_course_user_profiles_returns(), $enrolledusers);
// Check we get the requested user and that is in a group.
$this->assertCount(1, $enrolledusers);
$this->assertCount(1, $enrolledusers[0]['groups']);
foreach($enrolledusers as $enrolleduser) {
if ($enrolleduser['username'] == $data->user1->username) {
$this->assertEquals($data->user1->idnumber, $enrolleduser['idnumber']);
$this->assertEquals($data->user1->firstname, $enrolleduser['firstname']);
$this->assertEquals($data->user1->lastname, $enrolleduser['lastname']);
$this->assertEquals($data->user1->email, $enrolleduser['email']);
$this->assertEquals($data->user1->address, $enrolleduser['address']);
$this->assertEquals($data->user1->phone1, $enrolleduser['phone1']);
$this->assertEquals($data->user1->phone2, $enrolleduser['phone2']);
$this->assertEquals($data->user1->department, $enrolleduser['department']);
$this->assertEquals($data->user1->institution, $enrolleduser['institution']);
$this->assertEquals($data->user1->description, $enrolleduser['description']);
$this->assertEquals(FORMAT_HTML, $enrolleduser['descriptionformat']);
$this->assertEquals($data->user1->city, $enrolleduser['city']);
$this->assertEquals($data->user1->country, $enrolleduser['country']);
if (!empty($CFG->usetags)) {
$this->assertEquals(implode(', ', $data->user1->interests), $enrolleduser['interests']);
}
}
}
}
/**
* Test create_users
*/
public function test_create_users() {
global $DB;
$this->resetAfterTest(true);
$user1 = array(
'username' => 'usernametest1',
'password' => 'Moodle2012!',
'idnumber' => 'idnumbertest1',
'firstname' => 'First Name User Test 1',
'lastname' => 'Last Name User Test 1',
'middlename' => 'Middle Name User Test 1',
'lastnamephonetic' => '最後のお名前のテスト一号',
'firstnamephonetic' => 'お名前のテスト一号',
'alternatename' => 'Alternate Name User Test 1',
'email' => '[email protected]',
'description' => 'This is a description for user 1',
'city' => 'Perth',
'country' => 'AU',
'preferences' => [[
'type' => 'htmleditor',
'value' => 'atto'
], [
'type' => 'invalidpreference',
'value' => 'abcd'
]
],
'department' => 'College of Science',
'institution' => 'National Institute of Physics',
'phone1' => '01 2345 6789',
'maildisplay' => 1,
'interests' => 'badminton, basketball, cooking, '
);
// User with an authentication method done externally.
$user2 = array(
'username' => 'usernametest2',
'firstname' => 'First Name User Test 2',
'lastname' => 'Last Name User Test 2',
'email' => '[email protected]',
'auth' => 'oauth2'
);
$context = \context_system::instance();
$roleid = $this->assignUserCapability('moodle/user:create', $context->id);
$this->assignUserCapability('moodle/user:editprofile', $context->id, $roleid);
// Call the external function.
$createdusers = core_user_external::create_users(array($user1, $user2));
// We need to execute the return values cleaning process to simulate the web service server.
$createdusers = external_api::clean_returnvalue(core_user_external::create_users_returns(), $createdusers);
// Check we retrieve the good total number of created users + no error on capability.
$this->assertCount(2, $createdusers);
foreach($createdusers as $createduser) {
$dbuser = $DB->get_record('user', array('id' => $createduser['id']));
if ($createduser['username'] === $user1['username']) {
$usertotest = $user1;
$this->assertEquals('atto', get_user_preferences('htmleditor', null, $dbuser));
$this->assertEquals(null, get_user_preferences('invalidpreference', null, $dbuser));
// Confirm user interests have been saved.
$interests = \core_tag_tag::get_item_tags_array('core', 'user', $createduser['id'],
\core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
// There should be 3 user interests.
$this->assertCount(3, $interests);
} else if ($createduser['username'] === $user2['username']) {
$usertotest = $user2;
}
foreach ($dbuser as $property => $value) {
if ($property === 'password') {
if ($usertotest === $user2) {
// External auth mechanisms don't store password in the user table.
$this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $value);
} else {
// Skip hashed passwords.
continue;
}
}
// Confirm that the values match.
if (isset($usertotest[$property])) {
$this->assertEquals($usertotest[$property], $value);
}
}
}
// Call without required capability
$this->unassignUserCapability('moodle/user:create', $context->id, $roleid);
$this->expectException('required_capability_exception');
core_user_external::create_users(array($user1));
}
/**
* Test create_users with password and createpassword parameter not set.
*/
public function test_create_users_empty_password() {
$this->resetAfterTest();
$this->setAdminUser();
$user = [
'username' => 'usernametest1',
'firstname' => 'First Name User Test 1',
'lastname' => 'Last Name User Test 1',
'email' => '[email protected]',
];
// This should throw an exception because either password or createpassword param must be passed for auth_manual.
$this->expectException(\invalid_parameter_exception::class);
core_user_external::create_users([$user]);
}
/**
* Data provider for \core_user_externallib_testcase::test_create_users_with_same_emails().
*/
public function create_users_provider_with_same_emails() {
return [
'Same emails allowed, same case' => [
1, false
],
'Same emails allowed, different case' => [
1, true
],
'Same emails disallowed, same case' => [
0, false
],
'Same emails disallowed, different case' => [
0, true
],
];
}
/**
* Test for \core_user_external::create_users() when user using the same email addresses are being created.
*
* @dataProvider create_users_provider_with_same_emails
* @param int $sameemailallowed The value to set for $CFG->allowaccountssameemail.
* @param boolean $differentcase Whether to user a different case for the other user.
*/
public function test_create_users_with_same_emails($sameemailallowed, $differentcase) {
global $DB;
$this->resetAfterTest();
$this->setAdminUser();
// Allow multiple users with the same email address.
set_config('allowaccountssameemail', $sameemailallowed);
$users = [
[
'username' => 's1',
'firstname' => 'Johnny',
'lastname' => 'Bravo',
'email' => '[email protected]',
'password' => 'Passw0rd!'
],
[
'username' => 's2',
'firstname' => 'John',
'lastname' => 'Doe',
'email' => $differentcase ? '[email protected]' : '[email protected]',
'password' => 'Passw0rd!'
],
];
if (!$sameemailallowed) {
// This should throw an exception when $CFG->allowaccountssameemail is empty.
$this->expectException(\invalid_parameter_exception::class);
}
// Create our users.
core_user_external::create_users($users);
// Confirm that the users have been created.
list($insql, $params) = $DB->get_in_or_equal(['s1', 's2']);
$this->assertEquals(2, $DB->count_records_select('user', 'username ' . $insql, $params));
}
/**
* Test create_users with invalid parameters
*
* @dataProvider data_create_users_invalid_parameter
* @param array $data User data to attempt to register.
* @param string $expectmessage Expected exception message.
*/
public function test_create_users_invalid_parameter(array $data, $expectmessage) {
global $USER, $CFG, $DB;
$this->resetAfterTest(true);
$this->assignUserCapability('moodle/user:create', SYSCONTEXTID);
$this->expectException('invalid_parameter_exception');
$this->expectExceptionMessage($expectmessage);
core_user_external::create_users(array($data));
}
/**
* Data provider for {@see self::test_create_users_invalid_parameter()}.
*
* @return array
*/
public function data_create_users_invalid_parameter() {
return [
'blank_username' => [
'data' => [
'username' => '',
'firstname' => 'Foo',
'lastname' => 'Bar',
'email' => '[email protected]',
'createpassword' => 1,
],
'expectmessage' => 'The field username cannot be blank',
],
'blank_firtname' => [
'data' => [
'username' => 'foobar',
'firstname' => "\t \n",
'lastname' => 'Bar',
'email' => '[email protected]',
'createpassword' => 1,
],
'expectmessage' => 'The field firstname cannot be blank',
],
'blank_lastname' => [
'data' => [
'username' => 'foobar',
'firstname' => '0',
'lastname' => ' ',
'email' => '[email protected]',
'createpassword' => 1,
],
'expectmessage' => 'The field lastname cannot be blank',
],
'invalid_email' => [
'data' => [
'username' => 'foobar',
'firstname' => 'Foo',
'lastname' => 'Bar',
'email' => '@foobar',
'createpassword' => 1,
],
'expectmessage' => 'Email address is invalid',
],
'missing_password' => [
'data' => [
'username' => 'foobar',
'firstname' => 'Foo',
'lastname' => 'Bar',
'email' => '[email protected]',
],
'expectmessage' => 'Invalid password: you must provide a password, or set createpassword',
],
];
}
/**
* Test delete_users
*/
public function test_delete_users() {
global $USER, $CFG, $DB;
$this->resetAfterTest(true);
$user1 = self::getDataGenerator()->create_user();
$user2 = self::getDataGenerator()->create_user();
// Check the users were correctly created.
$this->assertEquals(2, $DB->count_records_select('user', 'deleted = 0 AND (id = :userid1 OR id = :userid2)',
array('userid1' => $user1->id, 'userid2' => $user2->id)));
$context = \context_system::instance();
$roleid = $this->assignUserCapability('moodle/user:delete', $context->id);
// Call the external function.
core_user_external::delete_users(array($user1->id, $user2->id));
// Check we retrieve no users + no error on capability.
$this->assertEquals(0, $DB->count_records_select('user', 'deleted = 0 AND (id = :userid1 OR id = :userid2)',
array('userid1' => $user1->id, 'userid2' => $user2->id)));
// Call without required capability.
$this->unassignUserCapability('moodle/user:delete', $context->id, $roleid);
$this->expectException('required_capability_exception');
core_user_external::delete_users(array($user1->id, $user2->id));
}
/**
* Test update_users
*/
public function test_update_users() {
global $USER, $CFG, $DB;
$this->resetAfterTest(true);
$this->preventResetByRollback();
$wsuser = self::getDataGenerator()->create_user();
self::setUser($wsuser);
$context = \context_user::instance($USER->id);
$contextid = $context->id;
$filename = "reddot.png";
$filecontent = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38"
. "GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
// Call the files api to create a file.
$draftfile = core_files_external::upload($contextid, 'user', 'draft', 0, '/',
$filename, $filecontent, null, null);
$draftfile = external_api::clean_returnvalue(core_files_external::upload_returns(), $draftfile);
$draftid = $draftfile['itemid'];
$user1 = self::getDataGenerator()->create_user();
$user1 = array(
'id' => $user1->id,
'username' => 'usernametest1',
'password' => 'Moodle2012!',
'idnumber' => 'idnumbertest1',
'firstname' => 'First Name User Test 1',
'lastname' => 'Last Name User Test 1',
'middlename' => 'Middle Name User Test 1',
'lastnamephonetic' => '最後のお名前のテスト一号',
'firstnamephonetic' => 'お名前のテスト一号',
'alternatename' => 'Alternate Name User Test 1',
'email' => '[email protected]',
'description' => 'This is a description for user 1',
'city' => 'Perth',
'userpicture' => $draftid,
'country' => 'AU',
'preferences' => [[
'type' => 'htmleditor',
'value' => 'atto'
], [
'type' => 'invialidpreference',
'value' => 'abcd'
]
],
'department' => 'College of Science',
'institution' => 'National Institute of Physics',
'phone1' => '01 2345 6789',
'maildisplay' => 1,
'interests' => 'badminton, basketball, cooking, '
);
$context = \context_system::instance();
$roleid = $this->assignUserCapability('moodle/user:update', $context->id);
$this->assignUserCapability('moodle/user:editprofile', $context->id, $roleid);
// Check we can't update deleted users, guest users, site admin.
$user2 = $user3 = $user4 = $user1;
$user2['id'] = $CFG->siteguest;
$siteadmins = explode(',', $CFG->siteadmins);
$user3['id'] = array_shift($siteadmins);
$userdeleted = self::getDataGenerator()->create_user();
$user4['id'] = $userdeleted->id;
user_delete_user($userdeleted);
$user5 = self::getDataGenerator()->create_user();
$user5 = array('id' => $user5->id, 'email' => $user5->email);
// Call the external function.
$returnvalue = core_user_external::update_users(array($user1, $user2, $user3, $user4));
$returnvalue = external_api::clean_returnvalue(core_user_external::update_users_returns(), $returnvalue);
// Check warnings.
$this->assertEquals($user2['id'], $returnvalue['warnings'][0]['itemid']); // Guest user.
$this->assertEquals('usernotupdatedguest', $returnvalue['warnings'][0]['warningcode']);
$this->assertEquals($user3['id'], $returnvalue['warnings'][1]['itemid']); // Admin user.
$this->assertEquals('usernotupdatedadmin', $returnvalue['warnings'][1]['warningcode']);
$this->assertEquals($user4['id'], $returnvalue['warnings'][2]['itemid']); // Deleted user.
$this->assertEquals('usernotupdateddeleted', $returnvalue['warnings'][2]['warningcode']);
$dbuser2 = $DB->get_record('user', array('id' => $user2['id']));
$this->assertNotEquals($dbuser2->username, $user2['username']);
$dbuser3 = $DB->get_record('user', array('id' => $user3['id']));
$this->assertNotEquals($dbuser3->username, $user3['username']);
$dbuser4 = $DB->get_record('user', array('id' => $user4['id']));
$this->assertNotEquals($dbuser4->username, $user4['username']);
$dbuser = $DB->get_record('user', array('id' => $user1['id']));
$this->assertEquals($dbuser->username, $user1['username']);
$this->assertEquals($dbuser->idnumber, $user1['idnumber']);
$this->assertEquals($dbuser->firstname, $user1['firstname']);
$this->assertEquals($dbuser->lastname, $user1['lastname']);
$this->assertEquals($dbuser->email, $user1['email']);
$this->assertEquals($dbuser->description, $user1['description']);
$this->assertEquals($dbuser->city, $user1['city']);
$this->assertEquals($dbuser->country, $user1['country']);
$this->assertNotEquals(0, $dbuser->picture, 'Picture must be set to the new icon itemid for this user');
$this->assertEquals($dbuser->department, $user1['department']);
$this->assertEquals($dbuser->institution, $user1['institution']);
$this->assertEquals($dbuser->phone1, $user1['phone1']);
$this->assertEquals($dbuser->maildisplay, $user1['maildisplay']);
$this->assertEquals('atto', get_user_preferences('htmleditor', null, $dbuser));
$this->assertEquals(null, get_user_preferences('invalidpreference', null, $dbuser));
// Confirm user interests have been saved.
$interests = \core_tag_tag::get_item_tags_array('core', 'user', $user1['id'], \core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
// There should be 3 user interests.
$this->assertCount(3, $interests);
// Confirm no picture change when parameter is not supplied.
unset($user1['userpicture']);
core_user_external::update_users(array($user1));
$dbusernopic = $DB->get_record('user', array('id' => $user1['id']));
$this->assertEquals($dbuser->picture, $dbusernopic->picture, 'Picture not change without the parameter.');
// Confirm delete of picture deletes the picture from the user record.
$user1['userpicture'] = 0;
core_user_external::update_users(array($user1));
$dbuserdelpic = $DB->get_record('user', array('id' => $user1['id']));
$this->assertEquals(0, $dbuserdelpic->picture, 'Picture must be deleted when sent as 0.');
// Updating user with an invalid email.
$user5['email'] = 'bogus';
$returnvalue = core_user_external::update_users(array($user5));
$returnvalue = external_api::clean_returnvalue(core_user_external::update_users_returns(), $returnvalue);
$this->assertEquals('useremailinvalid', $returnvalue['warnings'][0]['warningcode']);
$this->assertStringContainsString('Invalid email address',
$returnvalue['warnings'][0]['message']);
// Updating user with a duplicate email.
$user5['email'] = $user1['email'];
$returnvalue = core_user_external::update_users(array($user1, $user5));
$returnvalue = external_api::clean_returnvalue(core_user_external::update_users_returns(), $returnvalue);
$this->assertEquals('useremailduplicate', $returnvalue['warnings'][0]['warningcode']);
$this->assertStringContainsString('Duplicate email address',
$returnvalue['warnings'][0]['message']);
// Updating a user that does not exist.
$user5['id'] = -1;
$returnvalue = core_user_external::update_users(array($user5));
$returnvalue = external_api::clean_returnvalue(core_user_external::update_users_returns(), $returnvalue);
$this->assertEquals('invaliduserid', $returnvalue['warnings'][0]['warningcode']);
$this->assertStringContainsString('Invalid user ID',
$returnvalue['warnings'][0]['message']);
// Updating a remote user.
$user1['mnethostid'] = 5;
user_update_user($user1); // Update user not using webservice.
unset($user1['mnethostid']); // The mnet host ID field is not in the allowed field list for the webservice.
$returnvalue = core_user_external::update_users(array($user1));
$returnvalue = external_api::clean_returnvalue(core_user_external::update_users_returns(), $returnvalue);
$this->assertEquals('usernotupdatedremote', $returnvalue['warnings'][0]['warningcode']);
$this->assertStringContainsString('User is a remote user',
$returnvalue['warnings'][0]['message']);
// Call without required capability.
$this->unassignUserCapability('moodle/user:update', $context->id, $roleid);
$this->expectException('required_capability_exception');
core_user_external::update_users(array($user1));
}
/**
* Data provider for testing \core_user_external::update_users() for users with same emails
*
* @return array
*/
public function users_with_same_emails() {
return [
'Same emails not allowed: Update name using exactly the same email' => [
0, 'John', '[email protected]', 'Johnny', '[email protected]', false, true
],
'Same emails not allowed: Update using someone else\'s email' => [
0, 'John', '[email protected]', 'Johnny', '[email protected]', true, false
],
'Same emails allowed: Update using someone else\'s email' => [
1, 'John', '[email protected]', 'Johnny', '[email protected]', true, true
],
'Same emails not allowed: Update using same email but with different case' => [
0, 'John', '[email protected]', 'Johnny', '[email protected]', false, true
],
'Same emails not allowed: Update using another user\'s email similar to user but with different case' => [
0, 'John', '[email protected]', 'Johnny', '[email protected]', true, false
],
'Same emails allowed: Update using another user\'s email similar to user but with different case' => [
1, 'John', '[email protected]', 'Johnny', '[email protected]', true, true
],
];
}
/**
* Test update_users using similar emails with varying cases.
*
* @dataProvider users_with_same_emails
* @param boolean $allowsameemail The value to set for $CFG->allowaccountssameemail.
* @param string $currentname The user's current name.
* @param string $currentemail The user's current email.
* @param string $newname The user's new name.
* @param string $newemail The user's new email.
* @param boolean $withanotheruser Whether to create another user that has the same email as the target user's new email.
* @param boolean $successexpected Whether we expect that the target user's email/name will be updated.
*/
public function test_update_users_emails_with_different_cases($allowsameemail, $currentname, $currentemail,
$newname, $newemail, $withanotheruser, $successexpected) {
global $DB;
$this->resetAfterTest();
$this->setAdminUser();
// Set the value for $CFG->allowaccountssameemail.
set_config('allowaccountssameemail', $allowsameemail);
$generator = self::getDataGenerator();
// Create the user that we wish to update.
$usertoupdate = $generator->create_user(['email' => $currentemail, 'firstname' => $currentname]);
if ($withanotheruser) {
// Create another user that has the same email as the new email that we'd like to update for our target user.
$generator->create_user(['email' => $newemail]);
}
// Build the user update parameters.
$updateparams = [
'id' => $usertoupdate->id,
'email' => $newemail,
'firstname' => $newname
];
// Let's try to update the user's information.
core_user_external::update_users([$updateparams]);
// Fetch the updated user record.
$userrecord = $DB->get_record('user', ['id' => $usertoupdate->id], 'id, email, firstname');
// If we expect the update to succeed, then the email/name would have been changed.
if ($successexpected) {
$expectedemail = $newemail;
$expectedname = $newname;
} else {
$expectedemail = $currentemail;
$expectedname = $currentname;
}
// Confirm that our expectations are met.
$this->assertEquals($expectedemail, $userrecord->email);
$this->assertEquals($expectedname, $userrecord->firstname);