Merge branch 'MDL-62643-master' of git://github.com/damyon/moodle
[moodle.git] / user / tests / userlib_test.php
blobbc5347c5ef3580129e7b42114c22cf03e1f05db5
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.
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 * Unit tests for user/lib.php.
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
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
29 require_once($CFG->dirroot.'/user/lib.php');
31 /**
32 * Unit tests for user lib api.
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
39 class core_userliblib_testcase extends advanced_testcase {
40 /**
41 * Test user_get_user_details_courses
43 public function test_user_get_user_details_courses() {
44 global $DB;
46 $this->resetAfterTest();
48 // Create user and modify user profile.
49 $user1 = $this->getDataGenerator()->create_user();
50 $user2 = $this->getDataGenerator()->create_user();
52 $course1 = $this->getDataGenerator()->create_course();
53 $coursecontext = context_course::instance($course1->id);
54 $teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
55 $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
56 $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
57 role_assign($teacherrole->id, $user1->id, $coursecontext->id);
58 role_assign($teacherrole->id, $user2->id, $coursecontext->id);
60 accesslib_clear_all_caches_for_unit_testing();
62 // Get user2 details as a user with super system capabilities.
63 $result = user_get_user_details_courses($user2);
64 $this->assertEquals($user2->id, $result['id']);
65 $this->assertEquals(fullname($user2), $result['fullname']);
66 $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
68 $this->setUser($user1);
69 // Get user2 details as a user who can only see this user in a course.
70 $result = user_get_user_details_courses($user2);
71 $this->assertEquals($user2->id, $result['id']);
72 $this->assertEquals(fullname($user2), $result['fullname']);
73 $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
77 /**
78 * Test user_update_user.
80 public function test_user_update_user() {
81 global $DB;
83 $this->resetAfterTest();
85 // Create user and modify user profile.
86 $user = $this->getDataGenerator()->create_user();
87 $user->firstname = 'Test';
88 $user->password = 'M00dLe@T';
90 // Update user and capture event.
91 $sink = $this->redirectEvents();
92 user_update_user($user);
93 $events = $sink->get_events();
94 $sink->close();
95 $event = array_pop($events);
97 // Test updated value.
98 $dbuser = $DB->get_record('user', array('id' => $user->id));
99 $this->assertSame($user->firstname, $dbuser->firstname);
100 $this->assertNotSame('M00dLe@T', $dbuser->password);
102 // Test event.
103 $this->assertInstanceOf('\core\event\user_updated', $event);
104 $this->assertSame($user->id, $event->objectid);
105 $this->assertSame('user_updated', $event->get_legacy_eventname());
106 $this->assertEventLegacyData($dbuser, $event);
107 $this->assertEquals(context_user::instance($user->id), $event->get_context());
108 $expectedlogdata = array(SITEID, 'user', 'update', 'view.php?id='.$user->id, '');
109 $this->assertEventLegacyLogData($expectedlogdata, $event);
111 // Update user with no password update.
112 $password = $user->password = hash_internal_user_password('M00dLe@T');
113 user_update_user($user, false);
114 $dbuser = $DB->get_record('user', array('id' => $user->id));
115 $this->assertSame($password, $dbuser->password);
117 // Verify event is not triggred by user_update_user when needed.
118 $sink = $this->redirectEvents();
119 user_update_user($user, false, false);
120 $events = $sink->get_events();
121 $sink->close();
122 $this->assertCount(0, $events);
124 // With password, there should be 1 event.
125 $sink = $this->redirectEvents();
126 user_update_user($user, true, false);
127 $events = $sink->get_events();
128 $sink->close();
129 $this->assertCount(1, $events);
130 $event = array_pop($events);
131 $this->assertInstanceOf('\core\event\user_password_updated', $event);
133 // Test user data validation.
134 $user->username = 'johndoe123';
135 $user->auth = 'shibolth';
136 $user->country = 'WW';
137 $user->lang = 'xy';
138 $user->theme = 'somewrongthemename';
139 $user->timezone = '30.5';
140 $user->url = 'wwww.somewrong@#$url.com.aus';
141 $debugmessages = $this->getDebuggingMessages();
142 user_update_user($user, true, false);
143 $this->assertDebuggingCalledCount(6, $debugmessages);
145 // Now, with valid user data.
146 $user->username = 'johndoe321';
147 $user->auth = 'shibboleth';
148 $user->country = 'AU';
149 $user->lang = 'en';
150 $user->theme = 'clean';
151 $user->timezone = 'Australia/Perth';
152 $user->url = 'www.moodle.org';
153 user_update_user($user, true, false);
154 $this->assertDebuggingNotCalled();
158 * Test create_users.
160 public function test_create_users() {
161 global $DB;
163 $this->resetAfterTest();
165 $user = array(
166 'username' => 'usernametest1',
167 'password' => 'Moodle2012!',
168 'idnumber' => 'idnumbertest1',
169 'firstname' => 'First Name User Test 1',
170 'lastname' => 'Last Name User Test 1',
171 'middlename' => 'Middle Name User Test 1',
172 'lastnamephonetic' => '最後のお名前のテスト一号',
173 'firstnamephonetic' => 'お名前のテスト一号',
174 'alternatename' => 'Alternate Name User Test 1',
175 'email' => 'usertest1@example.com',
176 'description' => 'This is a description for user 1',
177 'city' => 'Perth',
178 'country' => 'AU'
181 // Create user and capture event.
182 $sink = $this->redirectEvents();
183 $user['id'] = user_create_user($user);
184 $events = $sink->get_events();
185 $sink->close();
186 $event = array_pop($events);
188 // Test user info in DB.
189 $dbuser = $DB->get_record('user', array('id' => $user['id']));
190 $this->assertEquals($dbuser->username, $user['username']);
191 $this->assertEquals($dbuser->idnumber, $user['idnumber']);
192 $this->assertEquals($dbuser->firstname, $user['firstname']);
193 $this->assertEquals($dbuser->lastname, $user['lastname']);
194 $this->assertEquals($dbuser->email, $user['email']);
195 $this->assertEquals($dbuser->description, $user['description']);
196 $this->assertEquals($dbuser->city, $user['city']);
197 $this->assertEquals($dbuser->country, $user['country']);
199 // Test event.
200 $this->assertInstanceOf('\core\event\user_created', $event);
201 $this->assertEquals($user['id'], $event->objectid);
202 $this->assertEquals('user_created', $event->get_legacy_eventname());
203 $this->assertEquals(context_user::instance($user['id']), $event->get_context());
204 $this->assertEventLegacyData($dbuser, $event);
205 $expectedlogdata = array(SITEID, 'user', 'add', '/view.php?id='.$event->objectid, fullname($dbuser));
206 $this->assertEventLegacyLogData($expectedlogdata, $event);
208 // Verify event is not triggred by user_create_user when needed.
209 $user = array('username' => 'usernametest2'); // Create another user.
210 $sink = $this->redirectEvents();
211 user_create_user($user, true, false);
212 $events = $sink->get_events();
213 $sink->close();
214 $this->assertCount(0, $events);
216 // Test user data validation, first some invalid data.
217 $user['username'] = 'johndoe123';
218 $user['auth'] = 'shibolth';
219 $user['country'] = 'WW';
220 $user['lang'] = 'xy';
221 $user['theme'] = 'somewrongthemename';
222 $user['timezone'] = '-30.5';
223 $user['url'] = 'wwww.somewrong@#$url.com.aus';
224 $debugmessages = $this->getDebuggingMessages();
225 $user['id'] = user_create_user($user, true, false);
226 $this->assertDebuggingCalledCount(6, $debugmessages);
227 $dbuser = $DB->get_record('user', array('id' => $user['id']));
228 $this->assertEquals($dbuser->country, 0);
229 $this->assertEquals($dbuser->lang, 'en');
230 $this->assertEquals($dbuser->timezone, '');
232 // Now, with valid user data.
233 $user['username'] = 'johndoe321';
234 $user['auth'] = 'shibboleth';
235 $user['country'] = 'AU';
236 $user['lang'] = 'en';
237 $user['theme'] = 'clean';
238 $user['timezone'] = 'Australia/Perth';
239 $user['url'] = 'www.moodle.org';
240 user_create_user($user, true, false);
241 $this->assertDebuggingNotCalled();
245 * Test function user_count_login_failures().
247 public function test_user_count_login_failures() {
248 $this->resetAfterTest();
249 $user = $this->getDataGenerator()->create_user();
250 $this->assertEquals(0, get_user_preferences('login_failed_count_since_success', 0, $user));
251 for ($i = 0; $i < 10; $i++) {
252 login_attempt_failed($user);
254 $this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user));
255 $count = user_count_login_failures($user); // Reset count.
256 $this->assertEquals(10, $count);
257 $this->assertEquals(0, get_user_preferences('login_failed_count_since_success', 0, $user));
259 for ($i = 0; $i < 10; $i++) {
260 login_attempt_failed($user);
262 $this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user));
263 $count = user_count_login_failures($user, false); // Do not reset count.
264 $this->assertEquals(10, $count);
265 $this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user));
269 * Test function user_add_password_history().
271 public function test_user_add_password_history() {
272 global $DB;
274 $this->resetAfterTest();
276 $user1 = $this->getDataGenerator()->create_user();
277 $user2 = $this->getDataGenerator()->create_user();
278 $user3 = $this->getDataGenerator()->create_user();
279 $DB->delete_records('user_password_history', array());
281 set_config('passwordreuselimit', 0);
283 user_add_password_history($user1->id, 'pokus');
284 $this->assertEquals(0, $DB->count_records('user_password_history'));
286 // Test adding and discarding of old.
288 set_config('passwordreuselimit', 3);
290 user_add_password_history($user1->id, 'pokus');
291 $this->assertEquals(1, $DB->count_records('user_password_history'));
292 $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
294 user_add_password_history($user1->id, 'pokus2');
295 user_add_password_history($user1->id, 'pokus3');
296 user_add_password_history($user1->id, 'pokus4');
297 $this->assertEquals(3, $DB->count_records('user_password_history'));
298 $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user1->id)));
300 user_add_password_history($user2->id, 'pokus1');
301 $this->assertEquals(4, $DB->count_records('user_password_history'));
302 $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user1->id)));
303 $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user2->id)));
305 user_add_password_history($user2->id, 'pokus2');
306 user_add_password_history($user2->id, 'pokus3');
307 $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user2->id)));
309 $ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
310 user_add_password_history($user2->id, 'pokus4');
311 $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user2->id)));
312 $newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
314 $removed = array_shift($ids);
315 $added = array_pop($newids);
316 $this->assertSame($ids, $newids);
317 $this->assertGreaterThan($removed, $added);
319 // Test disabling prevents changes.
321 set_config('passwordreuselimit', 0);
323 $this->assertEquals(6, $DB->count_records('user_password_history'));
325 $ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
326 user_add_password_history($user2->id, 'pokus5');
327 user_add_password_history($user3->id, 'pokus1');
328 $newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
329 $this->assertSame($ids, $newids);
330 $this->assertEquals(6, $DB->count_records('user_password_history'));
332 set_config('passwordreuselimit', -1);
334 $ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
335 user_add_password_history($user2->id, 'pokus6');
336 user_add_password_history($user3->id, 'pokus6');
337 $newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
338 $this->assertSame($ids, $newids);
339 $this->assertEquals(6, $DB->count_records('user_password_history'));
343 * Test function user_add_password_history().
345 public function test_user_is_previously_used_password() {
346 global $DB;
348 $this->resetAfterTest();
350 $user1 = $this->getDataGenerator()->create_user();
351 $user2 = $this->getDataGenerator()->create_user();
352 $DB->delete_records('user_password_history', array());
354 set_config('passwordreuselimit', 0);
356 user_add_password_history($user1->id, 'pokus');
357 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus'));
359 set_config('passwordreuselimit', 3);
361 user_add_password_history($user2->id, 'pokus1');
362 user_add_password_history($user2->id, 'pokus2');
364 user_add_password_history($user1->id, 'pokus1');
365 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1'));
366 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
367 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3'));
368 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
370 user_add_password_history($user1->id, 'pokus2');
371 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1'));
372 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2'));
373 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3'));
374 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
376 user_add_password_history($user1->id, 'pokus3');
377 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1'));
378 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2'));
379 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
380 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
382 user_add_password_history($user1->id, 'pokus4');
383 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
384 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2'));
385 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
386 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4'));
388 set_config('passwordreuselimit', 2);
390 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
391 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
392 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
393 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4'));
395 set_config('passwordreuselimit', 3);
397 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
398 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
399 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
400 $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4'));
402 set_config('passwordreuselimit', 0);
404 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
405 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
406 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3'));
407 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
411 * Test that password history is deleted together with user.
413 public function test_delete_of_hashes_on_user_delete() {
414 global $DB;
416 $this->resetAfterTest();
418 $user1 = $this->getDataGenerator()->create_user();
419 $user2 = $this->getDataGenerator()->create_user();
420 $DB->delete_records('user_password_history', array());
422 set_config('passwordreuselimit', 3);
424 user_add_password_history($user1->id, 'pokus');
425 user_add_password_history($user2->id, 'pokus1');
426 user_add_password_history($user2->id, 'pokus2');
428 $this->assertEquals(3, $DB->count_records('user_password_history'));
429 $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
430 $this->assertEquals(2, $DB->count_records('user_password_history', array('userid' => $user2->id)));
432 delete_user($user2);
433 $this->assertEquals(1, $DB->count_records('user_password_history'));
434 $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
435 $this->assertEquals(0, $DB->count_records('user_password_history', array('userid' => $user2->id)));
439 * Test user_list_view function
441 public function test_user_list_view() {
443 $this->resetAfterTest();
445 // Course without sections.
446 $course = $this->getDataGenerator()->create_course();
447 $context = context_course::instance($course->id);
449 $this->setAdminUser();
451 // Redirect events to the sink, so we can recover them later.
452 $sink = $this->redirectEvents();
454 user_list_view($course, $context);
455 $events = $sink->get_events();
456 $this->assertCount(1, $events);
457 $event = reset($events);
459 // Check the event details are correct.
460 $this->assertInstanceOf('\core\event\user_list_viewed', $event);
461 $this->assertEquals($context, $event->get_context());
462 $this->assertEquals($course->shortname, $event->other['courseshortname']);
463 $this->assertEquals($course->fullname, $event->other['coursefullname']);
468 * Test setting the user menu avatar size.
470 public function test_user_menu_custom_avatar_size() {
471 global $PAGE;
472 $this->resetAfterTest(true);
474 $testsize = 100;
476 $PAGE->set_url('/');
477 $user = $this->getDataGenerator()->create_user();
478 $opts = user_get_user_navigation_info($user, $PAGE, array('avatarsize' => $testsize));
479 $avatarhtml = $opts->metadata['useravatar'];
481 $matches = [];
482 preg_match('/(?:.*width=")(\d*)(?:" height=")(\d*)(?:".*\/>)/', $avatarhtml, $matches);
483 $this->assertCount(3, $matches);
485 $this->assertEquals(intval($matches[1]), $testsize);
486 $this->assertEquals(intval($matches[2]), $testsize);
490 * Test user_can_view_profile
492 public function test_user_can_view_profile() {
493 global $DB, $CFG;
495 $this->resetAfterTest();
497 // Create five users.
498 $user1 = $this->getDataGenerator()->create_user();
499 $user2 = $this->getDataGenerator()->create_user();
500 $user3 = $this->getDataGenerator()->create_user();
501 $user4 = $this->getDataGenerator()->create_user();
502 $user5 = $this->getDataGenerator()->create_user();
503 $user6 = $this->getDataGenerator()->create_user(array('deleted' => 1));
504 $user7 = $this->getDataGenerator()->create_user();
505 $user8 = $this->getDataGenerator()->create_user();
506 $user8->id = 0; // Visitor.
508 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
509 // Add the course creator role to the course contact and assign a user to that role.
510 $CFG->coursecontact = '2';
511 $coursecreatorrole = $DB->get_record('role', array('shortname' => 'coursecreator'));
512 $this->getDataGenerator()->role_assign($coursecreatorrole->id, $user7->id);
514 // Create two courses.
515 $course1 = $this->getDataGenerator()->create_course();
516 $course2 = $this->getDataGenerator()->create_course();
517 $coursecontext = context_course::instance($course2->id);
518 // Prepare another course with separate groups and groupmodeforce set to true.
519 $record = new stdClass();
520 $record->groupmode = 1;
521 $record->groupmodeforce = 1;
522 $course3 = $this->getDataGenerator()->create_course($record);
523 // Enrol users 1 and 2 in first course.
524 $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
525 $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
526 // Enrol users 2 and 3 in second course.
527 $this->getDataGenerator()->enrol_user($user2->id, $course2->id);
528 $this->getDataGenerator()->enrol_user($user3->id, $course2->id);
529 // Enrol users 1, 4, and 5 into course 3.
530 $this->getDataGenerator()->enrol_user($user1->id, $course3->id);
531 $this->getDataGenerator()->enrol_user($user4->id, $course3->id);
532 $this->getDataGenerator()->enrol_user($user5->id, $course3->id);
534 // 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).
535 $this->setUser($user3);
536 $this->assertFalse(user_can_view_profile($user1, $course2));
537 $this->assertFalse(user_can_view_profile($user1, $course1));
539 // Remove capability moodle/user:viewdetails in course 2.
540 assign_capability('moodle/user:viewdetails', CAP_PROHIBIT, $studentrole->id, $coursecontext);
541 $coursecontext->mark_dirty();
542 // Set current user to user 1.
543 $this->setUser($user1);
544 // User 1 can see User 1's profile.
545 $this->assertTrue(user_can_view_profile($user1));
547 $tempcfg = $CFG->forceloginforprofiles;
548 $CFG->forceloginforprofiles = 0;
549 // Not forced to log in to view profiles, should be able to see all profiles besides user 6.
550 $users = array($user1, $user2, $user3, $user4, $user5, $user7);
551 foreach ($users as $user) {
552 $this->assertTrue(user_can_view_profile($user));
554 // Restore setting.
555 $CFG->forceloginforprofiles = $tempcfg;
557 // User 1 can not see user 6 as they have been deleted.
558 $this->assertFalse(user_can_view_profile($user6));
559 // User 1 can see User 7 as they are a course contact.
560 $this->assertTrue(user_can_view_profile($user7));
561 // User 1 is in a course with user 2 and has the right capability - return true.
562 $this->assertTrue(user_can_view_profile($user2));
563 // User 1 is not in a course with user 3 - return false.
564 $this->assertFalse(user_can_view_profile($user3));
566 // Set current user to user 2.
567 $this->setUser($user2);
568 // User 2 is in a course with user 3 but does not have the right capability - return false.
569 $this->assertFalse(user_can_view_profile($user3));
571 // Set user 1 in one group and users 4 and 5 in another group.
572 $group1 = $this->getDataGenerator()->create_group(array('courseid' => $course3->id));
573 $group2 = $this->getDataGenerator()->create_group(array('courseid' => $course3->id));
574 groups_add_member($group1->id, $user1->id);
575 groups_add_member($group2->id, $user4->id);
576 groups_add_member($group2->id, $user5->id);
577 $this->setUser($user1);
578 // Check that user 1 can not see user 4.
579 $this->assertFalse(user_can_view_profile($user4));
580 // Check that user 5 can see user 4.
581 $this->setUser($user5);
582 $this->assertTrue(user_can_view_profile($user4));
584 // Test the user:viewalldetails cap check using the course creator role which, by default, can't see student profiles.
585 $this->setUser($user7);
586 $this->assertFalse(user_can_view_profile($user4));
587 assign_capability('moodle/user:viewalldetails', CAP_ALLOW, $coursecreatorrole->id, context_system::instance()->id, true);
588 reload_all_capabilities();
589 $this->assertTrue(user_can_view_profile($user4));
590 unassign_capability('moodle/user:viewalldetails', $coursecreatorrole->id, $coursecontext->id);
591 reload_all_capabilities();
593 $CFG->coursecontact = null;
595 // Visitor (Not a guest user, userid=0).
596 $CFG->forceloginforprofiles = 1;
597 $this->setUser($user8);
598 $this->assertFalse(user_can_view_profile($user1));
600 $allroles = $DB->get_records_menu('role', array(), 'id', 'archetype, id');
601 // Let us test with guest user.
602 $this->setGuestUser();
603 $CFG->forceloginforprofiles = 1;
604 foreach ($users as $user) {
605 $this->assertFalse(user_can_view_profile($user));
608 // Even with cap, still guests should not be allowed in.
609 $guestrole = $DB->get_records_menu('role', array('shortname' => 'guest'), 'id', 'archetype, id');
610 assign_capability('moodle/user:viewdetails', CAP_ALLOW, $guestrole['guest'], context_system::instance()->id, true);
611 reload_all_capabilities();
612 foreach ($users as $user) {
613 $this->assertFalse(user_can_view_profile($user));
616 $CFG->forceloginforprofiles = 0;
617 foreach ($users as $user) {
618 $this->assertTrue(user_can_view_profile($user));
621 // Let us test with Visitor user.
622 $this->setUser($user8);
623 $CFG->forceloginforprofiles = 1;
624 foreach ($users as $user) {
625 $this->assertFalse(user_can_view_profile($user));
628 $CFG->forceloginforprofiles = 0;
629 foreach ($users as $user) {
630 $this->assertTrue(user_can_view_profile($user));
633 // Testing non-shared courses where capabilities are met, using system role overrides.
634 $CFG->forceloginforprofiles = $tempcfg;
635 $course4 = $this->getDataGenerator()->create_course();
636 $this->getDataGenerator()->enrol_user($user1->id, $course4->id);
638 // Assign a manager role at the system context.
639 $managerrole = $DB->get_record('role', array('shortname' => 'manager'));
640 $user9 = $this->getDataGenerator()->create_user();
641 $this->getDataGenerator()->role_assign($managerrole->id, $user9->id);
643 // Make sure viewalldetails and viewdetails are overridden to 'prevent' (i.e. can be overridden at a lower context).
644 $systemcontext = context_system::instance();
645 assign_capability('moodle/user:viewdetails', CAP_PREVENT, $managerrole->id, $systemcontext, true);
646 assign_capability('moodle/user:viewalldetails', CAP_PREVENT, $managerrole->id, $systemcontext, true);
647 $systemcontext->mark_dirty();
649 // And override these to 'Allow' in a specific course.
650 $course4context = context_course::instance($course4->id);
651 assign_capability('moodle/user:viewalldetails', CAP_ALLOW, $managerrole->id, $course4context, true);
652 assign_capability('moodle/user:viewdetails', CAP_ALLOW, $managerrole->id, $course4context, true);
653 $course4context->mark_dirty();
655 // The manager now shouldn't have viewdetails in the system or user context.
656 $this->setUser($user9);
657 $user1context = context_user::instance($user1->id);
658 $this->assertFalse(has_capability('moodle/user:viewdetails', $systemcontext));
659 $this->assertFalse(has_capability('moodle/user:viewdetails', $user1context));
661 // Confirm that user_can_view_profile() returns true for $user1 when called without $course param. It should find $course1.
662 $this->assertTrue(user_can_view_profile($user1));
664 // Confirm this also works when restricting scope to just that course.
665 $this->assertTrue(user_can_view_profile($user1, $course4));
669 * Test user_get_user_details
671 public function test_user_get_user_details() {
672 global $DB;
674 $this->resetAfterTest();
676 // Create user and modify user profile.
677 $teacher = $this->getDataGenerator()->create_user();
678 $student = $this->getDataGenerator()->create_user();
679 $studentfullname = fullname($student);
681 $course1 = $this->getDataGenerator()->create_course();
682 $coursecontext = context_course::instance($course1->id);
683 $teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
684 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
685 $this->getDataGenerator()->enrol_user($teacher->id, $course1->id);
686 $this->getDataGenerator()->enrol_user($student->id, $course1->id);
687 role_assign($teacherrole->id, $teacher->id, $coursecontext->id);
688 role_assign($studentrole->id, $student->id, $coursecontext->id);
690 accesslib_clear_all_caches_for_unit_testing();
692 // Get student details as a user with super system capabilities.
693 $result = user_get_user_details($student, $course1);
694 $this->assertEquals($student->id, $result['id']);
695 $this->assertEquals($studentfullname, $result['fullname']);
696 $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
698 $this->setUser($teacher);
699 // Get student details as a user who can only see this user in a course.
700 $result = user_get_user_details($student, $course1);
701 $this->assertEquals($student->id, $result['id']);
702 $this->assertEquals($studentfullname, $result['fullname']);
703 $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
705 // Get student details with required fields.
706 $result = user_get_user_details($student, $course1, array('id', 'fullname'));
707 $this->assertCount(2, $result);
708 $this->assertEquals($student->id, $result['id']);
709 $this->assertEquals($studentfullname, $result['fullname']);
711 // Get exception for invalid required fields.
712 $this->expectException('moodle_exception');
713 $result = user_get_user_details($student, $course1, array('wrongrequiredfield'));
717 * Regression test for MDL-57840.
719 * Ensure the fields "auth, confirmed, idnumber, lang, theme, timezone and mailformat" are present when
720 * calling user_get_user_details() function.
722 public function test_user_get_user_details_missing_fields() {
723 global $CFG;
725 $this->resetAfterTest(true);
726 $this->setAdminUser(); // We need capabilities to view the data.
727 $user = self::getDataGenerator()->create_user([
728 'auth' => 'auth_something',
729 'confirmed' => '0',
730 'idnumber' => 'someidnumber',
731 'lang' => 'en',
732 'theme' => $CFG->theme,
733 'timezone' => '50',
734 'mailformat' => '0',
737 // Fields that should get by default.
738 $got = user_get_user_details($user);
739 self::assertSame('auth_something', $got['auth']);
740 self::assertSame('0', $got['confirmed']);
741 self::assertSame('someidnumber', $got['idnumber']);
742 self::assertSame('en', $got['lang']);
743 self::assertSame($CFG->theme, $got['theme']);
744 self::assertSame('50', $got['timezone']);
745 self::assertSame('0', $got['mailformat']);
749 * Test returning the total number of participants.
751 public function test_user_get_total_participants() {
752 global $DB;
754 $this->resetAfterTest();
756 // Create a course.
757 $course = self::getDataGenerator()->create_course();
759 // Create a teacher.
760 $teacher = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
762 // Create a bunch of students.
763 $student1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
764 $student2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
765 $student3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
767 // Create a group.
768 $group = self::getDataGenerator()->create_group(array('courseid' => $course->id));
770 // Enrol the students.
771 self::getDataGenerator()->enrol_user($student1->id, $course->id);
772 self::getDataGenerator()->enrol_user($student2->id, $course->id);
773 self::getDataGenerator()->enrol_user($student3->id, $course->id);
775 // Enrol the teacher.
776 $roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
777 self::getDataGenerator()->enrol_user($teacher->id, $course->id, $roleids['editingteacher']);
779 // Add the teacher and two of the students to the group.
780 groups_add_member($group->id, $teacher->id);
781 groups_add_member($group->id, $student1->id);
782 groups_add_member($group->id, $student2->id);
784 // Set it so the teacher and two of the students have accessed the courses within the last day,
785 // but only one of the students is in the group.
786 $accesssince = time() - DAYSECS;
787 $lastaccess = new stdClass();
788 $lastaccess->userid = $teacher->id;
789 $lastaccess->courseid = $course->id;
790 $lastaccess->timeaccess = time() - DAYSECS;
791 $DB->insert_record('user_lastaccess', $lastaccess);
793 $lastaccess->userid = $student1->id;
794 $DB->insert_record('user_lastaccess', $lastaccess);
796 $lastaccess->userid = $student3->id;
797 $DB->insert_record('user_lastaccess', $lastaccess);
799 // Now, when we perform the following search we should only return 1 user. A student who belongs to
800 // the group and has the name 'searchforthis' and has also accessed the course in the last day.
801 $count = user_get_total_participants($course->id, $group->id, $accesssince + 1, $roleids['student'], 0, -1,
802 'searchforthis');
804 $this->assertEquals(1, $count);
808 * Test returning the number of participants on the front page.
810 public function test_user_get_total_participants_on_front_page() {
811 $this->resetAfterTest();
813 // Set it so that only 3 users have accessed the site within the last day.
814 $accesssince = time() - DAYSECS;
816 // Create a bunch of users.
817 $user1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
818 $user2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
819 $user3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
820 $user4 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
822 // Create a group.
823 $group = self::getDataGenerator()->create_group(array('courseid' => SITEID));
825 // Add 3 of the users to a group.
826 groups_add_member($group->id, $user1->id);
827 groups_add_member($group->id, $user2->id);
828 groups_add_member($group->id, $user3->id);
830 // Now, when we perform the following search we should only return 2 users. Users who belong to
831 // the group and have the name 'searchforthis' and have also accessed the site in the last day.
832 $count = user_get_total_participants(SITEID, $group->id, $accesssince + 1, 0, 0, -1, 'searchforthis');
834 $this->assertEquals(2, $count);
838 * Test returning the participants.
840 public function test_user_get_participants() {
841 global $DB;
843 $this->resetAfterTest();
845 // Create a course.
846 $course = self::getDataGenerator()->create_course();
848 // Create a teacher.
849 $teacher = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
851 // Create a bunch of students.
852 $student1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
853 $student2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
854 $student3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
856 // Create a group.
857 $group = self::getDataGenerator()->create_group(array('courseid' => $course->id));
859 // Enrol the students.
860 self::getDataGenerator()->enrol_user($student1->id, $course->id);
861 self::getDataGenerator()->enrol_user($student2->id, $course->id);
862 self::getDataGenerator()->enrol_user($student3->id, $course->id);
864 // Enrol the teacher.
865 $roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
866 self::getDataGenerator()->enrol_user($teacher->id, $course->id, $roleids['editingteacher']);
868 // Add the teacher and two of the students to the group.
869 groups_add_member($group->id, $teacher->id);
870 groups_add_member($group->id, $student1->id);
871 groups_add_member($group->id, $student2->id);
873 // Set it so the teacher and two of the students have accessed the course within the last day, but only one of
874 // the students is in the group.
875 $accesssince = time() - DAYSECS;
876 $lastaccess = new stdClass();
877 $lastaccess->userid = $teacher->id;
878 $lastaccess->courseid = $course->id;
879 $lastaccess->timeaccess = time() - DAYSECS;
880 $DB->insert_record('user_lastaccess', $lastaccess);
882 $lastaccess->userid = $student1->id;
883 $DB->insert_record('user_lastaccess', $lastaccess);
885 $lastaccess->userid = $student3->id;
886 $DB->insert_record('user_lastaccess', $lastaccess);
888 // Now, when we perform the following search we should only return 1 user. A student who belongs to
889 // the group and has the name 'searchforthis' and has also accessed the course in the last day.
890 $userset = user_get_participants($course->id, $group->id, $accesssince + 1, $roleids['student'], 0, -1, 'searchforthis');
892 $this->assertEquals($student1->id, $userset->current()->id);
893 $this->assertEquals(1, iterator_count($userset));
897 * Test returning the participants on the front page.
899 public function test_user_get_participants_on_front_page() {
900 $this->resetAfterTest();
902 // Set it so that only 3 users have accessed the site within the last day.
903 $accesssince = time() - DAYSECS;
905 // Create a bunch of users.
906 $user1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
907 $user2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
908 $user3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
909 $user4 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
911 // Create a group.
912 $group = self::getDataGenerator()->create_group(array('courseid' => SITEID));
914 // Add 3 of the users to a group.
915 groups_add_member($group->id, $user1->id);
916 groups_add_member($group->id, $user2->id);
917 groups_add_member($group->id, $user3->id);
919 // Now, when we perform the following search we should only return 2 users. Users who belong to
920 // the group and have the name 'searchforthis' and have also accessed the site in the last day.
921 $userset = user_get_participants(SITEID, $group->id, $accesssince + 1, 0, 0, -1, 'searchforthis', '', array(),
922 'ORDER BY id ASC');
924 $this->assertEquals($user1->id, $userset->current()->id);
925 $userset->next();
926 $this->assertEquals($user2->id, $userset->current()->id);