MDL-63174 user: core_user_create_users to throw exception on empty names
[moodle.git] / user / tests / userlib_test.php
CommitLineData
bb78e249
RT
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 {
d26eae4a
DW
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
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);
59
60 accesslib_clear_all_caches_for_unit_testing();
61
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']);
67
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']);
74
75 }
76
bb78e249
RT
77 /**
78 * Test user_update_user.
79 */
80 public function test_user_update_user() {
81 global $DB;
82
83 $this->resetAfterTest();
84
85 // Create user and modify user profile.
86 $user = $this->getDataGenerator()->create_user();
87 $user->firstname = 'Test';
88 $user->password = 'M00dLe@T';
89
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);
96
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);
101
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);
110
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);
2b55cb1b
RT
116
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);
123
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);
7a067206
SL
132
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';
16825c4e 139 $user->timezone = '30.5';
7a067206
SL
140 $user->url = 'wwww.somewrong@#$url.com.aus';
141 $debugmessages = $this->getDebuggingMessages();
142 user_update_user($user, true, false);
143 $this->assertDebuggingCalledCount(6, $debugmessages);
144
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();
bb78e249
RT
155 }
156
157 /**
158 * Test create_users.
159 */
160 public function test_create_users() {
161 global $DB;
162
163 $this->resetAfterTest();
164
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',
0fe86bbd 175 'email' => 'usertest1@example.com',
bb78e249
RT
176 'description' => 'This is a description for user 1',
177 'city' => 'Perth',
7a067206 178 'country' => 'AU'
bb78e249
RT
179 );
180
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);
187
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']);
198
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);
2b55cb1b
RT
207
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);
7a067206
SL
215
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';
16825c4e 222 $user['timezone'] = '-30.5';
7a067206
SL
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');
16825c4e 230 $this->assertEquals($dbuser->timezone, '');
7a067206
SL
231
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();
bb78e249 242 }
52dc1de7
AA
243
244 /**
245 * Test function user_count_login_failures().
246 */
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);
253 }
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));
258
259 for ($i = 0; $i < 10; $i++) {
260 login_attempt_failed($user);
261 }
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));
266 }
1d658535
PS
267
268 /**
269 * Test function user_add_password_history().
270 */
271 public function test_user_add_password_history() {
272 global $DB;
273
274 $this->resetAfterTest();
275
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());
280
281 set_config('passwordreuselimit', 0);
282
283 user_add_password_history($user1->id, 'pokus');
284 $this->assertEquals(0, $DB->count_records('user_password_history'));
285
286 // Test adding and discarding of old.
287
288 set_config('passwordreuselimit', 3);
289
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)));
293
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)));
299
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)));
304
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)));
308
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'));
313
314 $removed = array_shift($ids);
315 $added = array_pop($newids);
316 $this->assertSame($ids, $newids);
317 $this->assertGreaterThan($removed, $added);
318
319 // Test disabling prevents changes.
320
321 set_config('passwordreuselimit', 0);
322
323 $this->assertEquals(6, $DB->count_records('user_password_history'));
324
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'));
331
332 set_config('passwordreuselimit', -1);
333
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'));
340 }
341
342 /**
343 * Test function user_add_password_history().
344 */
345 public function test_user_is_previously_used_password() {
346 global $DB;
347
348 $this->resetAfterTest();
349
350 $user1 = $this->getDataGenerator()->create_user();
351 $user2 = $this->getDataGenerator()->create_user();
352 $DB->delete_records('user_password_history', array());
353
354 set_config('passwordreuselimit', 0);
355
356 user_add_password_history($user1->id, 'pokus');
357 $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus'));
358
359 set_config('passwordreuselimit', 3);
360
361 user_add_password_history($user2->id, 'pokus1');
362 user_add_password_history($user2->id, 'pokus2');
363
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'));
369
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'));
375
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'));
381
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'));
387
388 set_config('passwordreuselimit', 2);
389
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'));
394
395 set_config('passwordreuselimit', 3);
396
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'));
401
402 set_config('passwordreuselimit', 0);
403
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'));
408 }
409
410 /**
411 * Test that password history is deleted together with user.
412 */
413 public function test_delete_of_hashes_on_user_delete() {
414 global $DB;
415
416 $this->resetAfterTest();
417
418 $user1 = $this->getDataGenerator()->create_user();
419 $user2 = $this->getDataGenerator()->create_user();
420 $DB->delete_records('user_password_history', array());
421
422 set_config('passwordreuselimit', 3);
423
424 user_add_password_history($user1->id, 'pokus');
425 user_add_password_history($user2->id, 'pokus1');
426 user_add_password_history($user2->id, 'pokus2');
427
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)));
431
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)));
436 }
826d572d
JL
437
438 /**
439 * Test user_list_view function
440 */
441 public function test_user_list_view() {
442
443 $this->resetAfterTest();
444
445 // Course without sections.
446 $course = $this->getDataGenerator()->create_course();
447 $context = context_course::instance($course->id);
448
449 $this->setAdminUser();
450
451 // Redirect events to the sink, so we can recover them later.
452 $sink = $this->redirectEvents();
453
454 user_list_view($course, $context);
455 $events = $sink->get_events();
456 $this->assertCount(1, $events);
457 $event = reset($events);
458
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']);
464
465 }
466
9dcd5035
DB
467 /**
468 * Test setting the user menu avatar size.
469 */
470 public function test_user_menu_custom_avatar_size() {
471 global $PAGE;
472 $this->resetAfterTest(true);
473
474 $testsize = 100;
475
22b8c5b8 476 $PAGE->set_url('/');
9dcd5035
DB
477 $user = $this->getDataGenerator()->create_user();
478 $opts = user_get_user_navigation_info($user, $PAGE, array('avatarsize' => $testsize));
479 $avatarhtml = $opts->metadata['useravatar'];
480
481 $matches = [];
482 preg_match('/(?:.*width=")(\d*)(?:" height=")(\d*)(?:".*\/>)/', $avatarhtml, $matches);
483 $this->assertCount(3, $matches);
484
485 $this->assertEquals(intval($matches[1]), $testsize);
486 $this->assertEquals(intval($matches[2]), $testsize);
487 }
488
82e4d438
AG
489 /**
490 * Test user_can_view_profile
491 */
492 public function test_user_can_view_profile() {
493 global $DB, $CFG;
494
495 $this->resetAfterTest();
496
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();
3e40dc8c
AA
505 $user8 = $this->getDataGenerator()->create_user();
506 $user8->id = 0; // Visitor.
82e4d438
AG
507
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);
513
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);
533
4266786b
JD
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));
538
82e4d438
AG
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));
546
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));
553 }
554 // Restore setting.
555 $CFG->forceloginforprofiles = $tempcfg;
556
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));
565
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));
570
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));
583
4d068a67
JD
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();
592
82e4d438 593 $CFG->coursecontact = null;
3e40dc8c
AA
594
595 // Visitor (Not a guest user, userid=0).
596 $CFG->forceloginforprofiles = 1;
597 $this->setUser($user8);
d621396f 598 $this->assertFalse(user_can_view_profile($user1));
3e40dc8c 599
3e40dc8c 600 $allroles = $DB->get_records_menu('role', array(), 'id', 'archetype, id');
58d85af2
AA
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));
606 }
607
608 // Even with cap, still guests should not be allowed in.
d621396f
TL
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);
3e40dc8c 611 reload_all_capabilities();
58d85af2
AA
612 foreach ($users as $user) {
613 $this->assertFalse(user_can_view_profile($user));
614 }
615
616 $CFG->forceloginforprofiles = 0;
617 foreach ($users as $user) {
618 $this->assertTrue(user_can_view_profile($user));
619 }
620
621 // Let us test with Visitor user.
622 $this->setUser($user8);
3e40dc8c 623 $CFG->forceloginforprofiles = 1;
58d85af2
AA
624 foreach ($users as $user) {
625 $this->assertFalse(user_can_view_profile($user));
626 }
627
3e40dc8c 628 $CFG->forceloginforprofiles = 0;
58d85af2
AA
629 foreach ($users as $user) {
630 $this->assertTrue(user_can_view_profile($user));
631 }
067accce
JD
632
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);
637
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);
642
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();
648
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();
654
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));
660
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));
663
664 // Confirm this also works when restricting scope to just that course.
665 $this->assertTrue(user_can_view_profile($user1, $course4));
82e4d438 666 }
6399ecd7
JPG
667
668 /**
669 * Test user_get_user_details
670 */
671 public function test_user_get_user_details() {
672 global $DB;
673
674 $this->resetAfterTest();
675
676 // Create user and modify user profile.
677 $teacher = $this->getDataGenerator()->create_user();
678 $student = $this->getDataGenerator()->create_user();
679 $studentfullname = fullname($student);
680
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);
689
690 accesslib_clear_all_caches_for_unit_testing();
691
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']);
697
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']);
704
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']);
710
711 // Get exception for invalid required fields.
712 $this->expectException('moodle_exception');
713 $result = user_get_user_details($student, $course1, array('wrongrequiredfield'));
714 }
b80caca1
DTR
715
716 /**
717 * Regression test for MDL-57840.
718 *
719 * Ensure the fields "auth, confirmed, idnumber, lang, theme, timezone and mailformat" are present when
720 * calling user_get_user_details() function.
721 */
722 public function test_user_get_user_details_missing_fields() {
6db24235
JL
723 global $CFG;
724
b80caca1
DTR
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',
6db24235
JL
731 'lang' => 'en',
732 'theme' => $CFG->theme,
b80caca1
DTR
733 'timezone' => '50',
734 'mailformat' => '0',
735 ]);
736
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']);
6db24235
JL
742 self::assertSame('en', $got['lang']);
743 self::assertSame($CFG->theme, $got['theme']);
b80caca1
DTR
744 self::assertSame('50', $got['timezone']);
745 self::assertSame('0', $got['mailformat']);
746 }
ba6645da
MN
747
748 /**
749 * Test returning the total number of participants.
750 */
751 public function test_user_get_total_participants() {
752 global $DB;
753
754 $this->resetAfterTest();
755
756 // Create a course.
757 $course = self::getDataGenerator()->create_course();
758
759 // Create a teacher.
760 $teacher = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
761
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']);
766
767 // Create a group.
768 $group = self::getDataGenerator()->create_group(array('courseid' => $course->id));
769
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);
774
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']);
778
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);
783
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);
792
793 $lastaccess->userid = $student1->id;
794 $DB->insert_record('user_lastaccess', $lastaccess);
795
796 $lastaccess->userid = $student3->id;
797 $DB->insert_record('user_lastaccess', $lastaccess);
798
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.
9651e491
JP
801 $count = user_get_total_participants($course->id, $group->id, $accesssince + 1, $roleids['student'], 0, -1,
802 'searchforthis');
ba6645da
MN
803
804 $this->assertEquals(1, $count);
805 }
806
807 /**
808 * Test returning the number of participants on the front page.
809 */
810 public function test_user_get_total_participants_on_front_page() {
811 $this->resetAfterTest();
812
813 // Set it so that only 3 users have accessed the site within the last day.
814 $accesssince = time() - DAYSECS;
815
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]);
821
822 // Create a group.
823 $group = self::getDataGenerator()->create_group(array('courseid' => SITEID));
824
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);
829
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.
9651e491 832 $count = user_get_total_participants(SITEID, $group->id, $accesssince + 1, 0, 0, -1, 'searchforthis');
ba6645da
MN
833
834 $this->assertEquals(2, $count);
835 }
836
837 /**
838 * Test returning the participants.
839 */
840 public function test_user_get_participants() {
841 global $DB;
842
843 $this->resetAfterTest();
844
845 // Create a course.
846 $course = self::getDataGenerator()->create_course();
847
848 // Create a teacher.
849 $teacher = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
850
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']);
855
856 // Create a group.
857 $group = self::getDataGenerator()->create_group(array('courseid' => $course->id));
858
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);
863
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']);
867
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);
872
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);
881
882 $lastaccess->userid = $student1->id;
883 $DB->insert_record('user_lastaccess', $lastaccess);
884
885 $lastaccess->userid = $student3->id;
886 $DB->insert_record('user_lastaccess', $lastaccess);
887
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.
9651e491 890 $userset = user_get_participants($course->id, $group->id, $accesssince + 1, $roleids['student'], 0, -1, 'searchforthis');
ba6645da 891
ba6645da 892 $this->assertEquals($student1->id, $userset->current()->id);
78da366b 893 $this->assertEquals(1, iterator_count($userset));
ba6645da
MN
894 }
895
896 /**
897 * Test returning the participants on the front page.
898 */
899 public function test_user_get_participants_on_front_page() {
900 $this->resetAfterTest();
901
902 // Set it so that only 3 users have accessed the site within the last day.
903 $accesssince = time() - DAYSECS;
904
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]);
910
911 // Create a group.
912 $group = self::getDataGenerator()->create_group(array('courseid' => SITEID));
913
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);
918
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.
9651e491
JP
921 $userset = user_get_participants(SITEID, $group->id, $accesssince + 1, 0, 0, -1, 'searchforthis', '', array(),
922 'ORDER BY id ASC');
ba6645da
MN
923
924 $this->assertEquals($user1->id, $userset->current()->id);
925 $userset->next();
926 $this->assertEquals($user2->id, $userset->current()->id);
927 }
bb78e249 928}