99b1713307fde4552638fe686665eeed11adb7fa
[moodle.git] / user / tests / externallib_test.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  * User external PHPunit tests
19  *
20  * @package    core_user
21  * @category   external
22  * @copyright  2012 Jerome Mouneyrac
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  * @since Moodle 2.4
25  */
27 defined('MOODLE_INTERNAL') || die();
29 global $CFG;
31 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
32 require_once($CFG->dirroot . '/user/externallib.php');
33 require_once($CFG->dirroot . '/files/externallib.php');
35 class core_user_externallib_testcase extends externallib_advanced_testcase {
37     /**
38      * Test get_users
39      */
40     public function test_get_users() {
41         global $USER, $CFG;
43         $this->resetAfterTest(true);
45         $course = self::getDataGenerator()->create_course();
47         $user1 = array(
48             'username' => 'usernametest1',
49             'idnumber' => 'idnumbertest1',
50             'firstname' => 'First Name User Test 1',
51             'lastname' => 'Last Name User Test 1',
52             'email' => 'usertest1@example.com',
53             'address' => '2 Test Street Perth 6000 WA',
54             'phone1' => '01010101010',
55             'phone2' => '02020203',
56             'icq' => 'testuser1',
57             'skype' => 'testuser1',
58             'yahoo' => 'testuser1',
59             'aim' => 'testuser1',
60             'msn' => 'testuser1',
61             'department' => 'Department of user 1',
62             'institution' => 'Institution of user 1',
63             'description' => 'This is a description for user 1',
64             'descriptionformat' => FORMAT_MOODLE,
65             'city' => 'Perth',
66             'url' => 'http://moodle.org',
67             'country' => 'au'
68             );
70         $user1 = self::getDataGenerator()->create_user($user1);
71         set_config('usetags', 1);
72         require_once($CFG->dirroot . '/user/editlib.php');
73         require_once($CFG->dirroot . '/tag/lib.php');
74         $user1->interests = array('Cinema', 'Tennis', 'Dance', 'Guitar', 'Cooking');
75         useredit_update_interests($user1, $user1->interests);
77         $user2 = self::getDataGenerator()->create_user(
78                 array('username' => 'usernametest2', 'idnumber' => 'idnumbertest2'));
80         $generatedusers = array();
81         $generatedusers[$user1->id] = $user1;
82         $generatedusers[$user2->id] = $user2;
84         $context = context_course::instance($course->id);
85         $roleid = $this->assignUserCapability('moodle/user:viewdetails', $context->id);
87         // Enrol the users in the course.
88         $this->getDataGenerator()->enrol_user($user1->id, $course->id, $roleid);
89         $this->getDataGenerator()->enrol_user($user2->id, $course->id, $roleid);
90         $this->getDataGenerator()->enrol_user($USER->id, $course->id, $roleid);
92         // call as admin and receive all possible fields.
93         $this->setAdminUser();
95         $searchparams = array(
96             array('key' => 'invalidkey', 'value' => 'invalidkey'),
97             array('key' => 'email', 'value' => $user1->email),
98             array('key' => 'firstname', 'value' => $user1->firstname));
100         // Call the external function.
101         $result = core_user_external::get_users($searchparams);
103         // We need to execute the return values cleaning process to simulate the web service server
104         $result = external_api::clean_returnvalue(core_user_external::get_users_returns(), $result);
106         // Check we retrieve the good total number of enrolled users + no error on capability.
107         $expectedreturnedusers = 1;
108         $returnedusers = $result['users'];
109         $this->assertEquals($expectedreturnedusers, count($returnedusers));
111         foreach($returnedusers as $returneduser) {
112             $generateduser = ($returneduser['id'] == $USER->id) ?
113                                 $USER : $generatedusers[$returneduser['id']];
114             $this->assertEquals($generateduser->username, $returneduser['username']);
115             if (!empty($generateduser->idnumber)) {
116                 $this->assertEquals($generateduser->idnumber, $returneduser['idnumber']);
117             }
118             $this->assertEquals($generateduser->firstname, $returneduser['firstname']);
119             $this->assertEquals($generateduser->lastname, $returneduser['lastname']);
120             if ($generateduser->email != $USER->email) { // Don't check the tmp modified $USER email.
121                 $this->assertEquals($generateduser->email, $returneduser['email']);
122             }
123             if (!empty($generateduser->address)) {
124                 $this->assertEquals($generateduser->address, $returneduser['address']);
125             }
126             if (!empty($generateduser->phone1)) {
127                 $this->assertEquals($generateduser->phone1, $returneduser['phone1']);
128             }
129             if (!empty($generateduser->phone2)) {
130                 $this->assertEquals($generateduser->phone2, $returneduser['phone2']);
131             }
132             if (!empty($generateduser->icq)) {
133                 $this->assertEquals($generateduser->icq, $returneduser['icq']);
134             }
135             if (!empty($generateduser->skype)) {
136                 $this->assertEquals($generateduser->skype, $returneduser['skype']);
137             }
138             if (!empty($generateduser->yahoo)) {
139                 $this->assertEquals($generateduser->yahoo, $returneduser['yahoo']);
140             }
141             if (!empty($generateduser->aim)) {
142                 $this->assertEquals($generateduser->aim, $returneduser['aim']);
143             }
144             if (!empty($generateduser->msn)) {
145                 $this->assertEquals($generateduser->msn, $returneduser['msn']);
146             }
147             if (!empty($generateduser->department)) {
148                 $this->assertEquals($generateduser->department, $returneduser['department']);
149             }
150             if (!empty($generateduser->institution)) {
151                 $this->assertEquals($generateduser->institution, $returneduser['institution']);
152             }
153             if (!empty($generateduser->description)) {
154                 $this->assertEquals($generateduser->description, $returneduser['description']);
155             }
156             if (!empty($generateduser->descriptionformat)) {
157                 $this->assertEquals(FORMAT_HTML, $returneduser['descriptionformat']);
158             }
159             if (!empty($generateduser->city)) {
160                 $this->assertEquals($generateduser->city, $returneduser['city']);
161             }
162             if (!empty($generateduser->country)) {
163                 $this->assertEquals($generateduser->country, $returneduser['country']);
164             }
165             if (!empty($generateduser->url)) {
166                 $this->assertEquals($generateduser->url, $returneduser['url']);
167             }
168             if (!empty($CFG->usetags) and !empty($generateduser->interests)) {
169                 $this->assertEquals(implode(', ', $generateduser->interests), $returneduser['interests']);
170             }
171         }
173         // Test the invalid key warning.
174         $warnings = $result['warnings'];
175         $this->assertEquals(count($warnings), 1);
176         $warning = array_pop($warnings);
177         $this->assertEquals($warning['item'], 'invalidkey');
178         $this->assertEquals($warning['warningcode'], 'invalidfieldparameter');
180         // Test sending twice the same search field.
181         try {
182             $searchparams = array(
183             array('key' => 'firstname', 'value' => 'Canard'),
184             array('key' => 'email', 'value' => $user1->email),
185             array('key' => 'firstname', 'value' => $user1->firstname));
187             // Call the external function.
188             $result = core_user_external::get_users($searchparams);
189             $this->fail('Expecting \'keyalreadyset\' moodle_exception to be thrown.');
190         } catch (moodle_exception $e) {
191             $this->assertEquals('keyalreadyset', $e->errorcode);
192         } catch (Exception $e) {
193             $this->fail('Expecting \'keyalreadyset\' moodle_exception to be thrown.');
194         }
195     }
197     /**
198      * Test get_users_by_field
199      */
200     public function test_get_users_by_field() {
201         global $USER, $CFG;
203         $this->resetAfterTest(true);
205         $course = self::getDataGenerator()->create_course();
206         $user1 = array(
207             'username' => 'usernametest1',
208             'idnumber' => 'idnumbertest1',
209             'firstname' => 'First Name User Test 1',
210             'lastname' => 'Last Name User Test 1',
211             'email' => 'usertest1@example.com',
212             'address' => '2 Test Street Perth 6000 WA',
213             'phone1' => '01010101010',
214             'phone2' => '02020203',
215             'icq' => 'testuser1',
216             'skype' => 'testuser1',
217             'yahoo' => 'testuser1',
218             'aim' => 'testuser1',
219             'msn' => 'testuser1',
220             'department' => 'Department of user 1',
221             'institution' => 'Institution of user 1',
222             'description' => 'This is a description for user 1',
223             'descriptionformat' => FORMAT_MOODLE,
224             'city' => 'Perth',
225             'url' => 'http://moodle.org',
226             'country' => 'au'
227             );
228         $user1 = self::getDataGenerator()->create_user($user1);
229         if (!empty($CFG->usetags)) {
230             require_once($CFG->dirroot . '/user/editlib.php');
231             require_once($CFG->dirroot . '/tag/lib.php');
232             $user1->interests = array('Cinema', 'Tennis', 'Dance', 'Guitar', 'Cooking');
233             useredit_update_interests($user1, $user1->interests);
234         }
235         $user2 = self::getDataGenerator()->create_user(
236                 array('username' => 'usernametest2', 'idnumber' => 'idnumbertest2'));
238         $generatedusers = array();
239         $generatedusers[$user1->id] = $user1;
240         $generatedusers[$user2->id] = $user2;
242         $context = context_course::instance($course->id);
243         $roleid = $this->assignUserCapability('moodle/user:viewdetails', $context->id);
245         // Enrol the users in the course.
246         $this->getDataGenerator()->enrol_user($user1->id, $course->id, $roleid, 'manual');
247         $this->getDataGenerator()->enrol_user($user2->id, $course->id, $roleid, 'manual');
248         $this->getDataGenerator()->enrol_user($USER->id, $course->id, $roleid, 'manual');
250         // call as admin and receive all possible fields.
251         $this->setAdminUser();
253         $fieldstosearch = array('id', 'idnumber', 'username', 'email');
255         foreach ($fieldstosearch as $fieldtosearch) {
257             // Call the external function.
258             $returnedusers = core_user_external::get_users_by_field($fieldtosearch,
259                         array($USER->{$fieldtosearch}, $user1->{$fieldtosearch}, $user2->{$fieldtosearch}));
260             $returnedusers = external_api::clean_returnvalue(core_user_external::get_users_by_field_returns(), $returnedusers);
262             // Expected result differ following the searched field
263             // Admin user in the PHPunit framework doesn't have an idnumber.
264             if ($fieldtosearch == 'idnumber') {
265                 $expectedreturnedusers = 2;
266             } else {
267                 $expectedreturnedusers = 3;
268             }
270             // Check we retrieve the good total number of enrolled users + no error on capability.
271             $this->assertEquals($expectedreturnedusers, count($returnedusers));
273             foreach($returnedusers as $returneduser) {
274                 $generateduser = ($returneduser['id'] == $USER->id) ?
275                                     $USER : $generatedusers[$returneduser['id']];
276                 $this->assertEquals($generateduser->username, $returneduser['username']);
277                 if (!empty($generateduser->idnumber)) {
278                     $this->assertEquals($generateduser->idnumber, $returneduser['idnumber']);
279                 }
280                 $this->assertEquals($generateduser->firstname, $returneduser['firstname']);
281                 $this->assertEquals($generateduser->lastname, $returneduser['lastname']);
282                 if ($generateduser->email != $USER->email) { //don't check the tmp modified $USER email
283                     $this->assertEquals($generateduser->email, $returneduser['email']);
284                 }
285                 if (!empty($generateduser->address)) {
286                     $this->assertEquals($generateduser->address, $returneduser['address']);
287                 }
288                 if (!empty($generateduser->phone1)) {
289                     $this->assertEquals($generateduser->phone1, $returneduser['phone1']);
290                 }
291                 if (!empty($generateduser->phone2)) {
292                     $this->assertEquals($generateduser->phone2, $returneduser['phone2']);
293                 }
294                 if (!empty($generateduser->icq)) {
295                     $this->assertEquals($generateduser->icq, $returneduser['icq']);
296                 }
297                 if (!empty($generateduser->skype)) {
298                     $this->assertEquals($generateduser->skype, $returneduser['skype']);
299                 }
300                 if (!empty($generateduser->yahoo)) {
301                     $this->assertEquals($generateduser->yahoo, $returneduser['yahoo']);
302                 }
303                 if (!empty($generateduser->aim)) {
304                     $this->assertEquals($generateduser->aim, $returneduser['aim']);
305                 }
306                 if (!empty($generateduser->msn)) {
307                     $this->assertEquals($generateduser->msn, $returneduser['msn']);
308                 }
309                 if (!empty($generateduser->department)) {
310                     $this->assertEquals($generateduser->department, $returneduser['department']);
311                 }
312                 if (!empty($generateduser->institution)) {
313                     $this->assertEquals($generateduser->institution, $returneduser['institution']);
314                 }
315                 if (!empty($generateduser->description)) {
316                     $this->assertEquals($generateduser->description, $returneduser['description']);
317                 }
318                 if (!empty($generateduser->descriptionformat) and isset($returneduser['descriptionformat'])) {
319                     $this->assertEquals($generateduser->descriptionformat, $returneduser['descriptionformat']);
320                 }
321                 if (!empty($generateduser->city)) {
322                     $this->assertEquals($generateduser->city, $returneduser['city']);
323                 }
324                 if (!empty($generateduser->country)) {
325                     $this->assertEquals($generateduser->country, $returneduser['country']);
326                 }
327                 if (!empty($generateduser->url)) {
328                     $this->assertEquals($generateduser->url, $returneduser['url']);
329                 }
330                 if (!empty($CFG->usetags) and !empty($generateduser->interests)) {
331                     $this->assertEquals(implode(', ', $generateduser->interests), $returneduser['interests']);
332                 }
333             }
334         }
336         // Test that no result are returned for search by username if we are not admin
337         $this->setGuestUser();
339         // Call the external function.
340         $returnedusers = core_user_external::get_users_by_field('username',
341                     array($USER->username, $user1->username, $user2->username));
342         $returnedusers = external_api::clean_returnvalue(core_user_external::get_users_by_field_returns(), $returnedusers);
344         // Only the own $USER username should be returned
345         $this->assertEquals(1, count($returnedusers));
347         // And finally test as one of the enrolled users.
348         $this->setUser($user1);
350         // Call the external function.
351         $returnedusers = core_user_external::get_users_by_field('username',
352             array($USER->username, $user1->username, $user2->username));
353         $returnedusers = external_api::clean_returnvalue(core_user_external::get_users_by_field_returns(), $returnedusers);
355         // Only the own $USER username should be returned still.
356         $this->assertEquals(1, count($returnedusers));
357     }
359     /**
360      * Test get_course_user_profiles
361      */
362     public function test_get_course_user_profiles() {
363         global $USER, $CFG;
365         $this->resetAfterTest(true);
367         $course = self::getDataGenerator()->create_course();
368         $user1 = array(
369             'username' => 'usernametest1',
370             'idnumber' => 'idnumbertest1',
371             'firstname' => 'First Name User Test 1',
372             'lastname' => 'Last Name User Test 1',
373             'email' => 'usertest1@example.com',
374             'address' => '2 Test Street Perth 6000 WA',
375             'phone1' => '01010101010',
376             'phone2' => '02020203',
377             'icq' => 'testuser1',
378             'skype' => 'testuser1',
379             'yahoo' => 'testuser1',
380             'aim' => 'testuser1',
381             'msn' => 'testuser1',
382             'department' => 'Department of user 1',
383             'institution' => 'Institution of user 1',
384             'description' => 'This is a description for user 1',
385             'descriptionformat' => FORMAT_MOODLE,
386             'city' => 'Perth',
387             'url' => 'http://moodle.org',
388             'country' => 'au'
389             );
390         $user1 = self::getDataGenerator()->create_user($user1);
391         if (!empty($CFG->usetags)) {
392             require_once($CFG->dirroot . '/user/editlib.php');
393             require_once($CFG->dirroot . '/tag/lib.php');
394             $user1->interests = array('Cinema', 'Tennis', 'Dance', 'Guitar', 'Cooking');
395             useredit_update_interests($user1, $user1->interests);
396         }
397         $user2 = self::getDataGenerator()->create_user();
399         $context = context_course::instance($course->id);
400         $roleid = $this->assignUserCapability('moodle/user:viewdetails', $context->id);
402         // Enrol the users in the course.
403         $this->getDataGenerator()->enrol_user($user1->id, $course->id, $roleid, 'manual');
404         $this->getDataGenerator()->enrol_user($user2->id, $course->id, $roleid, 'manual');
405         $this->getDataGenerator()->enrol_user($USER->id, $course->id, $roleid, 'manual');
407         // Call the external function.
408         $enrolledusers = core_user_external::get_course_user_profiles(array(
409                     array('userid' => $USER->id, 'courseid' => $course->id),
410                     array('userid' => $user1->id, 'courseid' => $course->id),
411                     array('userid' => $user2->id, 'courseid' => $course->id)));
413         // We need to execute the return values cleaning process to simulate the web service server.
414         $enrolledusers = external_api::clean_returnvalue(core_user_external::get_course_user_profiles_returns(), $enrolledusers);
416         // Check we retrieve the good total number of enrolled users + no error on capability.
417         $this->assertEquals(3, count($enrolledusers));
419         // Do the same call as admin to receive all possible fields.
420         $this->setAdminUser();
421         $USER->email = "admin@example.com";
423         // Call the external function.
424         $enrolledusers = core_user_external::get_course_user_profiles(array(
425                     array('userid' => $USER->id, 'courseid' => $course->id),
426                     array('userid' => $user1->id, 'courseid' => $course->id),
427                     array('userid' => $user2->id, 'courseid' => $course->id)));
429         // We need to execute the return values cleaning process to simulate the web service server.
430         $enrolledusers = external_api::clean_returnvalue(core_user_external::get_course_user_profiles_returns(), $enrolledusers);
432         foreach($enrolledusers as $enrolleduser) {
433             if ($enrolleduser['username'] == $user1->username) {
434                 $this->assertEquals($user1->idnumber, $enrolleduser['idnumber']);
435                 $this->assertEquals($user1->firstname, $enrolleduser['firstname']);
436                 $this->assertEquals($user1->lastname, $enrolleduser['lastname']);
437                 $this->assertEquals($user1->email, $enrolleduser['email']);
438                 $this->assertEquals($user1->address, $enrolleduser['address']);
439                 $this->assertEquals($user1->phone1, $enrolleduser['phone1']);
440                 $this->assertEquals($user1->phone2, $enrolleduser['phone2']);
441                 $this->assertEquals($user1->icq, $enrolleduser['icq']);
442                 $this->assertEquals($user1->skype, $enrolleduser['skype']);
443                 $this->assertEquals($user1->yahoo, $enrolleduser['yahoo']);
444                 $this->assertEquals($user1->aim, $enrolleduser['aim']);
445                 $this->assertEquals($user1->msn, $enrolleduser['msn']);
446                 $this->assertEquals($user1->department, $enrolleduser['department']);
447                 $this->assertEquals($user1->institution, $enrolleduser['institution']);
448                 $this->assertEquals($user1->description, $enrolleduser['description']);
449                 $this->assertEquals(FORMAT_HTML, $enrolleduser['descriptionformat']);
450                 $this->assertEquals($user1->city, $enrolleduser['city']);
451                 $this->assertEquals($user1->country, $enrolleduser['country']);
452                 $this->assertEquals($user1->url, $enrolleduser['url']);
453                 if (!empty($CFG->usetags)) {
454                     $this->assertEquals(implode(', ', $user1->interests), $enrolleduser['interests']);
455                 }
456             }
457         }
458     }
460     /**
461      * Test create_users
462      */
463     public function test_create_users() {
464          global $USER, $CFG, $DB;
466         $this->resetAfterTest(true);
468         $user1 = array(
469             'username' => 'usernametest1',
470             'password' => 'Moodle2012!',
471             'idnumber' => 'idnumbertest1',
472             'firstname' => 'First Name User Test 1',
473             'lastname' => 'Last Name User Test 1',
474             'middlename' => 'Middle Name User Test 1',
475             'lastnamephonetic' => '最後のお名前のテスト一号',
476             'firstnamephonetic' => 'お名前のテスト一号',
477             'alternatename' => 'Alternate Name User Test 1',
478             'email' => 'usertest1@example.com',
479             'description' => 'This is a description for user 1',
480             'city' => 'Perth',
481             'country' => 'au'
482             );
484         $context = context_system::instance();
485         $roleid = $this->assignUserCapability('moodle/user:create', $context->id);
487         // Call the external function.
488         $createdusers = core_user_external::create_users(array($user1));
490         // We need to execute the return values cleaning process to simulate the web service server.
491         $createdusers = external_api::clean_returnvalue(core_user_external::create_users_returns(), $createdusers);
493         // Check we retrieve the good total number of created users + no error on capability.
494         $this->assertEquals(1, count($createdusers));
496         foreach($createdusers as $createduser) {
497             $dbuser = $DB->get_record('user', array('id' => $createduser['id']));
498             $this->assertEquals($dbuser->username, $user1['username']);
499             $this->assertEquals($dbuser->idnumber, $user1['idnumber']);
500             $this->assertEquals($dbuser->firstname, $user1['firstname']);
501             $this->assertEquals($dbuser->lastname, $user1['lastname']);
502             $this->assertEquals($dbuser->email, $user1['email']);
503             $this->assertEquals($dbuser->description, $user1['description']);
504             $this->assertEquals($dbuser->city, $user1['city']);
505             $this->assertEquals($dbuser->country, $user1['country']);
506         }
508         // Call without required capability
509         $this->unassignUserCapability('moodle/user:create', $context->id, $roleid);
510         $this->setExpectedException('required_capability_exception');
511         $createdusers = core_user_external::create_users(array($user1));
512     }
514     /**
515      * Test delete_users
516      */
517     public function test_delete_users() {
518         global $USER, $CFG, $DB;
520         $this->resetAfterTest(true);
522         $user1 = self::getDataGenerator()->create_user();
523         $user2 = self::getDataGenerator()->create_user();
525         // Check the users were correctly created.
526         $this->assertEquals(2, $DB->count_records_select('user', 'deleted = 0 AND (id = :userid1 OR id = :userid2)',
527                 array('userid1' => $user1->id, 'userid2' => $user2->id)));
529         $context = context_system::instance();
530         $roleid = $this->assignUserCapability('moodle/user:delete', $context->id);
532         // Call the external function.
533         core_user_external::delete_users(array($user1->id, $user2->id));
535         // Check we retrieve no users + no error on capability.
536         $this->assertEquals(0, $DB->count_records_select('user', 'deleted = 0 AND (id = :userid1 OR id = :userid2)',
537                 array('userid1' => $user1->id, 'userid2' => $user2->id)));
539         // Call without required capability.
540         $this->unassignUserCapability('moodle/user:delete', $context->id, $roleid);
541         $this->setExpectedException('required_capability_exception');
542         core_user_external::delete_users(array($user1->id, $user2->id));
543     }
545     /**
546      * Test get_users_by_id
547      */
548     public function test_get_users_by_id() {
549         global $USER, $CFG;
551         $this->resetAfterTest(true);
553         $user1 = array(
554             'username' => 'usernametest1',
555             'idnumber' => 'idnumbertest1',
556             'firstname' => 'First Name User Test 1',
557             'lastname' => 'Last Name User Test 1',
558             'email' => 'usertest1@example.com',
559             'address' => '2 Test Street Perth 6000 WA',
560             'phone1' => '01010101010',
561             'phone2' => '02020203',
562             'icq' => 'testuser1',
563             'skype' => 'testuser1',
564             'yahoo' => 'testuser1',
565             'aim' => 'testuser1',
566             'msn' => 'testuser1',
567             'department' => 'Department of user 1',
568             'institution' => 'Institution of user 1',
569             'description' => 'This is a description for user 1',
570             'descriptionformat' => FORMAT_MOODLE,
571             'city' => 'Perth',
572             'url' => 'http://moodle.org',
573             'country' => 'au'
574             );
575         $user1 = self::getDataGenerator()->create_user($user1);
576         if (!empty($CFG->usetags)) {
577             require_once($CFG->dirroot . '/user/editlib.php');
578             require_once($CFG->dirroot . '/tag/lib.php');
579             $user1->interests = array('Cinema', 'Tennis', 'Dance', 'Guitar', 'Cooking');
580             useredit_update_interests($user1, $user1->interests);
581         }
582         $user2 = self::getDataGenerator()->create_user();
584         $context = context_system::instance();
585         $roleid = $this->assignUserCapability('moodle/user:viewdetails', $context->id);
587         // Call the external function.
588         $returnedusers = core_user_external::get_users_by_id(array(
589                     $USER->id, $user1->id, $user2->id));
591         // We need to execute the return values cleaning process to simulate the web service server.
592         $returnedusers = external_api::clean_returnvalue(core_user_external::get_users_by_id_returns(), $returnedusers);
594         // Check we retrieve the good total number of enrolled users + no error on capability.
595         $this->assertEquals(3, count($returnedusers));
597         // Do the same call as admin to receive all possible fields.
598         $this->setAdminUser();
599         $USER->email = "admin@example.com";
601         // Call the external function.
602         $returnedusers = core_user_external::get_users_by_id(array(
603                     $USER->id, $user1->id, $user2->id));
605         // We need to execute the return values cleaning process to simulate the web service server.
606         $returnedusers = external_api::clean_returnvalue(core_user_external::get_users_by_id_returns(), $returnedusers);
608         foreach($returnedusers as $enrolleduser) {
609             if ($enrolleduser['username'] == $user1->username) {
610                 $this->assertEquals($user1->idnumber, $enrolleduser['idnumber']);
611                 $this->assertEquals($user1->firstname, $enrolleduser['firstname']);
612                 $this->assertEquals($user1->lastname, $enrolleduser['lastname']);
613                 $this->assertEquals($user1->email, $enrolleduser['email']);
614                 $this->assertEquals($user1->address, $enrolleduser['address']);
615                 $this->assertEquals($user1->phone1, $enrolleduser['phone1']);
616                 $this->assertEquals($user1->phone2, $enrolleduser['phone2']);
617                 $this->assertEquals($user1->icq, $enrolleduser['icq']);
618                 $this->assertEquals($user1->skype, $enrolleduser['skype']);
619                 $this->assertEquals($user1->yahoo, $enrolleduser['yahoo']);
620                 $this->assertEquals($user1->aim, $enrolleduser['aim']);
621                 $this->assertEquals($user1->msn, $enrolleduser['msn']);
622                 $this->assertEquals($user1->department, $enrolleduser['department']);
623                 $this->assertEquals($user1->institution, $enrolleduser['institution']);
624                 $this->assertEquals($user1->description, $enrolleduser['description']);
625                 $this->assertEquals(FORMAT_HTML, $enrolleduser['descriptionformat']);
626                 $this->assertEquals($user1->city, $enrolleduser['city']);
627                 $this->assertEquals($user1->country, $enrolleduser['country']);
628                 $this->assertEquals($user1->url, $enrolleduser['url']);
629                 if (!empty($CFG->usetags)) {
630                     $this->assertEquals(implode(', ', $user1->interests), $enrolleduser['interests']);
631                 }
632             }
633         }
634     }
636     /**
637      * Test update_users
638      */
639     public function test_update_users() {
640         global $USER, $CFG, $DB;
642         $this->resetAfterTest(true);
644         $user1 = self::getDataGenerator()->create_user();
646         $user1 = array(
647             'id' => $user1->id,
648             'username' => 'usernametest1',
649             'password' => 'Moodle2012!',
650             'idnumber' => 'idnumbertest1',
651             'firstname' => 'First Name User Test 1',
652             'lastname' => 'Last Name User Test 1',
653             'middlename' => 'Middle Name User Test 1',
654             'lastnamephonetic' => '最後のお名前のテスト一号',
655             'firstnamephonetic' => 'お名前のテスト一号',
656             'alternatename' => 'Alternate Name User Test 1',
657             'email' => 'usertest1@example.com',
658             'description' => 'This is a description for user 1',
659             'city' => 'Perth',
660             'country' => 'au'
661             );
663         $context = context_system::instance();
664         $roleid = $this->assignUserCapability('moodle/user:update', $context->id);
666         // Call the external function.
667         core_user_external::update_users(array($user1));
669         $dbuser = $DB->get_record('user', array('id' => $user1['id']));
670         $this->assertEquals($dbuser->username, $user1['username']);
671         $this->assertEquals($dbuser->idnumber, $user1['idnumber']);
672         $this->assertEquals($dbuser->firstname, $user1['firstname']);
673         $this->assertEquals($dbuser->lastname, $user1['lastname']);
674         $this->assertEquals($dbuser->email, $user1['email']);
675         $this->assertEquals($dbuser->description, $user1['description']);
676         $this->assertEquals($dbuser->city, $user1['city']);
677         $this->assertEquals($dbuser->country, $user1['country']);
679         // Call without required capability.
680         $this->unassignUserCapability('moodle/user:update', $context->id, $roleid);
681         $this->setExpectedException('required_capability_exception');
682         core_user_external::update_users(array($user1));
683     }
685     /**
686      * Test add_user_private_files
687      */
688     public function test_add_user_private_files() {
689         global $USER, $CFG, $DB;
691         $this->resetAfterTest(true);
693         $context = context_system::instance();
694         $roleid = $this->assignUserCapability('moodle/user:manageownfiles', $context->id);
696         $context = context_user::instance($USER->id);
697         $contextid = $context->id;
698         $component = "user";
699         $filearea = "draft";
700         $itemid = 0;
701         $filepath = "/";
702         $filename = "Simple.txt";
703         $filecontent = base64_encode("Let us create a nice simple file");
704         $contextlevel = null;
705         $instanceid = null;
706         $browser = get_file_browser();
708         // Call the files api to create a file.
709         $draftfile = core_files_external::upload($contextid, $component, $filearea, $itemid, $filepath,
710                                                  $filename, $filecontent, $contextlevel, $instanceid);
711         $draftfile = external_api::clean_returnvalue(core_files_external::upload_returns(), $draftfile);
713         $draftid = $draftfile['itemid'];
714         // Make sure the file was created.
715         $file = $browser->get_file_info($context, $component, $filearea, $draftid, $filepath, $filename);
716         $this->assertNotEmpty($file);
718         // Make sure the file does not exist in the user private files.
719         $file = $browser->get_file_info($context, $component, 'private', 0, $filepath, $filename);
720         $this->assertEmpty($file);
722         // Call the external function.
723         core_user_external::add_user_private_files($draftid);
725         // Make sure the file was added to the user private files.
726         $file = $browser->get_file_info($context, $component, 'private', 0, $filepath, $filename);
727         $this->assertNotEmpty($file);
728     }
730     /**
731      * Test add user device
732      */
733     public function test_add_user_device() {
734         global $USER, $CFG, $DB;
736         $this->resetAfterTest(true);
738         $device = array(
739                 'appid' => 'com.moodle.moodlemobile',
740                 'name' => 'occam',
741                 'model' => 'Nexus 4',
742                 'platform' => 'Android',
743                 'version' => '4.2.2',
744                 'pushid' => 'apushdkasdfj4835',
745                 'uuid' => 'asdnfl348qlksfaasef859'
746                 );
748         // Call the external function.
749         core_user_external::add_user_device($device['appid'], $device['name'], $device['model'], $device['platform'],
750                                             $device['version'], $device['pushid'], $device['uuid']);
752         $created = $DB->get_record('user_devices', array('pushid' => $device['pushid']));
753         $created = (array) $created;
755         $this->assertEquals($device, array_intersect_key((array)$created, $device));
757         // Test reuse the same pushid value.
758         $warnings = core_user_external::add_user_device($device['appid'], $device['name'], $device['model'], $device['platform'],
759                                                         $device['version'], $device['pushid'], $device['uuid']);
760         // We need to execute the return values cleaning process to simulate the web service server.
761         $warnings = external_api::clean_returnvalue(core_user_external::add_user_device_returns(), $warnings);
762         $this->assertCount(1, $warnings);
764         // Test update an existing device.
765         $device['pushid'] = 'different than before';
766         $warnings = core_user_external::add_user_device($device['appid'], $device['name'], $device['model'], $device['platform'],
767                                                         $device['version'], $device['pushid'], $device['uuid']);
768         $warnings = external_api::clean_returnvalue(core_user_external::add_user_device_returns(), $warnings);
770         $this->assertEquals(1, $DB->count_records('user_devices'));
771         $updated = $DB->get_record('user_devices', array('pushid' => $device['pushid']));
772         $this->assertEquals($device, array_intersect_key((array)$updated, $device));
774         // Test creating a new device just changing the uuid.
775         $device['uuid'] = 'newuidforthesameuser';
776         $device['pushid'] = 'new different than before';
777         $warnings = core_user_external::add_user_device($device['appid'], $device['name'], $device['model'], $device['platform'],
778                                                         $device['version'], $device['pushid'], $device['uuid']);
779         $warnings = external_api::clean_returnvalue(core_user_external::add_user_device_returns(), $warnings);
780         $this->assertEquals(2, $DB->count_records('user_devices'));
781     }
783     /**
784      * Test remove user device
785      */
786     public function test_remove_user_device() {
787         global $USER, $CFG, $DB;
789         $this->resetAfterTest(true);
791         $device = array(
792                 'appid' => 'com.moodle.moodlemobile',
793                 'name' => 'occam',
794                 'model' => 'Nexus 4',
795                 'platform' => 'Android',
796                 'version' => '4.2.2',
797                 'pushid' => 'apushdkasdfj4835',
798                 'uuid' => 'ABCDE3723ksdfhasfaasef859'
799                 );
801         // A device with the same properties except the appid and pushid.
802         $device2 = $device;
803         $device2['pushid'] = "0987654321";
804         $device2['appid'] = "other.app.com";
806         // Create a user device using the external API function.
807         core_user_external::add_user_device($device['appid'], $device['name'], $device['model'], $device['platform'],
808                                             $device['version'], $device['pushid'], $device['uuid']);
810         // Create the same device but for a different app.
811         core_user_external::add_user_device($device2['appid'], $device2['name'], $device2['model'], $device2['platform'],
812                                             $device2['version'], $device2['pushid'], $device2['uuid']);
814         // Try to remove a device that does not exist.
815         $result = core_user_external::remove_user_device('1234567890');
816         $result = external_api::clean_returnvalue(core_user_external::remove_user_device_returns(), $result);
817         $this->assertFalse($result['removed']);
818         $this->assertCount(1, $result['warnings']);
820         // Try to remove a device that does not exist for an existing app.
821         $result = core_user_external::remove_user_device('1234567890', $device['appid']);
822         $result = external_api::clean_returnvalue(core_user_external::remove_user_device_returns(), $result);
823         $this->assertFalse($result['removed']);
824         $this->assertCount(1, $result['warnings']);
826         // Remove an existing device for an existing app. This will remove one of the two devices.
827         $result = core_user_external::remove_user_device($device['uuid'], $device['appid']);
828         $result = external_api::clean_returnvalue(core_user_external::remove_user_device_returns(), $result);
829         $this->assertTrue($result['removed']);
831         // Remove all the devices. This must remove the remaining device.
832         $result = core_user_external::remove_user_device($device['uuid']);
833         $result = external_api::clean_returnvalue(core_user_external::remove_user_device_returns(), $result);
834         $this->assertTrue($result['removed']);
835     }