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/>.
16
17/**
18 * Unit tests for user/lib.php.
19 *
20 * @package    core_user
21 * @category   phpunit
22 * @copyright  2013 Rajesh Taneja <rajesh@moodle.com>
23 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26defined('MOODLE_INTERNAL') || die();
27
28global $CFG;
29require_once($CFG->dirroot.'/user/lib.php');
30
31/**
32 * Unit tests for user lib api.
33 *
34 * @package    core_user
35 * @category   phpunit
36 * @copyright  2013 Rajesh Taneja <rajesh@moodle.com>
37 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 */
39class core_userliblib_testcase extends advanced_testcase {
40    /**
41     * Test user_get_user_details_courses
42     */
43    public function test_user_get_user_details_courses() {
44        global $DB;
45
46        $this->resetAfterTest();
47
48        // Create user and modify user profile.
49        $user1 = $this->getDataGenerator()->create_user();
50        $user2 = $this->getDataGenerator()->create_user();
51        $user3 = $this->getDataGenerator()->create_user();
52
53        $course1 = $this->getDataGenerator()->create_course();
54        $coursecontext = context_course::instance($course1->id);
55        $teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
56        $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
57        $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
58        role_assign($teacherrole->id, $user1->id, $coursecontext->id);
59        role_assign($teacherrole->id, $user2->id, $coursecontext->id);
60
61        accesslib_clear_all_caches_for_unit_testing();
62
63        // Get user2 details as a user with super system capabilities.
64        $result = user_get_user_details_courses($user2);
65        $this->assertEquals($user2->id, $result['id']);
66        $this->assertEquals(fullname($user2), $result['fullname']);
67        $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
68
69        $this->setUser($user1);
70        // Get user2 details as a user who can only see this user in a course.
71        $result = user_get_user_details_courses($user2);
72        $this->assertEquals($user2->id, $result['id']);
73        $this->assertEquals(fullname($user2), $result['fullname']);
74        $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
75
76        // Get user2 details as a user who doesn't share any course with user2.
77        $this->setUser($user3);
78        $result = user_get_user_details_courses($user2);
79        $this->assertNull($result);
80    }
81
82    /**
83     * Verify return when course groupmode set to 'no groups'.
84     */
85    public function test_user_get_user_details_courses_groupmode_nogroups() {
86        $this->resetAfterTest();
87
88        // Enrol 2 users into a course with groupmode set to 'no groups'.
89        // Profiles should be visible.
90        $user1 = $this->getDataGenerator()->create_user();
91        $user2 = $this->getDataGenerator()->create_user();
92        $course = $this->getDataGenerator()->create_course((object) ['groupmode' => 0]);
93        $this->getDataGenerator()->enrol_user($user1->id, $course->id);
94        $this->getDataGenerator()->enrol_user($user2->id, $course->id);
95
96        $this->setUser($user1);
97        $userdetails = user_get_user_details_courses($user2);
98        $this->assertIsArray($userdetails);
99        $this->assertEquals($user2->id, $userdetails['id']);
100    }
101
102    /**
103     * Verify return when course groupmode set to 'separate groups'.
104     */
105    public function test_user_get_user_details_courses_groupmode_separate() {
106        $this->resetAfterTest();
107
108        // Enrol 2 users into a course with groupmode set to 'separate groups'.
109        // The users are not in any groups, so profiles should be hidden (same as if they were in separate groups).
110        $user1 = $this->getDataGenerator()->create_user();
111        $user2 = $this->getDataGenerator()->create_user();
112        $course = $this->getDataGenerator()->create_course((object) ['groupmode' => 1]);
113        $this->getDataGenerator()->enrol_user($user1->id, $course->id);
114        $this->getDataGenerator()->enrol_user($user2->id, $course->id);
115
116        $this->setUser($user1);
117        $this->assertNull(user_get_user_details_courses($user2));
118    }
119
120    /**
121     * Verify return when course groupmode set to 'visible groups'.
122     */
123    public function test_user_get_user_details_courses_groupmode_visible() {
124        $this->resetAfterTest();
125
126        // Enrol 2 users into a course with groupmode set to 'visible groups'.
127        // The users are not in any groups, and profiles should be visible because of the groupmode.
128        $user1 = $this->getDataGenerator()->create_user();
129        $user2 = $this->getDataGenerator()->create_user();
130        $course = $this->getDataGenerator()->create_course((object) ['groupmode' => 2]);
131        $this->getDataGenerator()->enrol_user($user1->id, $course->id);
132        $this->getDataGenerator()->enrol_user($user2->id, $course->id);
133
134        $this->setUser($user1);
135        $userdetails = user_get_user_details_courses($user2);
136        $this->assertIsArray($userdetails);
137        $this->assertEquals($user2->id, $userdetails['id']);
138    }
139
140    /**
141     * Test user_update_user.
142     */
143    public function test_user_update_user() {
144        global $DB;
145
146        $this->resetAfterTest();
147
148        // Create user and modify user profile.
149        $user = $this->getDataGenerator()->create_user();
150        $user->firstname = 'Test';
151        $user->password = 'M00dLe@T';
152
153        // Update user and capture event.
154        $sink = $this->redirectEvents();
155        user_update_user($user);
156        $events = $sink->get_events();
157        $sink->close();
158        $event = array_pop($events);
159
160        // Test updated value.
161        $dbuser = $DB->get_record('user', array('id' => $user->id));
162        $this->assertSame($user->firstname, $dbuser->firstname);
163        $this->assertNotSame('M00dLe@T', $dbuser->password);
164
165        // Test event.
166        $this->assertInstanceOf('\core\event\user_updated', $event);
167        $this->assertSame($user->id, $event->objectid);
168        $this->assertSame('user_updated', $event->get_legacy_eventname());
169        $this->assertEventLegacyData($dbuser, $event);
170        $this->assertEquals(context_user::instance($user->id), $event->get_context());
171        $expectedlogdata = array(SITEID, 'user', 'update', 'view.php?id='.$user->id, '');
172        $this->assertEventLegacyLogData($expectedlogdata, $event);
173
174        // Update user with no password update.
175        $password = $user->password = hash_internal_user_password('M00dLe@T');
176        user_update_user($user, false);
177        $dbuser = $DB->get_record('user', array('id' => $user->id));
178        $this->assertSame($password, $dbuser->password);
179
180        // Verify event is not triggred by user_update_user when needed.
181        $sink = $this->redirectEvents();
182        user_update_user($user, false, false);
183        $events = $sink->get_events();
184        $sink->close();
185        $this->assertCount(0, $events);
186
187        // With password, there should be 1 event.
188        $sink = $this->redirectEvents();
189        user_update_user($user, true, false);
190        $events = $sink->get_events();
191        $sink->close();
192        $this->assertCount(1, $events);
193        $event = array_pop($events);
194        $this->assertInstanceOf('\core\event\user_password_updated', $event);
195
196        // Test user data validation.
197        $user->username = 'johndoe123';
198        $user->auth = 'shibolth';
199        $user->country = 'WW';
200        $user->lang = 'xy';
201        $user->theme = 'somewrongthemename';
202        $user->timezone = '30.5';
203        $debugmessages = $this->getDebuggingMessages();
204        user_update_user($user, true, false);
205        $this->assertDebuggingCalledCount(5, $debugmessages);
206
207        // Now, with valid user data.
208        $user->username = 'johndoe321';
209        $user->auth = 'shibboleth';
210        $user->country = 'AU';
211        $user->lang = 'en';
212        $user->theme = 'classic';
213        $user->timezone = 'Australia/Perth';
214        user_update_user($user, true, false);
215        $this->assertDebuggingNotCalled();
216    }
217
218    /**
219     * Test create_users.
220     */
221    public function test_create_users() {
222        global $DB;
223
224        $this->resetAfterTest();
225
226        $user = array(
227            'username' => 'usernametest1',
228            'password' => 'Moodle2012!',
229            'idnumber' => 'idnumbertest1',
230            'firstname' => 'First Name User Test 1',
231            'lastname' => 'Last Name User Test 1',
232            'middlename' => 'Middle Name User Test 1',
233            'lastnamephonetic' => '最後のお名前のテスト一号',
234            'firstnamephonetic' => 'お名前のテスト一号',
235            'alternatename' => 'Alternate Name User Test 1',
236            'email' => 'usertest1@example.com',
237            'description' => 'This is a description for user 1',
238            'city' => 'Perth',
239            'country' => 'AU'
240            );
241
242        // Create user and capture event.
243        $sink = $this->redirectEvents();
244        $user['id'] = user_create_user($user);
245        $events = $sink->get_events();
246        $sink->close();
247        $event = array_pop($events);
248
249        // Test user info in DB.
250        $dbuser = $DB->get_record('user', array('id' => $user['id']));
251        $this->assertEquals($dbuser->username, $user['username']);
252        $this->assertEquals($dbuser->idnumber, $user['idnumber']);
253        $this->assertEquals($dbuser->firstname, $user['firstname']);
254        $this->assertEquals($dbuser->lastname, $user['lastname']);
255        $this->assertEquals($dbuser->email, $user['email']);
256        $this->assertEquals($dbuser->description, $user['description']);
257        $this->assertEquals($dbuser->city, $user['city']);
258        $this->assertEquals($dbuser->country, $user['country']);
259
260        // Test event.
261        $this->assertInstanceOf('\core\event\user_created', $event);
262        $this->assertEquals($user['id'], $event->objectid);
263        $this->assertEquals('user_created', $event->get_legacy_eventname());
264        $this->assertEquals(context_user::instance($user['id']), $event->get_context());
265        $this->assertEventLegacyData($dbuser, $event);
266        $expectedlogdata = array(SITEID, 'user', 'add', '/view.php?id='.$event->objectid, fullname($dbuser));
267        $this->assertEventLegacyLogData($expectedlogdata, $event);
268
269        // Verify event is not triggred by user_create_user when needed.
270        $user = array('username' => 'usernametest2'); // Create another user.
271        $sink = $this->redirectEvents();
272        user_create_user($user, true, false);
273        $events = $sink->get_events();
274        $sink->close();
275        $this->assertCount(0, $events);
276
277        // Test user data validation, first some invalid data.
278        $user['username'] = 'johndoe123';
279        $user['auth'] = 'shibolth';
280        $user['country'] = 'WW';
281        $user['lang'] = 'xy';
282        $user['theme'] = 'somewrongthemename';
283        $user['timezone'] = '-30.5';
284        $debugmessages = $this->getDebuggingMessages();
285        $user['id'] = user_create_user($user, true, false);
286        $this->assertDebuggingCalledCount(5, $debugmessages);
287        $dbuser = $DB->get_record('user', array('id' => $user['id']));
288        $this->assertEquals($dbuser->country, 0);
289        $this->assertEquals($dbuser->lang, 'en');
290        $this->assertEquals($dbuser->timezone, '');
291
292        // Now, with valid user data.
293        $user['username'] = 'johndoe321';
294        $user['auth'] = 'shibboleth';
295        $user['country'] = 'AU';
296        $user['lang'] = 'en';
297        $user['theme'] = 'classic';
298        $user['timezone'] = 'Australia/Perth';
299        user_create_user($user, true, false);
300        $this->assertDebuggingNotCalled();
301    }
302
303    /**
304     * Test that {@link user_create_user()} throws exception when invalid username is provided.
305     *
306     * @dataProvider data_create_user_invalid_username
307     * @param string $username Invalid username
308     * @param string $expectmessage Expected exception message
309     */
310    public function test_create_user_invalid_username($username, $expectmessage) {
311        global $CFG;
312
313        $this->resetAfterTest();
314        $CFG->extendedusernamechars = false;
315
316        $user = [
317            'username' => $username,
318        ];
319
320        $this->expectException('moodle_exception');
321        $this->expectExceptionMessage($expectmessage);
322
323        user_create_user($user);
324    }
325
326    /**
327     * Data provider for {@link self::test_create_user_invalid_username()}.
328     *
329     * @return array
330     */
331    public function data_create_user_invalid_username() {
332        return [
333            'empty_string' => [
334                '',
335                'The username cannot be blank',
336            ],
337            'only_whitespace' => [
338                "\t\t  \t\n ",
339                'The username cannot be blank',
340            ],
341            'lower_case' => [
342                'Mudrd8mz',
343                'The username must be in lower case',
344            ],
345            'extended_chars' => [
346                'dmudrák',
347                'The given username contains invalid characters',
348            ],
349        ];
350    }
351
352    /**
353     * Test function user_count_login_failures().
354     */
355    public function test_user_count_login_failures() {
356        $this->resetAfterTest();
357        $user = $this->getDataGenerator()->create_user();
358        $this->assertEquals(0, get_user_preferences('login_failed_count_since_success', 0, $user));
359        for ($i = 0; $i < 10; $i++) {
360            login_attempt_failed($user);
361        }
362        $this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user));
363        $count = user_count_login_failures($user); // Reset count.
364        $this->assertEquals(10, $count);
365        $this->assertEquals(0, get_user_preferences('login_failed_count_since_success', 0, $user));
366
367        for ($i = 0; $i < 10; $i++) {
368            login_attempt_failed($user);
369        }
370        $this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user));
371        $count = user_count_login_failures($user, false); // Do not reset count.
372        $this->assertEquals(10, $count);
373        $this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user));
374    }
375
376    /**
377     * Test function user_add_password_history().
378     */
379    public function test_user_add_password_history() {
380        global $DB;
381
382        $this->resetAfterTest();
383
384        $user1 = $this->getDataGenerator()->create_user();
385        $user2 = $this->getDataGenerator()->create_user();
386        $user3 = $this->getDataGenerator()->create_user();
387        $DB->delete_records('user_password_history', array());
388
389        set_config('passwordreuselimit', 0);
390
391        user_add_password_history($user1->id, 'pokus');
392        $this->assertEquals(0, $DB->count_records('user_password_history'));
393
394        // Test adding and discarding of old.
395
396        set_config('passwordreuselimit', 3);
397
398        user_add_password_history($user1->id, 'pokus');
399        $this->assertEquals(1, $DB->count_records('user_password_history'));
400        $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
401
402        user_add_password_history($user1->id, 'pokus2');
403        user_add_password_history($user1->id, 'pokus3');
404        user_add_password_history($user1->id, 'pokus4');
405        $this->assertEquals(3, $DB->count_records('user_password_history'));
406        $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user1->id)));
407
408        user_add_password_history($user2->id, 'pokus1');
409        $this->assertEquals(4, $DB->count_records('user_password_history'));
410        $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user1->id)));
411        $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user2->id)));
412
413        user_add_password_history($user2->id, 'pokus2');
414        user_add_password_history($user2->id, 'pokus3');
415        $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user2->id)));
416
417        $ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
418        user_add_password_history($user2->id, 'pokus4');
419        $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user2->id)));
420        $newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
421
422        $removed = array_shift($ids);
423        $added = array_pop($newids);
424        $this->assertSame($ids, $newids);
425        $this->assertGreaterThan($removed, $added);
426
427        // Test disabling prevents changes.
428
429        set_config('passwordreuselimit', 0);
430
431        $this->assertEquals(6, $DB->count_records('user_password_history'));
432
433        $ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
434        user_add_password_history($user2->id, 'pokus5');
435        user_add_password_history($user3->id, 'pokus1');
436        $newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
437        $this->assertSame($ids, $newids);
438        $this->assertEquals(6, $DB->count_records('user_password_history'));
439
440        set_config('passwordreuselimit', -1);
441
442        $ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
443        user_add_password_history($user2->id, 'pokus6');
444        user_add_password_history($user3->id, 'pokus6');
445        $newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
446        $this->assertSame($ids, $newids);
447        $this->assertEquals(6, $DB->count_records('user_password_history'));
448    }
449
450    /**
451     * Test function user_add_password_history().
452     */
453    public function test_user_is_previously_used_password() {
454        global $DB;
455
456        $this->resetAfterTest();
457
458        $user1 = $this->getDataGenerator()->create_user();
459        $user2 = $this->getDataGenerator()->create_user();
460        $DB->delete_records('user_password_history', array());
461
462        set_config('passwordreuselimit', 0);
463
464        user_add_password_history($user1->id, 'pokus');
465        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus'));
466
467        set_config('passwordreuselimit', 3);
468
469        user_add_password_history($user2->id, 'pokus1');
470        user_add_password_history($user2->id, 'pokus2');
471
472        user_add_password_history($user1->id, 'pokus1');
473        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1'));
474        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
475        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3'));
476        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
477
478        user_add_password_history($user1->id, 'pokus2');
479        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1'));
480        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2'));
481        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3'));
482        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
483
484        user_add_password_history($user1->id, 'pokus3');
485        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1'));
486        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2'));
487        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
488        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
489
490        user_add_password_history($user1->id, 'pokus4');
491        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
492        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2'));
493        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
494        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4'));
495
496        set_config('passwordreuselimit', 2);
497
498        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
499        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
500        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
501        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4'));
502
503        set_config('passwordreuselimit', 3);
504
505        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
506        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
507        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
508        $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4'));
509
510        set_config('passwordreuselimit', 0);
511
512        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
513        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
514        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3'));
515        $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
516    }
517
518    /**
519     * Test that password history is deleted together with user.
520     */
521    public function test_delete_of_hashes_on_user_delete() {
522        global $DB;
523
524        $this->resetAfterTest();
525
526        $user1 = $this->getDataGenerator()->create_user();
527        $user2 = $this->getDataGenerator()->create_user();
528        $DB->delete_records('user_password_history', array());
529
530        set_config('passwordreuselimit', 3);
531
532        user_add_password_history($user1->id, 'pokus');
533        user_add_password_history($user2->id, 'pokus1');
534        user_add_password_history($user2->id, 'pokus2');
535
536        $this->assertEquals(3, $DB->count_records('user_password_history'));
537        $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
538        $this->assertEquals(2, $DB->count_records('user_password_history', array('userid' => $user2->id)));
539
540        delete_user($user2);
541        $this->assertEquals(1, $DB->count_records('user_password_history'));
542        $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
543        $this->assertEquals(0, $DB->count_records('user_password_history', array('userid' => $user2->id)));
544    }
545
546    /**
547     * Test user_list_view function
548     */
549    public function test_user_list_view() {
550
551        $this->resetAfterTest();
552
553        // Course without sections.
554        $course = $this->getDataGenerator()->create_course();
555        $context = context_course::instance($course->id);
556
557        $this->setAdminUser();
558
559        // Redirect events to the sink, so we can recover them later.
560        $sink = $this->redirectEvents();
561
562        user_list_view($course, $context);
563        $events = $sink->get_events();
564        $this->assertCount(1, $events);
565        $event = reset($events);
566
567        // Check the event details are correct.
568        $this->assertInstanceOf('\core\event\user_list_viewed', $event);
569        $this->assertEquals($context, $event->get_context());
570        $this->assertEquals($course->shortname, $event->other['courseshortname']);
571        $this->assertEquals($course->fullname, $event->other['coursefullname']);
572
573    }
574
575    /**
576     * Test setting the user menu avatar size.
577     */
578    public function test_user_menu_custom_avatar_size() {
579        global $PAGE;
580        $this->resetAfterTest(true);
581
582        $testsize = 100;
583
584        $PAGE->set_url('/');
585        $user = $this->getDataGenerator()->create_user();
586        $opts = user_get_user_navigation_info($user, $PAGE, array('avatarsize' => $testsize));
587        $avatarhtml = $opts->metadata['useravatar'];
588
589        $matches = [];
590        preg_match('/(?:.*width=")(\d*)(?:" height=")(\d*)(?:".*\/>)/', $avatarhtml, $matches);
591        $this->assertCount(3, $matches);
592
593        $this->assertEquals(intval($matches[1]), $testsize);
594        $this->assertEquals(intval($matches[2]), $testsize);
595    }
596
597    /**
598     * Test user_can_view_profile
599     */
600    public function test_user_can_view_profile() {
601        global $DB, $CFG;
602
603        $this->resetAfterTest();
604
605        // Create five users.
606        $user1 = $this->getDataGenerator()->create_user();
607        $user2 = $this->getDataGenerator()->create_user();
608        $user3 = $this->getDataGenerator()->create_user();
609        $user4 = $this->getDataGenerator()->create_user();
610        $user5 = $this->getDataGenerator()->create_user();
611        $user6 = $this->getDataGenerator()->create_user(array('deleted' => 1));
612        $user7 = $this->getDataGenerator()->create_user();
613        $user8 = $this->getDataGenerator()->create_user();
614        $user8->id = 0; // Visitor.
615
616        $studentrole = $DB->get_record('role', array('shortname' => 'student'));
617        // Add the course creator role to the course contact and assign a user to that role.
618        $CFG->coursecontact = '2';
619        $coursecreatorrole = $DB->get_record('role', array('shortname' => 'coursecreator'));
620        $this->getDataGenerator()->role_assign($coursecreatorrole->id, $user7->id);
621
622         // Create two courses.
623        $course1 = $this->getDataGenerator()->create_course();
624        $course2 = $this->getDataGenerator()->create_course();
625        $coursecontext = context_course::instance($course2->id);
626        // Prepare another course with separate groups and groupmodeforce set to true.
627        $record = new stdClass();
628        $record->groupmode = 1;
629        $record->groupmodeforce = 1;
630        $course3 = $this->getDataGenerator()->create_course($record);
631        // Enrol users 1 and 2 in first course.
632        $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
633        $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
634        // Enrol users 2 and 3 in second course.
635        $this->getDataGenerator()->enrol_user($user2->id, $course2->id);
636        $this->getDataGenerator()->enrol_user($user3->id, $course2->id);
637        // Enrol users 1, 4, and 5 into course 3.
638        $this->getDataGenerator()->enrol_user($user1->id, $course3->id);
639        $this->getDataGenerator()->enrol_user($user4->id, $course3->id);
640        $this->getDataGenerator()->enrol_user($user5->id, $course3->id);
641
642        // User 3 should not be able to see user 1, either by passing their own course (course 2) or user 1's course (course 1).
643        $this->setUser($user3);
644        $this->assertFalse(user_can_view_profile($user1, $course2));
645        $this->assertFalse(user_can_view_profile($user1, $course1));
646
647        // Remove capability moodle/user:viewdetails in course 2.
648        assign_capability('moodle/user:viewdetails', CAP_PROHIBIT, $studentrole->id, $coursecontext);
649        // Set current user to user 1.
650        $this->setUser($user1);
651        // User 1 can see User 1's profile.
652        $this->assertTrue(user_can_view_profile($user1));
653
654        $tempcfg = $CFG->forceloginforprofiles;
655        $CFG->forceloginforprofiles = 0;
656        // Not forced to log in to view profiles, should be able to see all profiles besides user 6.
657        $users = array($user1, $user2, $user3, $user4, $user5, $user7);
658        foreach ($users as $user) {
659            $this->assertTrue(user_can_view_profile($user));
660        }
661        // Restore setting.
662        $CFG->forceloginforprofiles = $tempcfg;
663
664        // User 1 can not see user 6 as they have been deleted.
665        $this->assertFalse(user_can_view_profile($user6));
666        // User 1 can see User 7 as they are a course contact.
667        $this->assertTrue(user_can_view_profile($user7));
668        // User 1 is in a course with user 2 and has the right capability - return true.
669        $this->assertTrue(user_can_view_profile($user2));
670        // User 1 is not in a course with user 3 - return false.
671        $this->assertFalse(user_can_view_profile($user3));
672
673        // Set current user to user 2.
674        $this->setUser($user2);
675        // User 2 is in a course with user 3 but does not have the right capability - return false.
676        $this->assertFalse(user_can_view_profile($user3));
677
678        // Set user 1 in one group and users 4 and 5 in another group.
679        $group1 = $this->getDataGenerator()->create_group(array('courseid' => $course3->id));
680        $group2 = $this->getDataGenerator()->create_group(array('courseid' => $course3->id));
681        groups_add_member($group1->id, $user1->id);
682        groups_add_member($group2->id, $user4->id);
683        groups_add_member($group2->id, $user5->id);
684        $this->setUser($user1);
685        // Check that user 1 can not see user 4.
686        $this->assertFalse(user_can_view_profile($user4));
687        // Check that user 5 can see user 4.
688        $this->setUser($user5);
689        $this->assertTrue(user_can_view_profile($user4));
690
691        // Test the user:viewalldetails cap check using the course creator role which, by default, can't see student profiles.
692        $this->setUser($user7);
693        $this->assertFalse(user_can_view_profile($user4));
694        assign_capability('moodle/user:viewalldetails', CAP_ALLOW, $coursecreatorrole->id, context_system::instance()->id, true);
695        reload_all_capabilities();
696        $this->assertTrue(user_can_view_profile($user4));
697        unassign_capability('moodle/user:viewalldetails', $coursecreatorrole->id, $coursecontext->id);
698        reload_all_capabilities();
699
700        $CFG->coursecontact = null;
701
702        // Visitor (Not a guest user, userid=0).
703        $CFG->forceloginforprofiles = 1;
704        $this->setUser($user8);
705        $this->assertFalse(user_can_view_profile($user1));
706
707        // Let us test with guest user.
708        $this->setGuestUser();
709        $CFG->forceloginforprofiles = 1;
710        foreach ($users as $user) {
711            $this->assertFalse(user_can_view_profile($user));
712        }
713
714        // Even with cap, still guests should not be allowed in.
715        $guestrole = $DB->get_records_menu('role', array('shortname' => 'guest'), 'id', 'archetype, id');
716        assign_capability('moodle/user:viewdetails', CAP_ALLOW, $guestrole['guest'], context_system::instance()->id, true);
717        reload_all_capabilities();
718        foreach ($users as $user) {
719            $this->assertFalse(user_can_view_profile($user));
720        }
721
722        $CFG->forceloginforprofiles = 0;
723        foreach ($users as $user) {
724            $this->assertTrue(user_can_view_profile($user));
725        }
726
727        // Let us test with Visitor user.
728        $this->setUser($user8);
729        $CFG->forceloginforprofiles = 1;
730        foreach ($users as $user) {
731            $this->assertFalse(user_can_view_profile($user));
732        }
733
734        $CFG->forceloginforprofiles = 0;
735        foreach ($users as $user) {
736            $this->assertTrue(user_can_view_profile($user));
737        }
738
739        // Testing non-shared courses where capabilities are met, using system role overrides.
740        $CFG->forceloginforprofiles = $tempcfg;
741        $course4 = $this->getDataGenerator()->create_course();
742        $this->getDataGenerator()->enrol_user($user1->id, $course4->id);
743
744        // Assign a manager role at the system context.
745        $managerrole = $DB->get_record('role', array('shortname' => 'manager'));
746        $user9 = $this->getDataGenerator()->create_user();
747        $this->getDataGenerator()->role_assign($managerrole->id, $user9->id);
748
749        // Make sure viewalldetails and viewdetails are overridden to 'prevent' (i.e. can be overridden at a lower context).
750        $systemcontext = context_system::instance();
751        assign_capability('moodle/user:viewdetails', CAP_PREVENT, $managerrole->id, $systemcontext, true);
752        assign_capability('moodle/user:viewalldetails', CAP_PREVENT, $managerrole->id, $systemcontext, true);
753
754        // And override these to 'Allow' in a specific course.
755        $course4context = context_course::instance($course4->id);
756        assign_capability('moodle/user:viewalldetails', CAP_ALLOW, $managerrole->id, $course4context, true);
757        assign_capability('moodle/user:viewdetails', CAP_ALLOW, $managerrole->id, $course4context, true);
758
759        // The manager now shouldn't have viewdetails in the system or user context.
760        $this->setUser($user9);
761        $user1context = context_user::instance($user1->id);
762        $this->assertFalse(has_capability('moodle/user:viewdetails', $systemcontext));
763        $this->assertFalse(has_capability('moodle/user:viewdetails', $user1context));
764
765        // Confirm that user_can_view_profile() returns true for $user1 when called without $course param. It should find $course1.
766        $this->assertTrue(user_can_view_profile($user1));
767
768        // Confirm this also works when restricting scope to just that course.
769        $this->assertTrue(user_can_view_profile($user1, $course4));
770    }
771
772    /**
773     * Test user_get_user_details
774     */
775    public function test_user_get_user_details() {
776        global $DB;
777
778        $this->resetAfterTest();
779
780        // Create user and modify user profile.
781        $teacher = $this->getDataGenerator()->create_user();
782        $student = $this->getDataGenerator()->create_user();
783        $studentfullname = fullname($student);
784
785        $course1 = $this->getDataGenerator()->create_course();
786        $coursecontext = context_course::instance($course1->id);
787        $teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
788        $studentrole = $DB->get_record('role', array('shortname' => 'student'));
789        $this->getDataGenerator()->enrol_user($teacher->id, $course1->id);
790        $this->getDataGenerator()->enrol_user($student->id, $course1->id);
791        role_assign($teacherrole->id, $teacher->id, $coursecontext->id);
792        role_assign($studentrole->id, $student->id, $coursecontext->id);
793
794        accesslib_clear_all_caches_for_unit_testing();
795
796        // Get student details as a user with super system capabilities.
797        $result = user_get_user_details($student, $course1);
798        $this->assertEquals($student->id, $result['id']);
799        $this->assertEquals($studentfullname, $result['fullname']);
800        $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
801
802        $this->setUser($teacher);
803        // Get student details as a user who can only see this user in a course.
804        $result = user_get_user_details($student, $course1);
805        $this->assertEquals($student->id, $result['id']);
806        $this->assertEquals($studentfullname, $result['fullname']);
807        $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
808
809        // Get student details with required fields.
810        $result = user_get_user_details($student, $course1, array('id', 'fullname'));
811        $this->assertCount(2, $result);
812        $this->assertEquals($student->id, $result['id']);
813        $this->assertEquals($studentfullname, $result['fullname']);
814
815        // Get exception for invalid required fields.
816        $this->expectException('moodle_exception');
817        $result = user_get_user_details($student, $course1, array('wrongrequiredfield'));
818    }
819
820    /**
821     * Regression test for MDL-57840.
822     *
823     * Ensure the fields "auth, confirmed, idnumber, lang, theme, timezone and mailformat" are present when
824     * calling user_get_user_details() function.
825     */
826    public function test_user_get_user_details_missing_fields() {
827        global $CFG;
828
829        $this->resetAfterTest(true);
830        $this->setAdminUser(); // We need capabilities to view the data.
831        $user = self::getDataGenerator()->create_user([
832                                                          'auth'       => 'email',
833                                                          'confirmed'  => '0',
834                                                          'idnumber'   => 'someidnumber',
835                                                          'lang'       => 'en',
836                                                          'theme'      => $CFG->theme,
837                                                          'timezone'   => '5',
838                                                          'mailformat' => '0',
839                                                      ]);
840
841        // Fields that should get by default.
842        $got = user_get_user_details($user);
843        self::assertSame('email', $got['auth']);
844        self::assertSame('0', $got['confirmed']);
845        self::assertSame('someidnumber', $got['idnumber']);
846        self::assertSame('en', $got['lang']);
847        self::assertSame($CFG->theme, $got['theme']);
848        self::assertSame('5', $got['timezone']);
849        self::assertSame('0', $got['mailformat']);
850    }
851}
852