Merge branch 'wip-mdl-42560' of git://github.com/rajeshtaneja/moodle
[moodle.git] / lib / tests / accesslib_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Full functional accesslib test.
19  *
20  * @package    core
21  * @category   phpunit
22  * @copyright  2011 Petr Skoda {@link http://skodak.org}
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
29 /**
30  * Functional test for accesslib.php
31  *
32  * Note: execution may take many minutes especially on slower servers.
33  */
34 class core_accesslib_testcase extends advanced_testcase {
35     /**
36      * Verify comparison of context instances in phpunit asserts.
37      */
38     public function test_context_comparisons() {
39         $frontpagecontext1 = context_course::instance(SITEID);
40         context_helper::reset_caches();
41         $frontpagecontext2 = context_course::instance(SITEID);
42         $this->assertEquals($frontpagecontext1, $frontpagecontext2);
44         $user1 = context_user::instance(1);
45         $user2 = context_user::instance(2);
46         $this->assertNotEquals($user1, $user2);
47     }
49     /**
50      * Test resetting works.
51      */
52     public function test_accesslib_clear_all_caches() {
53         global $ACCESSLIB_PRIVATE;
55         $this->resetAfterTest();
57         $this->setAdminUser();
58         load_all_capabilities();
60         $this->assertNotEmpty($ACCESSLIB_PRIVATE->rolepermissions);
61         $this->assertNotEmpty($ACCESSLIB_PRIVATE->rolepermissions);
62         $this->assertNotEmpty($ACCESSLIB_PRIVATE->accessdatabyuser);
63         accesslib_clear_all_caches(true);
64         $this->assertEmpty($ACCESSLIB_PRIVATE->rolepermissions);
65         $this->assertEmpty($ACCESSLIB_PRIVATE->rolepermissions);
66         $this->assertEmpty($ACCESSLIB_PRIVATE->dirtycontexts);
67         $this->assertEmpty($ACCESSLIB_PRIVATE->accessdatabyuser);
68     }
70     /**
71      * Test getting of role access
72      */
73     public function test_get_role_access() {
74         global $DB;
76         $roles = $DB->get_records('role');
77         foreach ($roles as $role) {
78             $access = get_role_access($role->id);
80             $this->assertTrue(is_array($access));
81             $this->assertTrue(is_array($access['ra']));
82             $this->assertTrue(is_array($access['rdef']));
83             $this->assertTrue(isset($access['rdef_count']));
84             $this->assertTrue(is_array($access['loaded']));
85             $this->assertTrue(isset($access['time']));
86             $this->assertTrue(is_array($access['rsw']));
87         }
89         // Note: the data is validated in the functional permission evaluation test at the end of this testcase.
90     }
92     /**
93      * Test getting of guest role.
94      */
95     public function test_get_guest_role() {
96         global $CFG;
98         $guest = get_guest_role();
99         $this->assertEquals('guest', $guest->archetype);
100         $this->assertEquals('guest', $guest->shortname);
102         $this->assertEquals($CFG->guestroleid, $guest->id);
103     }
105     /**
106      * Test if user is admin.
107      */
108     public function test_is_siteadmin() {
109         global $DB, $CFG;
111         $this->resetAfterTest();
113         $users = $DB->get_records('user');
115         foreach ($users as $user) {
116             $this->setUser(0);
117             if ($user->username === 'admin') {
118                 $this->assertTrue(is_siteadmin($user));
119                 $this->assertTrue(is_siteadmin($user->id));
120                 $this->setUser($user);
121                 $this->assertTrue(is_siteadmin());
122                 $this->assertTrue(is_siteadmin(null));
123             } else {
124                 $this->assertFalse(is_siteadmin($user));
125                 $this->assertFalse(is_siteadmin($user->id));
126                 $this->setUser($user);
127                 $this->assertFalse(is_siteadmin());
128                 $this->assertFalse(is_siteadmin(null));
129             }
130         }
132         // Change the site admin list and check that it still works with
133         // multiple admins. We do this with userids only (not real user
134         // accounts) because it makes the test simpler.
135         $before = $CFG->siteadmins;
136         set_config('siteadmins', '666,667,668');
137         $this->assertTrue(is_siteadmin(666));
138         $this->assertTrue(is_siteadmin(667));
139         $this->assertTrue(is_siteadmin(668));
140         $this->assertFalse(is_siteadmin(669));
141         set_config('siteadmins', '13');
142         $this->assertTrue(is_siteadmin(13));
143         $this->assertFalse(is_siteadmin(666));
144         set_config('siteadmins', $before);
145     }
147     /**
148      * Test if user is enrolled in a course
149      */
150     public function test_is_enrolled() {
151         global $DB;
153         $this->resetAfterTest();
155         // Generate data.
156         $user = $this->getDataGenerator()->create_user();
157         $course = $this->getDataGenerator()->create_course();
158         $coursecontext = context_course::instance($course->id);
159         $role = $DB->get_record('role', array('shortname'=>'student'));
161         // There should be a manual enrolment as part of the default install.
162         $plugin = enrol_get_plugin('manual');
163         $instance = $DB->get_record('enrol', array(
164             'courseid' => $course->id,
165             'enrol' => 'manual',
166         ));
167         $this->assertNotSame(false, $instance);
169         // Enrol the user in the course.
170         $plugin->enrol_user($instance, $user->id, $role->id);
172         // We'll test with the mod/assign:submit capability.
173         $capability= 'mod/assign:submit';
174         $this->assertTrue($DB->record_exists('capabilities', array('name' => $capability)));
176         // Switch to our user.
177         $this->setUser($user);
179         // Ensure that the user has the capability first.
180         $this->assertTrue(has_capability($capability, $coursecontext, $user->id));
182         // We first test whether the user is enrolled on the course as this
183         // seeds the cache, then we test for the capability.
184         $this->assertTrue(is_enrolled($coursecontext, $user, '', true));
185         $this->assertTrue(is_enrolled($coursecontext, $user, $capability));
187         // Prevent the capability for this user role.
188         assign_capability($capability, CAP_PROHIBIT, $role->id, $coursecontext);
189         $coursecontext->mark_dirty();
190         $this->assertFalse(has_capability($capability, $coursecontext, $user->id));
192         // Again, we seed the cache first by checking initial enrolment,
193         // and then we test the actual capability.
194         $this->assertTrue(is_enrolled($coursecontext, $user, '', true));
195         $this->assertFalse(is_enrolled($coursecontext, $user, $capability));
196     }
198     /**
199      * Test logged in test.
200      */
201     public function test_isloggedin() {
202         global $USER;
204         $this->resetAfterTest();
206         $USER->id = 0;
207         $this->assertFalse(isloggedin());
208         $USER->id = 1;
209         $this->assertTrue(isloggedin());
210     }
212     /**
213      * Test guest user test.
214      */
215     public function test_isguestuser() {
216         global $DB;
218         $this->resetAfterTest();
220         $guest = $DB->get_record('user', array('username'=>'guest'));
221         $this->setUser(0);
222         $this->assertFalse(isguestuser());
223         $this->setAdminUser();
224         $this->assertFalse(isguestuser());
225         $this->assertTrue(isguestuser($guest));
226         $this->assertTrue(isguestuser($guest->id));
227         $this->setUser($guest);
228         $this->assertTrue(isguestuser());
230         $users = $DB->get_records('user');
231         foreach ($users as $user) {
232             if ($user->username === 'guest') {
233                 continue;
234             }
235             $this->assertFalse(isguestuser($user));
236         }
237     }
239     /**
240      * Test capability riskiness.
241      */
242     public function test_is_safe_capability() {
243         global $DB;
244         // Note: there is not much to test, just make sure no notices are throw for the most dangerous cap.
245         $capability = $DB->get_record('capabilities', array('name'=>'moodle/site:config'), '*', MUST_EXIST);
246         $this->assertFalse(is_safe_capability($capability));
247     }
249     /**
250      * Test context fetching.
251      */
252     public function test_get_context_info_array() {
253         $this->resetAfterTest();
255         $syscontext = context_system::instance();
256         $user = $this->getDataGenerator()->create_user();
257         $usercontext = context_user::instance($user->id);
258         $course = $this->getDataGenerator()->create_course();
259         $catcontext = context_coursecat::instance($course->category);
260         $coursecontext = context_course::instance($course->id);
261         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
262         $modcontext = context_module::instance($page->cmid);
263         $cm = get_coursemodule_from_instance('page', $page->id);
264         $block1 = $this->getDataGenerator()->create_block('online_users', array('parentcontextid'=>$coursecontext->id));
265         $block1context = context_block::instance($block1->id);
266         $block2 = $this->getDataGenerator()->create_block('online_users', array('parentcontextid'=>$modcontext->id));
267         $block2context = context_block::instance($block2->id);
269         $result = get_context_info_array($syscontext->id);
270         $this->assertCount(3, $result);
271         $this->assertEquals($syscontext, $result[0]);
272         $this->assertNull($result[1]);
273         $this->assertNull($result[2]);
275         $result = get_context_info_array($usercontext->id);
276         $this->assertCount(3, $result);
277         $this->assertEquals($usercontext, $result[0]);
278         $this->assertNull($result[1]);
279         $this->assertNull($result[2]);
281         $result = get_context_info_array($catcontext->id);
282         $this->assertCount(3, $result);
283         $this->assertEquals($catcontext, $result[0]);
284         $this->assertNull($result[1]);
285         $this->assertNull($result[2]);
287         $result = get_context_info_array($coursecontext->id);
288         $this->assertCount(3, $result);
289         $this->assertEquals($coursecontext, $result[0]);
290         $this->assertEquals($course->id, $result[1]->id);
291         $this->assertSame($course->shortname, $result[1]->shortname);
292         $this->assertNull($result[2]);
294         $result = get_context_info_array($block1context->id);
295         $this->assertCount(3, $result);
296         $this->assertEquals($block1context, $result[0]);
297         $this->assertEquals($course->id, $result[1]->id);
298         $this->assertEquals($course->shortname, $result[1]->shortname);
299         $this->assertNull($result[2]);
301         $result = get_context_info_array($modcontext->id);
302         $this->assertCount(3, $result);
303         $this->assertEquals($modcontext, $result[0]);
304         $this->assertEquals($course->id, $result[1]->id);
305         $this->assertSame($course->shortname, $result[1]->shortname);
306         $this->assertEquals($cm->id, $result[2]->id);
307         $this->assertEquals($cm->groupmembersonly, $result[2]->groupmembersonly);
309         $result = get_context_info_array($block2context->id);
310         $this->assertCount(3, $result);
311         $this->assertEquals($block2context, $result[0]);
312         $this->assertEquals($course->id, $result[1]->id);
313         $this->assertSame($course->shortname, $result[1]->shortname);
314         $this->assertEquals($cm->id, $result[2]->id);
315         $this->assertEquals($cm->groupmembersonly, $result[2]->groupmembersonly);
316     }
318     /**
319      * Test looking for course contacts.
320      */
321     public function test_has_coursecontact_role() {
322         global $DB, $CFG;
324         $this->resetAfterTest();
326         $users = $DB->get_records('user');
328         // Nobody is expected to have any course level roles.
329         $this->assertNotEmpty($CFG->coursecontact);
330         foreach ($users as $user) {
331             $this->assertFalse(has_coursecontact_role($user->id));
332         }
334         $user = $this->getDataGenerator()->create_user();
335         $course = $this->getDataGenerator()->create_course();
336         role_assign($CFG->coursecontact, $user->id, context_course::instance($course->id));
337         $this->assertTrue(has_coursecontact_role($user->id));
338     }
340     /**
341      * Test creation of roles.
342      */
343     public function test_create_role() {
344         global $DB;
346         $this->resetAfterTest();
348         $id = create_role('New student role', 'student2', 'New student description', 'student');
349         $role = $DB->get_record('role', array('id'=>$id));
351         $this->assertNotEmpty($role);
352         $this->assertSame('New student role', $role->name);
353         $this->assertSame('student2', $role->shortname);
354         $this->assertSame('New student description', $role->description);
355         $this->assertSame('student', $role->archetype);
356     }
358     /**
359      * Test adding of capabilities to roles.
360      */
361     public function test_assign_capability() {
362         global $DB;
364         $this->resetAfterTest();
366         $user = $this->getDataGenerator()->create_user();
367         $syscontext = context_system::instance();
368         $frontcontext = context_course::instance(SITEID);
369         $student = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST);
370         $this->assertTrue($DB->record_exists('capabilities', array('name'=>'moodle/backup:backupcourse'))); // Any capability assigned to student by default.
371         $this->assertFalse($DB->record_exists('role_capabilities', array('contextid'=>$syscontext->id, 'roleid'=>$student->id, 'capability'=>'moodle/backup:backupcourse')));
372         $this->assertFalse($DB->record_exists('role_capabilities', array('contextid'=>$frontcontext->id, 'roleid'=>$student->id, 'capability'=>'moodle/backup:backupcourse')));
374         $this->setUser($user);
375         $result = assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $student->id, $frontcontext->id);
376         $this->assertTrue($result);
377         $permission = $DB->get_record('role_capabilities', array('contextid'=>$frontcontext->id, 'roleid'=>$student->id, 'capability'=>'moodle/backup:backupcourse'));
378         $this->assertNotEmpty($permission);
379         $this->assertEquals(CAP_ALLOW, $permission->permission);
380         $this->assertEquals($user->id, $permission->modifierid);
382         $this->setUser(0);
383         $result = assign_capability('moodle/backup:backupcourse', CAP_PROHIBIT, $student->id, $frontcontext->id, false);
384         $this->assertTrue($result);
385         $permission = $DB->get_record('role_capabilities', array('contextid'=>$frontcontext->id, 'roleid'=>$student->id, 'capability'=>'moodle/backup:backupcourse'));
386         $this->assertNotEmpty($permission);
387         $this->assertEquals(CAP_ALLOW, $permission->permission);
388         $this->assertEquals(3, $permission->modifierid);
390         $result = assign_capability('moodle/backup:backupcourse', CAP_PROHIBIT, $student->id, $frontcontext->id, true);
391         $this->assertTrue($result);
392         $permission = $DB->get_record('role_capabilities', array('contextid'=>$frontcontext->id, 'roleid'=>$student->id, 'capability'=>'moodle/backup:backupcourse'));
393         $this->assertNotEmpty($permission);
394         $this->assertEquals(CAP_PROHIBIT, $permission->permission);
395         $this->assertEquals(0, $permission->modifierid);
397         $result = assign_capability('moodle/backup:backupcourse', CAP_INHERIT, $student->id, $frontcontext->id);
398         $this->assertTrue($result);
399         $permission = $DB->get_record('role_capabilities', array('contextid'=>$frontcontext->id, 'roleid'=>$student->id, 'capability'=>'moodle/backup:backupcourse'));
400         $this->assertEmpty($permission);
402         // Test event trigger.
403         $rolecapabilityevent = \core\event\role_capabilities_updated::create(array('context' => $syscontext,
404                                                                                   'objectid' => $student->id,
405                                                                                   'other' => array('name' => $student->shortname)
406                                                                                  ));
407         $expectedlegacylog = array(SITEID, 'role', 'view', 'admin/roles/define.php?action=view&roleid=' . $student->id,
408                             $student->shortname, '', $user->id);
409         $rolecapabilityevent->set_legacy_logdata($expectedlegacylog);
410         $rolecapabilityevent->add_record_snapshot('role', $student);
412         $sink = $this->redirectEvents();
413         $rolecapabilityevent->trigger();
414         $events = $sink->get_events();
415         $sink->close();
416         $event = array_pop($events);
418         $this->assertInstanceOf('\core\event\role_capabilities_updated', $event);
419         $expectedurl = new moodle_url('admin/roles/define.php', array('action' => 'view', 'roleid' => $student->id));
420         $this->assertEquals($expectedurl, $event->get_url());
421         $this->assertEventLegacyLogData($expectedlegacylog, $event);
422     }
424     /**
425      * Test removing of capabilities from roles.
426      */
427     public function test_unassign_capability() {
428         global $DB;
430         $this->resetAfterTest();
432         $syscontext = context_system::instance();
433         $frontcontext = context_course::instance(SITEID);
434         $manager = $DB->get_record('role', array('shortname'=>'manager'), '*', MUST_EXIST);
435         $this->assertTrue($DB->record_exists('capabilities', array('name'=>'moodle/backup:backupcourse'))); // Any capability assigned to manager by default.
436         assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $manager->id, $frontcontext->id);
438         $this->assertTrue($DB->record_exists('role_capabilities', array('contextid'=>$syscontext->id, 'roleid'=>$manager->id, 'capability'=>'moodle/backup:backupcourse')));
439         $this->assertTrue($DB->record_exists('role_capabilities', array('contextid'=>$frontcontext->id, 'roleid'=>$manager->id, 'capability'=>'moodle/backup:backupcourse')));
441         $result = unassign_capability('moodle/backup:backupcourse', $manager->id, $syscontext->id);
442         $this->assertTrue($result);
443         $this->assertFalse($DB->record_exists('role_capabilities', array('contextid'=>$syscontext->id, 'roleid'=>$manager->id, 'capability'=>'moodle/backup:backupcourse')));
444         $this->assertTrue($DB->record_exists('role_capabilities', array('contextid'=>$frontcontext->id, 'roleid'=>$manager->id, 'capability'=>'moodle/backup:backupcourse')));
445         unassign_capability('moodle/backup:backupcourse', $manager->id, $frontcontext);
446         $this->assertFalse($DB->record_exists('role_capabilities', array('contextid'=>$frontcontext->id, 'roleid'=>$manager->id, 'capability'=>'moodle/backup:backupcourse')));
448         assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $manager->id, $syscontext->id);
449         assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $manager->id, $frontcontext->id);
450         $this->assertTrue($DB->record_exists('role_capabilities', array('contextid'=>$frontcontext->id, 'roleid'=>$manager->id, 'capability'=>'moodle/backup:backupcourse')));
452         $result = unassign_capability('moodle/backup:backupcourse', $manager->id);
453         $this->assertTrue($result);
454         $this->assertFalse($DB->record_exists('role_capabilities', array('contextid'=>$syscontext->id, 'roleid'=>$manager->id, 'capability'=>'moodle/backup:backupcourse')));
455         $this->assertFalse($DB->record_exists('role_capabilities', array('contextid'=>$frontcontext->id, 'roleid'=>$manager->id, 'capability'=>'moodle/backup:backupcourse')));
456     }
458     /**
459      * Test role assigning.
460      */
461     public function test_role_assign() {
462         global $DB, $USER;
464         $this->resetAfterTest();
466         $user = $this->getDataGenerator()->create_user();
467         $course = $this->getDataGenerator()->create_course();
468         $role = $DB->get_record('role', array('shortname'=>'student'));
470         $this->setUser(0);
471         $context = context_system::instance();
472         $this->assertFalse($DB->record_exists('role_assignments', array('userid'=>$user->id, 'roleid'=>$role->id, 'contextid'=>$context->id)));
473         role_assign($role->id, $user->id, $context->id);
474         $ras = $DB->get_record('role_assignments', array('userid'=>$user->id, 'roleid'=>$role->id, 'contextid'=>$context->id));
475         $this->assertNotEmpty($ras);
476         $this->assertSame('', $ras->component);
477         $this->assertSame('0', $ras->itemid);
478         $this->assertEquals($USER->id, $ras->modifierid);
480         $this->setAdminUser();
481         $context = context_course::instance($course->id);
482         $this->assertFalse($DB->record_exists('role_assignments', array('userid'=>$user->id, 'roleid'=>$role->id, 'contextid'=>$context->id)));
483         role_assign($role->id, $user->id, $context->id, 'enrol_self', 1, 666);
484         $ras = $DB->get_record('role_assignments', array('userid'=>$user->id, 'roleid'=>$role->id, 'contextid'=>$context->id));
485         $this->assertNotEmpty($ras);
486         $this->assertSame('enrol_self', $ras->component);
487         $this->assertSame('1', $ras->itemid);
488         $this->assertEquals($USER->id, $ras->modifierid);
489         $this->assertEquals(666, $ras->timemodified);
491         // Test event triggered.
493         $user2 = $this->getDataGenerator()->create_user();
494         $sink = $this->redirectEvents();
495         $raid = role_assign($role->id, $user2->id, $context->id);
496         $events = $sink->get_events();
497         $sink->close();
498         $this->assertCount(1, $events);
499         $event = $events[0];
500         $this->assertInstanceOf('\core\event\role_assigned', $event);
501         $this->assertSame('role', $event->target);
502         $this->assertSame('role', $event->objecttable);
503         $this->assertEquals($role->id, $event->objectid);
504         $this->assertEquals($context->id, $event->contextid);
505         $this->assertEquals($user2->id, $event->relateduserid);
506         $this->assertCount(3, $event->other);
507         $this->assertEquals($raid, $event->other['id']);
508         $this->assertSame('', $event->other['component']);
509         $this->assertEquals(0, $event->other['itemid']);
510         $this->assertSame('role_assigned', $event::get_legacy_eventname());
511         $roles = get_all_roles();
512         $rolenames = role_fix_names($roles, $context, ROLENAME_ORIGINAL, true);
513         $expectedlegacylog = array($course->id, 'role', 'assign',
514             'admin/roles/assign.php?contextid='.$context->id.'&roleid='.$role->id, $rolenames[$role->id], '', $USER->id);
515         $this->assertEventLegacyLogData($expectedlegacylog, $event);
516     }
518     /**
519      * Test role unassigning.
520      */
521     public function test_role_unassign() {
522         global $DB, $USER;
524         $this->resetAfterTest();
526         $user = $this->getDataGenerator()->create_user();
527         $course = $this->getDataGenerator()->create_course();
528         $role = $DB->get_record('role', array('shortname'=>'student'));
530         $context = context_course::instance($course->id);
531         role_assign($role->id, $user->id, $context->id);
532         $this->assertTrue($DB->record_exists('role_assignments', array('userid'=>$user->id, 'roleid'=>$role->id, 'contextid'=>$context->id)));
533         role_unassign($role->id, $user->id, $context->id);
534         $this->assertFalse($DB->record_exists('role_assignments', array('userid'=>$user->id, 'roleid'=>$role->id, 'contextid'=>$context->id)));
536         role_assign($role->id, $user->id, $context->id, 'enrol_self', 1);
537         $this->assertTrue($DB->record_exists('role_assignments', array('userid'=>$user->id, 'roleid'=>$role->id, 'contextid'=>$context->id)));
538         role_unassign($role->id, $user->id, $context->id, 'enrol_self', 1);
539         $this->assertFalse($DB->record_exists('role_assignments', array('userid'=>$user->id, 'roleid'=>$role->id, 'contextid'=>$context->id)));
541         // Test event triggered.
543         role_assign($role->id, $user->id, $context->id);
544         $sink = $this->redirectEvents();
545         role_unassign($role->id, $user->id, $context->id);
546         $events = $sink->get_events();
547         $sink->close();
548         $this->assertCount(1, $events);
549         $event = $events[0];
550         $this->assertInstanceOf('\core\event\role_unassigned', $event);
551         $this->assertSame('role', $event->target);
552         $this->assertSame('role', $event->objecttable);
553         $this->assertEquals($role->id, $event->objectid);
554         $this->assertEquals($context->id, $event->contextid);
555         $this->assertEquals($user->id, $event->relateduserid);
556         $this->assertCount(3, $event->other);
557         $this->assertSame('', $event->other['component']);
558         $this->assertEquals(0, $event->other['itemid']);
559         $roles = get_all_roles();
560         $rolenames = role_fix_names($roles, $context, ROLENAME_ORIGINAL, true);
561         $expectedlegacylog = array($course->id, 'role', 'unassign',
562             'admin/roles/assign.php?contextid='.$context->id.'&roleid='.$role->id, $rolenames[$role->id], '', $USER->id);
563         $this->assertEventLegacyLogData($expectedlegacylog, $event);
564     }
566     /**
567      * Test role unassigning.
568      */
569     public function test_role_unassign_all() {
570         global $DB;
572         $this->resetAfterTest();
574         $user = $this->getDataGenerator()->create_user();
575         $course = $this->getDataGenerator()->create_course();
576         $role = $DB->get_record('role', array('shortname'=>'student'));
577         $role2 = $DB->get_record('role', array('shortname'=>'teacher'));
578         $syscontext = context_system::instance();
579         $coursecontext = context_course::instance($course->id);
580         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
581         $modcontext = context_module::instance($page->cmid);
583         role_assign($role->id, $user->id, $syscontext->id);
584         role_assign($role->id, $user->id, $coursecontext->id, 'enrol_self', 1);
585         $this->assertEquals(2, $DB->count_records('role_assignments', array('userid'=>$user->id)));
586         role_unassign_all(array('userid'=>$user->id, 'roleid'=>$role->id));
587         $this->assertEquals(0, $DB->count_records('role_assignments', array('userid'=>$user->id)));
589         role_assign($role->id, $user->id, $syscontext->id);
590         role_assign($role->id, $user->id, $coursecontext->id, 'enrol_self', 1);
591         role_assign($role->id, $user->id, $modcontext->id);
592         $this->assertEquals(3, $DB->count_records('role_assignments', array('userid'=>$user->id)));
593         role_unassign_all(array('userid'=>$user->id, 'contextid'=>$coursecontext->id), false);
594         $this->assertEquals(2, $DB->count_records('role_assignments', array('userid'=>$user->id)));
595         role_unassign_all(array('userid'=>$user->id, 'contextid'=>$coursecontext->id), true);
596         $this->assertEquals(1, $DB->count_records('role_assignments', array('userid'=>$user->id)));
597         role_unassign_all(array('userid'=>$user->id));
598         $this->assertEquals(0, $DB->count_records('role_assignments', array('userid'=>$user->id)));
600         role_assign($role->id, $user->id, $syscontext->id);
601         role_assign($role->id, $user->id, $coursecontext->id, 'enrol_self', 1);
602         role_assign($role->id, $user->id, $coursecontext->id);
603         role_assign($role->id, $user->id, $modcontext->id);
604         $this->assertEquals(4, $DB->count_records('role_assignments', array('userid'=>$user->id)));
605         role_unassign_all(array('userid'=>$user->id, 'contextid'=>$coursecontext->id, 'component'=>'enrol_self'), true, true);
606         $this->assertEquals(1, $DB->count_records('role_assignments', array('userid'=>$user->id)));
608         // Test events triggered.
610         role_assign($role2->id, $user->id, $coursecontext->id);
611         role_assign($role2->id, $user->id, $modcontext->id);
612         $sink = $this->redirectEvents();
613         role_unassign_all(array('userid'=>$user->id, 'roleid'=>$role2->id));
614         $events = $sink->get_events();
615         $sink->close();
616         $this->assertCount(2, $events);
617         $this->assertInstanceOf('\core\event\role_unassigned', $events[0]);
618         $this->assertInstanceOf('\core\event\role_unassigned', $events[1]);
619     }
621     /**
622      * Test role queries.
623      */
624     public function test_get_roles_with_capability() {
625         global $DB;
627         $this->resetAfterTest();
629         $syscontext = context_system::instance();
630         $frontcontext = context_course::instance(SITEID);
631         $manager = $DB->get_record('role', array('shortname'=>'manager'), '*', MUST_EXIST);
632         $teacher = $DB->get_record('role', array('shortname'=>'teacher'), '*', MUST_EXIST);
634         $this->assertTrue($DB->record_exists('capabilities', array('name'=>'moodle/backup:backupcourse'))); // Any capability is ok.
635         $DB->delete_records('role_capabilities', array('capability'=>'moodle/backup:backupcourse'));
637         $roles = get_roles_with_capability('moodle/backup:backupcourse');
638         $this->assertEquals(array(), $roles);
640         assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $manager->id, $syscontext->id);
641         assign_capability('moodle/backup:backupcourse', CAP_PROHIBIT, $manager->id, $frontcontext->id);
642         assign_capability('moodle/backup:backupcourse', CAP_PREVENT, $teacher->id, $frontcontext->id);
644         $roles = get_roles_with_capability('moodle/backup:backupcourse');
645         $this->assertEquals(array($teacher->id, $manager->id), array_keys($roles), '', 0, 10, true);
647         $roles = get_roles_with_capability('moodle/backup:backupcourse', CAP_ALLOW);
648         $this->assertEquals(array($manager->id), array_keys($roles), '', 0, 10, true);
650         $roles = get_roles_with_capability('moodle/backup:backupcourse', null, $syscontext);
651         $this->assertEquals(array($manager->id), array_keys($roles), '', 0, 10, true);
652     }
654     /**
655      * Test deleting of roles.
656      */
657     public function test_delete_role() {
658         global $DB;
660         $this->resetAfterTest();
662         $role = $DB->get_record('role', array('shortname'=>'manager'), '*', MUST_EXIST);
663         $user = $this->getDataGenerator()->create_user();
664         role_assign($role->id, $user->id, context_system::instance());
665         $course = $this->getDataGenerator()->create_course();
666         $rolename = (object)array('roleid'=>$role->id, 'name'=>'Man', 'contextid'=>context_course::instance($course->id)->id);
667         $DB->insert_record('role_names', $rolename);
669         $this->assertTrue($DB->record_exists('role_assignments', array('roleid'=>$role->id)));
670         $this->assertTrue($DB->record_exists('role_capabilities', array('roleid'=>$role->id)));
671         $this->assertTrue($DB->record_exists('role_names', array('roleid'=>$role->id)));
672         $this->assertTrue($DB->record_exists('role_context_levels', array('roleid'=>$role->id)));
673         $this->assertTrue($DB->record_exists('role_allow_assign', array('roleid'=>$role->id)));
674         $this->assertTrue($DB->record_exists('role_allow_assign', array('allowassign'=>$role->id)));
675         $this->assertTrue($DB->record_exists('role_allow_override', array('roleid'=>$role->id)));
676         $this->assertTrue($DB->record_exists('role_allow_override', array('allowoverride'=>$role->id)));
678         // Delete role and get event.
679         $sink = $this->redirectEvents();
680         $result = delete_role($role->id);
681         $events = $sink->get_events();
682         $sink->close();
683         $event = array_pop($events);
685         $this->assertTrue($result);
686         $this->assertFalse($DB->record_exists('role', array('id'=>$role->id)));
687         $this->assertFalse($DB->record_exists('role_assignments', array('roleid'=>$role->id)));
688         $this->assertFalse($DB->record_exists('role_capabilities', array('roleid'=>$role->id)));
689         $this->assertFalse($DB->record_exists('role_names', array('roleid'=>$role->id)));
690         $this->assertFalse($DB->record_exists('role_context_levels', array('roleid'=>$role->id)));
691         $this->assertFalse($DB->record_exists('role_allow_assign', array('roleid'=>$role->id)));
692         $this->assertFalse($DB->record_exists('role_allow_assign', array('allowassign'=>$role->id)));
693         $this->assertFalse($DB->record_exists('role_allow_override', array('roleid'=>$role->id)));
694         $this->assertFalse($DB->record_exists('role_allow_override', array('allowoverride'=>$role->id)));
696         // Test triggered event.
697         $this->assertInstanceOf('\core\event\role_deleted', $event);
698         $this->assertSame('role', $event->target);
699         $this->assertSame('role', $event->objecttable);
700         $this->assertSame($role->id, $event->objectid);
701         $this->assertEquals(context_system::instance(), $event->get_context());
702         $this->assertSame($role->shortname, $event->other['shortname']);
703         $this->assertSame($role->description, $event->other['description']);
704         $this->assertSame($role->archetype, $event->other['archetype']);
706         $expectedlegacylog = array(SITEID, 'role', 'delete', 'admin/roles/manage.php?action=delete&roleid='.$role->id,
707                                    $role->shortname, '');
708         $this->assertEventLegacyLogData($expectedlegacylog, $event);
709     }
711     /**
712      * Test fetching of all roles.
713      */
714     public function test_get_all_roles() {
715         global $DB;
717         $this->resetAfterTest();
719         $allroles = get_all_roles();
720         $this->assertInternalType('array', $allroles);
721         $this->assertCount(8, $allroles); // There are 8 roles is standard install.
723         $role = reset($allroles);
724         $role = (array)$role;
726         $this->assertEquals(array('id', 'name', 'shortname', 'description', 'sortorder', 'archetype'), array_keys($role), '', 0, 10, true);
728         foreach ($allroles as $roleid => $role) {
729             $this->assertEquals($role->id, $roleid);
730         }
732         $teacher = $DB->get_record('role', array('shortname'=>'teacher'), '*', MUST_EXIST);
733         $course = $this->getDataGenerator()->create_course();
734         $coursecontext = context_course::instance($course->id);
735         $otherid = create_role('Other role', 'other', 'Some other role', '');
736         $teacherename = (object)array('roleid'=>$teacher->id, 'name'=>'Učitel', 'contextid'=>$coursecontext->id);
737         $DB->insert_record('role_names', $teacherename);
738         $otherrename = (object)array('roleid'=>$otherid, 'name'=>'Ostatní', 'contextid'=>$coursecontext->id);
739         $DB->insert_record('role_names', $otherrename);
740         $renames = $DB->get_records_menu('role_names', array('contextid'=>$coursecontext->id), '', 'roleid, name');
742         $allroles = get_all_roles($coursecontext);
743         $this->assertInternalType('array', $allroles);
744         $this->assertCount(9, $allroles);
745         $role = reset($allroles);
746         $role = (array)$role;
748         $this->assertEquals(array('id', 'name', 'shortname', 'description', 'sortorder', 'archetype', 'coursealias'), array_keys($role), '', 0, 10, true);
750         foreach ($allroles as $roleid => $role) {
751             $this->assertEquals($role->id, $roleid);
752             if (isset($renames[$roleid])) {
753                 $this->assertSame($renames[$roleid], $role->coursealias);
754             } else {
755                 $this->assertNull($role->coursealias);
756             }
757         }
758     }
760     /**
761      * Test getting of all archetypes.
762      */
763     public function test_get_role_archetypes() {
764         $archetypes = get_role_archetypes();
765         $this->assertCount(8, $archetypes); // There are 8 archetypes in standard install.
766         foreach ($archetypes as $k => $v) {
767             $this->assertSame($k, $v);
768         }
769     }
771     /**
772      * Test getting of roles with given archetype.
773      */
774     public function test_get_archetype_roles() {
775         $this->resetAfterTest();
777         // New install should have 1 role for each archetype.
778         $archetypes = get_role_archetypes();
779         foreach ($archetypes as $archetype) {
780             $roles = get_archetype_roles($archetype);
781             $this->assertCount(1, $roles);
782             $role = reset($roles);
783             $this->assertSame($archetype, $role->archetype);
784         }
786         create_role('New student role', 'student2', 'New student description', 'student');
787         $roles = get_archetype_roles('student');
788         $this->assertCount(2, $roles);
789     }
791     /**
792      * Test aliased role names.
793      */
794     public function test_role_get_name() {
795         global $DB;
797         $this->resetAfterTest();
799         $allroles = $DB->get_records('role');
800         $teacher = $DB->get_record('role', array('shortname'=>'teacher'), '*', MUST_EXIST);
801         $course = $this->getDataGenerator()->create_course();
802         $coursecontext = context_course::instance($course->id);
803         $otherid = create_role('Other role', 'other', 'Some other role', '');
804         $teacherename = (object)array('roleid'=>$teacher->id, 'name'=>'Učitel', 'contextid'=>$coursecontext->id);
805         $DB->insert_record('role_names', $teacherename);
806         $otherrename = (object)array('roleid'=>$otherid, 'name'=>'Ostatní', 'contextid'=>$coursecontext->id);
807         $DB->insert_record('role_names', $otherrename);
808         $renames = $DB->get_records_menu('role_names', array('contextid'=>$coursecontext->id), '', 'roleid, name');
810         foreach ($allroles as $role) {
811             // Get localised name from lang pack.
812             $this->assertSame('', $role->name);
813             $name = role_get_name($role, null, ROLENAME_ORIGINAL);
814             $this->assertNotEmpty($name);
815             $this->assertNotEquals($role->shortname, $name);
817             if (isset($renames[$role->id])) {
818                 $this->assertSame($renames[$role->id], role_get_name($role, $coursecontext));
819                 $this->assertSame($renames[$role->id], role_get_name($role, $coursecontext, ROLENAME_ALIAS));
820                 $this->assertSame($renames[$role->id], role_get_name($role, $coursecontext, ROLENAME_ALIAS_RAW));
821                 $this->assertSame("{$renames[$role->id]} ($name)", role_get_name($role, $coursecontext, ROLENAME_BOTH));
822             } else {
823                 $this->assertSame($name, role_get_name($role, $coursecontext));
824                 $this->assertSame($name, role_get_name($role, $coursecontext, ROLENAME_ALIAS));
825                 $this->assertNull(role_get_name($role, $coursecontext, ROLENAME_ALIAS_RAW));
826                 $this->assertSame($name, role_get_name($role, $coursecontext, ROLENAME_BOTH));
827             }
828             $this->assertSame($name, role_get_name($role));
829             $this->assertSame($name, role_get_name($role, $coursecontext, ROLENAME_ORIGINAL));
830             $this->assertSame($name, role_get_name($role, null, ROLENAME_ORIGINAL));
831             $this->assertSame($role->shortname, role_get_name($role, $coursecontext, ROLENAME_SHORT));
832             $this->assertSame($role->shortname, role_get_name($role, null, ROLENAME_SHORT));
833             $this->assertSame("$name ($role->shortname)", role_get_name($role, $coursecontext, ROLENAME_ORIGINALANDSHORT));
834             $this->assertSame("$name ($role->shortname)", role_get_name($role, null, ROLENAME_ORIGINALANDSHORT));
835             $this->assertNull(role_get_name($role, null, ROLENAME_ALIAS_RAW));
836         }
837     }
839     /**
840      * Test tweaking of role name arrays.
841      */
842     public function test_role_fix_names() {
843         global $DB;
845         $this->resetAfterTest();
847         $teacher = $DB->get_record('role', array('shortname'=>'teacher'), '*', MUST_EXIST);
848         $student = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST);
849         $otherid = create_role('Other role', 'other', 'Some other role', '');
850         $anotherid = create_role('Another role', 'another', 'Yet another other role', '');
851         $allroles = $DB->get_records('role');
853         $syscontext = context_system::instance();
854         $frontcontext = context_course::instance(SITEID);
855         $course = $this->getDataGenerator()->create_course();
856         $coursecontext = context_course::instance($course->id);
857         $category = $DB->get_record('course_categories', array('id'=>$course->category), '*', MUST_EXIST);
858         $categorycontext = context_coursecat::instance($category->id);
860         $teacherename = (object)array('roleid'=>$teacher->id, 'name'=>'Učitel', 'contextid'=>$coursecontext->id);
861         $DB->insert_record('role_names', $teacherename);
862         $otherrename = (object)array('roleid'=>$otherid, 'name'=>'Ostatní', 'contextid'=>$coursecontext->id);
863         $DB->insert_record('role_names', $otherrename);
864         $renames = $DB->get_records_menu('role_names', array('contextid'=>$coursecontext->id), '', 'roleid, name');
866         // Make sure all localname contain proper values for each ROLENAME_ constant,
867         // note role_get_name() on frontpage is used to get the original name for future compatibility.
868         $roles = $allroles;
869         unset($roles[$student->id]); // Remove one role to make sure no role is added or removed.
870         $rolenames = array();
871         foreach ($roles as $role) {
872             $rolenames[$role->id] = $role->name;
873         }
875         $alltypes = array(ROLENAME_ALIAS, ROLENAME_ALIAS_RAW, ROLENAME_BOTH, ROLENAME_ORIGINAL, ROLENAME_ORIGINALANDSHORT, ROLENAME_SHORT);
876         foreach ($alltypes as $type) {
877             $fixed = role_fix_names($roles, $coursecontext, $type);
878             $this->assertCount(count($roles), $fixed);
879             foreach ($fixed as $roleid => $rolename) {
880                 $this->assertInstanceOf('stdClass', $rolename);
881                 $role = $allroles[$roleid];
882                 $name = role_get_name($role, $coursecontext, $type);
883                 $this->assertSame($name, $rolename->localname);
884             }
885             $fixed = role_fix_names($rolenames, $coursecontext, $type);
886             $this->assertCount(count($rolenames), $fixed);
887             foreach ($fixed as $roleid => $rolename) {
888                 $role = $allroles[$roleid];
889                 $name = role_get_name($role, $coursecontext, $type);
890                 $this->assertSame($name, $rolename);
891             }
892         }
893     }
895     /**
896      * Test role default allows.
897      */
898     public function test_get_default_role_archetype_allows() {
899         $archetypes = get_role_archetypes();
900         foreach ($archetypes as $archetype) {
902             $result = get_default_role_archetype_allows('assign', $archetype);
903             $this->assertInternalType('array', $result);
905             $result = get_default_role_archetype_allows('override', $archetype);
906             $this->assertInternalType('array', $result);
908             $result = get_default_role_archetype_allows('switch', $archetype);
909             $this->assertInternalType('array', $result);
910         }
912         $result = get_default_role_archetype_allows('assign', '');
913         $this->assertSame(array(), $result);
915         $result = get_default_role_archetype_allows('override', '');
916         $this->assertSame(array(), $result);
918         $result = get_default_role_archetype_allows('switch', '');
919         $this->assertSame(array(), $result);
921         $result = get_default_role_archetype_allows('assign', 'wrongarchetype');
922         $this->assertSame(array(), $result);
923         $this->assertDebuggingCalled();
925         $result = get_default_role_archetype_allows('override', 'wrongarchetype');
926         $this->assertSame(array(), $result);
927         $this->assertDebuggingCalled();
929         $result = get_default_role_archetype_allows('switch', 'wrongarchetype');
930         $this->assertSame(array(), $result);
931         $this->assertDebuggingCalled();
932     }
934     /**
935      * Test allowing of role assignments.
936      */
937     public function test_allow_assign() {
938         global $DB, $CFG;
940         $this->resetAfterTest();
942         $otherid = create_role('Other role', 'other', 'Some other role', '');
943         $student = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST);
945         $this->assertFalse($DB->record_exists('role_allow_assign', array('roleid'=>$otherid, 'allowassign'=>$student->id)));
946         allow_assign($otherid, $student->id);
947         $this->assertTrue($DB->record_exists('role_allow_assign', array('roleid'=>$otherid, 'allowassign'=>$student->id)));
949         // Test event trigger.
950         $allowroleassignevent = \core\event\role_allow_assign_updated::create(array('context' => context_system::instance()));
951         $sink = $this->redirectEvents();
952         $allowroleassignevent->trigger();
953         $events = $sink->get_events();
954         $sink->close();
955         $event = array_pop($events);
956         $this->assertInstanceOf('\core\event\role_allow_assign_updated', $event);
957         $mode = 'assign';
958         $baseurl = new moodle_url('/admin/roles/allow.php', array('mode' => $mode));
959         $expectedlegacylog = array(SITEID, 'role', 'edit allow ' . $mode, str_replace($CFG->wwwroot . '/', '', $baseurl));
960         $this->assertEventLegacyLogData($expectedlegacylog, $event);
961     }
963     /**
964      * Test allowing of role overrides.
965      */
966     public function test_allow_override() {
967         global $DB, $CFG;
969         $this->resetAfterTest();
971         $otherid = create_role('Other role', 'other', 'Some other role', '');
972         $student = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST);
974         $this->assertFalse($DB->record_exists('role_allow_override', array('roleid'=>$otherid, 'allowoverride'=>$student->id)));
975         allow_override($otherid, $student->id);
976         $this->assertTrue($DB->record_exists('role_allow_override', array('roleid'=>$otherid, 'allowoverride'=>$student->id)));
978         // Test event trigger.
979         $allowroleassignevent = \core\event\role_allow_override_updated::create(array('context' => context_system::instance()));
980         $sink = $this->redirectEvents();
981         $allowroleassignevent->trigger();
982         $events = $sink->get_events();
983         $sink->close();
984         $event = array_pop($events);
985         $this->assertInstanceOf('\core\event\role_allow_override_updated', $event);
986         $mode = 'override';
987         $baseurl = new moodle_url('/admin/roles/allow.php', array('mode' => $mode));
988         $expectedlegacylog = array(SITEID, 'role', 'edit allow ' . $mode, str_replace($CFG->wwwroot . '/', '', $baseurl));
989         $this->assertEventLegacyLogData($expectedlegacylog, $event);
990     }
992     /**
993      * Test allowing of role switching.
994      */
995     public function test_allow_switch() {
996         global $DB, $CFG;
998         $this->resetAfterTest();
1000         $otherid = create_role('Other role', 'other', 'Some other role', '');
1001         $student = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST);
1003         $this->assertFalse($DB->record_exists('role_allow_switch', array('roleid'=>$otherid, 'allowswitch'=>$student->id)));
1004         allow_switch($otherid, $student->id);
1005         $this->assertTrue($DB->record_exists('role_allow_switch', array('roleid'=>$otherid, 'allowswitch'=>$student->id)));
1007         // Test event trigger.
1008         $allowroleassignevent = \core\event\role_allow_switch_updated::create(array('context' => context_system::instance()));
1009         $sink = $this->redirectEvents();
1010         $allowroleassignevent->trigger();
1011         $events = $sink->get_events();
1012         $sink->close();
1013         $event = array_pop($events);
1014         $this->assertInstanceOf('\core\event\role_allow_switch_updated', $event);
1015         $mode = 'switch';
1016         $baseurl = new moodle_url('/admin/roles/allow.php', array('mode' => $mode));
1017         $expectedlegacylog = array(SITEID, 'role', 'edit allow ' . $mode, str_replace($CFG->wwwroot . '/', '', $baseurl));
1018         $this->assertEventLegacyLogData($expectedlegacylog, $event);
1019     }
1021     /**
1022      * Test returning of assignable roles in context.
1023      */
1024     public function test_get_assignable_roles() {
1025         global $DB;
1027         $this->resetAfterTest();
1029         $course = $this->getDataGenerator()->create_course();
1030         $coursecontext = context_course::instance($course->id);
1032         $teacherrole = $DB->get_record('role', array('shortname'=>'editingteacher'), '*', MUST_EXIST);
1033         $teacher = $this->getDataGenerator()->create_user();
1034         role_assign($teacherrole->id, $teacher->id, $coursecontext);
1035         $teacherename = (object)array('roleid'=>$teacher->id, 'name'=>'Učitel', 'contextid'=>$coursecontext->id);
1036         $DB->insert_record('role_names', $teacherename);
1038         $studentrole = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST);
1039         $student = $this->getDataGenerator()->create_user();
1040         role_assign($studentrole->id, $student->id, $coursecontext);
1042         $contexts = $DB->get_records('context');
1043         $users = $DB->get_records('user');
1044         $allroles = $DB->get_records('role');
1046         // Evaluate all results for all users in all contexts.
1047         foreach ($users as $user) {
1048             $this->setUser($user);
1049             foreach ($contexts as $contextid => $unused) {
1050                 $context = context_helper::instance_by_id($contextid);
1051                 $roles = get_assignable_roles($context, ROLENAME_SHORT);
1052                 foreach ($allroles as $roleid => $role) {
1053                     if (isset($roles[$roleid])) {
1054                         if (is_siteadmin()) {
1055                             $this->assertTrue($DB->record_exists('role_context_levels', array('contextlevel'=>$context->contextlevel, 'roleid'=>$roleid)));
1056                         } else {
1057                             $this->assertTrue(user_can_assign($context, $roleid), "u:$user->id r:$roleid");
1058                         }
1059                         $this->assertEquals($role->shortname, $roles[$roleid]);
1060                     } else {
1061                         $allowed = $DB->record_exists('role_context_levels', array('contextlevel'=>$context->contextlevel, 'roleid'=>$roleid));
1062                         if (is_siteadmin()) {
1063                             $this->assertFalse($allowed);
1064                         } else {
1065                             $this->assertFalse($allowed and user_can_assign($context, $roleid), "u:$user->id, r:{$allroles[$roleid]->name}, c:$context->contextlevel");
1066                         }
1067                     }
1068                 }
1069             }
1070         }
1072         // Not-logged-in user.
1073         $this->setUser(0);
1074         foreach ($contexts as $contextid => $unused) {
1075             $context = context_helper::instance_by_id($contextid);
1076             $roles = get_assignable_roles($context, ROLENAME_SHORT);
1077             $this->assertSame(array(), $roles);
1078         }
1080         // Test current user.
1081         $this->setUser(0);
1082         $admin = $DB->get_record('user', array('username'=>'admin'), '*', MUST_EXIST);
1083         $roles1 = get_assignable_roles($coursecontext, ROLENAME_SHORT, false, $admin);
1084         $roles2 = get_assignable_roles($coursecontext, ROLENAME_SHORT, false, $admin->id);
1085         $this->setAdminUser();
1086         $roles3 = get_assignable_roles($coursecontext, ROLENAME_SHORT);
1087         $this->assertSame($roles1, $roles3);
1088         $this->assertSame($roles2, $roles3);
1090         // Test parameter defaults.
1091         $this->setAdminUser();
1092         $roles1 = get_assignable_roles($coursecontext);
1093         $roles2 = get_assignable_roles($coursecontext, ROLENAME_ALIAS, false, $admin);
1094         $this->assertEquals($roles2, $roles1);
1096         // Verify returned names - let's allow all roles everywhere to simplify this a bit.
1097         $alllevels = context_helper::get_all_levels();
1098         $alllevels = array_keys($alllevels);
1099         foreach ($allroles as $roleid => $role) {
1100             set_role_contextlevels($roleid, $alllevels);
1101         }
1102         $alltypes = array(ROLENAME_ALIAS, ROLENAME_ALIAS_RAW, ROLENAME_BOTH, ROLENAME_ORIGINAL, ROLENAME_ORIGINALANDSHORT, ROLENAME_SHORT);
1103         foreach ($alltypes as $type) {
1104             $rolenames = role_fix_names($allroles, $coursecontext, $type);
1105             $roles = get_assignable_roles($coursecontext, $type, false, $admin);
1106             foreach ($roles as $roleid => $rolename) {
1107                 $this->assertSame($rolenames[$roleid]->localname, $rolename);
1108             }
1109         }
1111         // Verify counts.
1112         $alltypes = array(ROLENAME_ALIAS, ROLENAME_ALIAS_RAW, ROLENAME_BOTH, ROLENAME_ORIGINAL, ROLENAME_ORIGINALANDSHORT, ROLENAME_SHORT);
1113         foreach ($alltypes as $type) {
1114             $roles = get_assignable_roles($coursecontext, $type, false, $admin);
1115             list($rolenames, $rolecounts, $nameswithcounts) = get_assignable_roles($coursecontext, $type, true, $admin);
1116             $this->assertEquals($roles, $rolenames);
1117             foreach ($rolenames as $roleid => $name) {
1118                 if ($roleid == $teacherrole->id or $roleid == $studentrole->id) {
1119                     $this->assertEquals(1, $rolecounts[$roleid]);
1120                 } else {
1121                     $this->assertEquals(0, $rolecounts[$roleid]);
1122                 }
1123                 $this->assertSame("$name ($rolecounts[$roleid])", $nameswithcounts[$roleid]);
1124             }
1125         }
1126     }
1128     /**
1129      * Test getting of all switchable roles.
1130      */
1131     public function test_get_switchable_roles() {
1132         global $DB;
1134         $this->resetAfterTest();
1136         $course = $this->getDataGenerator()->create_course();
1137         $coursecontext = context_course::instance($course->id);
1139         $teacherrole = $DB->get_record('role', array('shortname'=>'editingteacher'), '*', MUST_EXIST);
1140         $teacher = $this->getDataGenerator()->create_user();
1141         role_assign($teacherrole->id, $teacher->id, $coursecontext);
1142         $teacherename = (object)array('roleid'=>$teacher->id, 'name'=>'Učitel', 'contextid'=>$coursecontext->id);
1143         $DB->insert_record('role_names', $teacherename);
1145         $contexts = $DB->get_records('context');
1146         $users = $DB->get_records('user');
1147         $allroles = $DB->get_records('role');
1149         // Evaluate all results for all users in all contexts.
1150         foreach ($users as $user) {
1151             $this->setUser($user);
1152             foreach ($contexts as $contextid => $unused) {
1153                 $context = context_helper::instance_by_id($contextid);
1154                 $roles = get_switchable_roles($context);
1155                 foreach ($allroles as $roleid => $role) {
1156                     if (is_siteadmin()) {
1157                         $this->assertTrue(isset($roles[$roleid]));
1158                     } else {
1159                         $parents = $context->get_parent_context_ids(true);
1160                         $pcontexts = implode(',' , $parents);
1161                         $allowed = $DB->record_exists_sql(
1162                             "SELECT r.id
1163                                FROM {role} r
1164                                JOIN {role_allow_switch} ras ON ras.allowswitch = r.id
1165                                JOIN {role_assignments} ra ON ra.roleid = ras.roleid
1166                               WHERE ra.userid = :userid AND ra.contextid IN ($pcontexts) AND r.id = :roleid
1167                             ",
1168                             array('userid'=>$user->id, 'roleid'=>$roleid)
1169                         );
1170                         if (isset($roles[$roleid])) {
1171                             $this->assertTrue($allowed);
1172                         } else {
1173                             $this->assertFalse($allowed);
1174                         }
1175                     }
1177                     if (isset($roles[$roleid])) {
1178                         $coursecontext = $context->get_course_context(false);
1179                         $this->assertSame(role_get_name($role, $coursecontext), $roles[$roleid]);
1180                     }
1181                 }
1182             }
1183         }
1184     }
1186     /**
1187      * Test getting of all overridable roles.
1188      */
1189     public function test_get_overridable_roles() {
1190         global $DB;
1192         $this->resetAfterTest();
1194         $course = $this->getDataGenerator()->create_course();
1195         $coursecontext = context_course::instance($course->id);
1197         $teacherrole = $DB->get_record('role', array('shortname'=>'editingteacher'), '*', MUST_EXIST);
1198         $teacher = $this->getDataGenerator()->create_user();
1199         role_assign($teacherrole->id, $teacher->id, $coursecontext);
1200         $teacherename = (object)array('roleid'=>$teacher->id, 'name'=>'Učitel', 'contextid'=>$coursecontext->id);
1201         $DB->insert_record('role_names', $teacherename);
1202         $this->assertTrue($DB->record_exists('capabilities', array('name'=>'moodle/backup:backupcourse'))); // Any capability is ok.
1203         assign_capability('moodle/backup:backupcourse', CAP_PROHIBIT, $teacher->id, $coursecontext->id);
1205         $studentrole = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST);
1206         $student = $this->getDataGenerator()->create_user();
1207         role_assign($studentrole->id, $student->id, $coursecontext);
1209         $contexts = $DB->get_records('context');
1210         $users = $DB->get_records('user');
1211         $allroles = $DB->get_records('role');
1213         // Evaluate all results for all users in all contexts.
1214         foreach ($users as $user) {
1215             $this->setUser($user);
1216             foreach ($contexts as $contextid => $unused) {
1217                 $context = context_helper::instance_by_id($contextid);
1218                 $roles = get_overridable_roles($context, ROLENAME_SHORT);
1219                 foreach ($allroles as $roleid => $role) {
1220                     $hascap = has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context);
1221                     if (is_siteadmin()) {
1222                         $this->assertTrue(isset($roles[$roleid]));
1223                     } else {
1224                         $parents = $context->get_parent_context_ids(true);
1225                         $pcontexts = implode(',' , $parents);
1226                         $allowed = $DB->record_exists_sql(
1227                             "SELECT r.id
1228                                FROM {role} r
1229                                JOIN {role_allow_override} rao ON r.id = rao.allowoverride
1230                                JOIN {role_assignments} ra ON rao.roleid = ra.roleid
1231                               WHERE ra.userid = :userid AND ra.contextid IN ($pcontexts) AND r.id = :roleid
1232                             ",
1233                             array('userid'=>$user->id, 'roleid'=>$roleid)
1234                         );
1235                         if (isset($roles[$roleid])) {
1236                             $this->assertTrue($hascap);
1237                             $this->assertTrue($allowed);
1238                         } else {
1239                             $this->assertFalse($hascap and $allowed);
1240                         }
1241                     }
1243                     if (isset($roles[$roleid])) {
1244                         $this->assertEquals($role->shortname, $roles[$roleid]);
1245                     }
1246                 }
1247             }
1248         }
1250         // Test parameter defaults.
1251         $this->setAdminUser();
1252         $roles1 = get_overridable_roles($coursecontext);
1253         $roles2 = get_overridable_roles($coursecontext, ROLENAME_ALIAS, false);
1254         $this->assertEquals($roles2, $roles1);
1256         $alltypes = array(ROLENAME_ALIAS, ROLENAME_ALIAS_RAW, ROLENAME_BOTH, ROLENAME_ORIGINAL, ROLENAME_ORIGINALANDSHORT, ROLENAME_SHORT);
1257         foreach ($alltypes as $type) {
1258             $rolenames = role_fix_names($allroles, $coursecontext, $type);
1259             $roles = get_overridable_roles($coursecontext, $type, false);
1260             foreach ($roles as $roleid => $rolename) {
1261                 $this->assertSame($rolenames[$roleid]->localname, $rolename);
1262             }
1263         }
1265         // Verify counts.
1266         $roles = get_overridable_roles($coursecontext, ROLENAME_ALIAS, false);
1267         list($rolenames, $rolecounts, $nameswithcounts) = get_overridable_roles($coursecontext, ROLENAME_ALIAS, true);
1268         $this->assertEquals($roles, $rolenames);
1269         foreach ($rolenames as $roleid => $name) {
1270             if ($roleid == $teacherrole->id) {
1271                 $this->assertEquals(1, $rolecounts[$roleid]);
1272             } else {
1273                 $this->assertEquals(0, $rolecounts[$roleid]);
1274             }
1275             $this->assertSame("$name ($rolecounts[$roleid])", $nameswithcounts[$roleid]);
1276         }
1277     }
1279     /**
1280      * Test we have context level defaults.
1281      */
1282     public function test_get_default_contextlevels() {
1283         $archetypes = get_role_archetypes();
1284         $alllevels = context_helper::get_all_levels();
1285         foreach ($archetypes as $archetype) {
1286             $defaults = get_default_contextlevels($archetype);
1287             $this->assertInternalType('array', $defaults);
1288             foreach ($defaults as $level) {
1289                 $this->assertTrue(isset($alllevels[$level]));
1290             }
1291         }
1292     }
1294     /**
1295      * Test role context level setup.
1296      */
1297     public function test_set_role_contextlevels() {
1298         global $DB;
1300         $this->resetAfterTest();
1302         $roleid = create_role('New student role', 'student2', 'New student description', 'student');
1304         $this->assertFalse($DB->record_exists('role_context_levels', array('roleid' => $roleid)));
1306         set_role_contextlevels($roleid, array(CONTEXT_COURSE, CONTEXT_MODULE));
1307         $levels = $DB->get_records('role_context_levels', array('roleid' => $roleid), '', 'contextlevel, contextlevel');
1308         $this->assertCount(2, $levels);
1309         $this->assertTrue(isset($levels[CONTEXT_COURSE]));
1310         $this->assertTrue(isset($levels[CONTEXT_MODULE]));
1312         set_role_contextlevels($roleid, array(CONTEXT_COURSE));
1313         $levels = $DB->get_records('role_context_levels', array('roleid' => $roleid), '', 'contextlevel, contextlevel');
1314         $this->assertCount(1, $levels);
1315         $this->assertTrue(isset($levels[CONTEXT_COURSE]));
1316     }
1318     /**
1319      * Test getting of role context levels
1320      */
1321     public function test_get_roles_for_contextlevels() {
1322         global $DB;
1324         $allroles = get_all_roles();
1325         foreach (context_helper::get_all_levels() as $level => $unused) {
1326             $roles = get_roles_for_contextlevels($level);
1327             foreach ($allroles as $roleid => $unused) {
1328                 $exists = $DB->record_exists('role_context_levels', array('contextlevel'=>$level, 'roleid'=>$roleid));
1329                 if (in_array($roleid, $roles)) {
1330                     $this->assertTrue($exists);
1331                 } else {
1332                     $this->assertFalse($exists);
1333                 }
1334             }
1335         }
1336     }
1338     /**
1339      * Test default enrol roles.
1340      */
1341     public function test_get_default_enrol_roles() {
1342         $this->resetAfterTest();
1344         $course = $this->getDataGenerator()->create_course();
1345         $coursecontext = context_course::instance($course->id);
1347         $id2 = create_role('New student role', 'student2', 'New student description', 'student');
1348         set_role_contextlevels($id2, array(CONTEXT_COURSE));
1350         $allroles = get_all_roles();
1351         $expected = array($id2=>$allroles[$id2]);
1353         foreach (get_role_archetypes() as $archetype) {
1354             $defaults = get_default_contextlevels($archetype);
1355             if (in_array(CONTEXT_COURSE, $defaults)) {
1356                 $roles = get_archetype_roles($archetype);
1357                 foreach ($roles as $role) {
1358                     $expected[$role->id] = $role;
1359                 }
1360             }
1361         }
1363         $roles = get_default_enrol_roles($coursecontext);
1364         foreach ($allroles as $role) {
1365             $this->assertEquals(isset($expected[$role->id]), isset($roles[$role->id]));
1366             if (isset($roles[$role->id])) {
1367                 $this->assertSame(role_get_name($role, $coursecontext), $roles[$role->id]);
1368             }
1369         }
1370     }
1372     /**
1373      * Test getting of role users.
1374      */
1375     public function test_get_role_users() {
1376         global $DB;
1378         $this->resetAfterTest();
1380         $systemcontext = context_system::instance();
1381         $studentrole = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST);
1382         $teacherrole = $DB->get_record('role', array('shortname'=>'editingteacher'), '*', MUST_EXIST);
1383         $course = $this->getDataGenerator()->create_course();
1384         $coursecontext = context_course::instance($course->id);
1385         $otherid = create_role('Other role', 'other', 'Some other role', '');
1386         $teacherrename = (object)array('roleid'=>$teacherrole->id, 'name'=>'Učitel', 'contextid'=>$coursecontext->id);
1387         $DB->insert_record('role_names', $teacherrename);
1388         $otherrename = (object)array('roleid'=>$otherid, 'name'=>'Ostatní', 'contextid'=>$coursecontext->id);
1389         $DB->insert_record('role_names', $otherrename);
1391         $user1 = $this->getDataGenerator()->create_user(array('firstname'=>'John', 'lastname'=>'Smith'));
1392         role_assign($teacherrole->id, $user1->id, $coursecontext->id);
1393         $user2 = $this->getDataGenerator()->create_user(array('firstname'=>'Jan', 'lastname'=>'Kovar'));
1394         role_assign($teacherrole->id, $user2->id, $systemcontext->id);
1395         $user3 = $this->getDataGenerator()->create_user();
1396         $this->getDataGenerator()->enrol_user($user3->id, $course->id, $teacherrole->id);
1397         $user4 = $this->getDataGenerator()->create_user();
1398         $this->getDataGenerator()->enrol_user($user4->id, $course->id, $studentrole->id);
1400         $group = $this->getDataGenerator()->create_group(array('courseid'=>$course->id));
1401         groups_add_member($group, $user3);
1403         $users = get_role_users($teacherrole->id, $coursecontext);
1404         $this->assertCount(2, $users);
1405         $this->assertArrayHasKey($user1->id, $users);
1406         $this->assertEquals($users[$user1->id]->id, $user1->id);
1407         $this->assertEquals($users[$user1->id]->roleid, $teacherrole->id);
1408         $this->assertEquals($users[$user1->id]->rolename, $teacherrole->name);
1409         $this->assertEquals($users[$user1->id]->roleshortname, $teacherrole->shortname);
1410         $this->assertEquals($users[$user1->id]->rolecoursealias, $teacherrename->name);
1411         $this->assertArrayHasKey($user3->id, $users);
1412         $this->assertEquals($users[$user3->id]->id, $user3->id);
1413         $this->assertEquals($users[$user3->id]->roleid, $teacherrole->id);
1414         $this->assertEquals($users[$user3->id]->rolename, $teacherrole->name);
1415         $this->assertEquals($users[$user3->id]->roleshortname, $teacherrole->shortname);
1416         $this->assertEquals($users[$user3->id]->rolecoursealias, $teacherrename->name);
1418         $users = get_role_users($teacherrole->id, $coursecontext, true);
1419         $this->assertCount(3, $users);
1421         $users = get_role_users($teacherrole->id, $coursecontext, true, '', null, null, '', 2, 1);
1422         $this->assertCount(1, $users);
1424         $users = get_role_users($teacherrole->id, $coursecontext, false, 'u.id, u.email, u.idnumber', 'u.idnumber');
1425         $this->assertCount(2, $users);
1426         $this->assertArrayHasKey($user1->id, $users);
1427         $this->assertArrayHasKey($user3->id, $users);
1429         $users = get_role_users($teacherrole->id, $coursecontext, false, 'u.id, u.email, u.idnumber', 'u.idnumber', null, $group->id);
1430         $this->assertCount(1, $users);
1431         $this->assertArrayHasKey($user3->id, $users);
1433         $users = get_role_users($teacherrole->id, $coursecontext, true, 'u.id, u.email, u.idnumber, u.firstname', 'u.idnumber', null, '', '', '', 'u.firstname = :xfirstname', array('xfirstname'=>'John'));
1434         $this->assertCount(1, $users);
1435         $this->assertArrayHasKey($user1->id, $users);
1436     }
1438     /**
1439      * Test used role query.
1440      */
1441     public function test_get_roles_used_in_context() {
1442         global $DB;
1444         $this->resetAfterTest();
1446         $systemcontext = context_system::instance();
1447         $teacherrole = $DB->get_record('role', array('shortname'=>'editingteacher'), '*', MUST_EXIST);
1448         $course = $this->getDataGenerator()->create_course();
1449         $coursecontext = context_course::instance($course->id);
1450         $otherid = create_role('Other role', 'other', 'Some other role', '');
1451         $teacherrename = (object)array('roleid'=>$teacherrole->id, 'name'=>'Učitel', 'contextid'=>$coursecontext->id);
1452         $DB->insert_record('role_names', $teacherrename);
1453         $otherrename = (object)array('roleid'=>$otherid, 'name'=>'Ostatní', 'contextid'=>$coursecontext->id);
1454         $DB->insert_record('role_names', $otherrename);
1456         $user1 = $this->getDataGenerator()->create_user();
1457         role_assign($teacherrole->id, $user1->id, $coursecontext->id);
1459         $roles = get_roles_used_in_context($coursecontext);
1460         $this->assertCount(1, $roles);
1461         $role = reset($roles);
1462         $roleid = key($roles);
1463         $this->assertEquals($roleid, $role->id);
1464         $this->assertEquals($teacherrole->id, $role->id);
1465         $this->assertSame($teacherrole->name, $role->name);
1466         $this->assertSame($teacherrole->shortname, $role->shortname);
1467         $this->assertEquals($teacherrole->sortorder, $role->sortorder);
1468         $this->assertSame($teacherrename->name, $role->coursealias);
1470         $user2 = $this->getDataGenerator()->create_user();
1471         role_assign($teacherrole->id, $user2->id, $systemcontext->id);
1472         role_assign($otherid, $user2->id, $systemcontext->id);
1474         $roles = get_roles_used_in_context($systemcontext);
1475         $this->assertCount(2, $roles);
1476     }
1478     /**
1479      * Test roles used in course.
1480      */
1481     public function test_get_user_roles_in_course() {
1482         global $DB, $CFG;
1484         $this->resetAfterTest();
1486         $teacherrole = $DB->get_record('role', array('shortname'=>'editingteacher'), '*', MUST_EXIST);
1487         $studentrole = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST);
1488         $course = $this->getDataGenerator()->create_course();
1489         $coursecontext = context_course::instance($course->id);
1490         $teacherrename = (object)array('roleid'=>$teacherrole->id, 'name'=>'Učitel', 'contextid'=>$coursecontext->id);
1491         $DB->insert_record('role_names', $teacherrename);
1493         $roleids = explode(',', $CFG->profileroles); // Should include teacher and student in new installs.
1494         $this->assertTrue(in_array($teacherrole->id, $roleids));
1495         $this->assertTrue(in_array($studentrole->id, $roleids));
1497         $user1 = $this->getDataGenerator()->create_user();
1498         role_assign($teacherrole->id, $user1->id, $coursecontext->id);
1499         role_assign($studentrole->id, $user1->id, $coursecontext->id);
1500         $user2 = $this->getDataGenerator()->create_user();
1501         role_assign($studentrole->id, $user2->id, $coursecontext->id);
1502         $user3 = $this->getDataGenerator()->create_user();
1504         $roles = get_user_roles_in_course($user1->id, $course->id);
1505         $this->assertEquals(1, preg_match_all('/,/', $roles, $matches));
1506         $this->assertTrue(strpos($roles, role_get_name($teacherrole, $coursecontext)) !== false);
1508         $roles = get_user_roles_in_course($user2->id, $course->id);
1509         $this->assertEquals(0, preg_match_all('/,/', $roles, $matches));
1510         $this->assertTrue(strpos($roles, role_get_name($studentrole, $coursecontext)) !== false);
1512         $roles = get_user_roles_in_course($user3->id, $course->id);
1513         $this->assertSame('', $roles);
1514     }
1516     /**
1517      * Test has_capability(), has_any_capability() and has_all_capabilities().
1518      */
1519     public function test_has_capability_and_friends() {
1520         global $DB;
1522         $this->resetAfterTest();
1524         $course = $this->getDataGenerator()->create_course();
1525         $coursecontext = context_course::instance($course->id);
1526         $teacherrole = $DB->get_record('role', array('shortname'=>'editingteacher'), '*', MUST_EXIST);
1527         $teacher = $this->getDataGenerator()->create_user();
1528         role_assign($teacherrole->id, $teacher->id, $coursecontext);
1529         $admin = $DB->get_record('user', array('username'=>'admin'));
1531         // Note: Here are used default capabilities, the full test is in permission evaluation bellow,
1532         // use two capabilities that teacher has and one does not, none of them should be allowed for not-logged-in user.
1534         $this->assertTrue($DB->record_exists('capabilities', array('name'=>'moodle/backup:backupsection')));
1535         $this->assertTrue($DB->record_exists('capabilities', array('name'=>'moodle/backup:backupcourse')));
1536         $this->assertTrue($DB->record_exists('capabilities', array('name'=>'moodle/site:approvecourse')));
1538         $sca = array('moodle/backup:backupsection', 'moodle/backup:backupcourse', 'moodle/site:approvecourse');
1539         $sc = array('moodle/backup:backupsection', 'moodle/backup:backupcourse');
1541         $this->setUser(0);
1542         $this->assertFalse(has_capability('moodle/backup:backupsection', $coursecontext));
1543         $this->assertFalse(has_capability('moodle/backup:backupcourse', $coursecontext));
1544         $this->assertFalse(has_capability('moodle/site:approvecourse', $coursecontext));
1545         $this->assertFalse(has_any_capability($sca, $coursecontext));
1546         $this->assertFalse(has_all_capabilities($sca, $coursecontext));
1548         $this->assertTrue(has_capability('moodle/backup:backupsection', $coursecontext, $teacher));
1549         $this->assertTrue(has_capability('moodle/backup:backupcourse', $coursecontext, $teacher));
1550         $this->assertFalse(has_capability('moodle/site:approvecourse', $coursecontext, $teacher));
1551         $this->assertTrue(has_any_capability($sca, $coursecontext, $teacher));
1552         $this->assertTrue(has_all_capabilities($sc, $coursecontext, $teacher));
1553         $this->assertFalse(has_all_capabilities($sca, $coursecontext, $teacher));
1555         $this->assertTrue(has_capability('moodle/backup:backupsection', $coursecontext, $admin));
1556         $this->assertTrue(has_capability('moodle/backup:backupcourse', $coursecontext, $admin));
1557         $this->assertTrue(has_capability('moodle/site:approvecourse', $coursecontext, $admin));
1558         $this->assertTrue(has_any_capability($sca, $coursecontext, $admin));
1559         $this->assertTrue(has_all_capabilities($sc, $coursecontext, $admin));
1560         $this->assertTrue(has_all_capabilities($sca, $coursecontext, $admin));
1562         $this->assertFalse(has_capability('moodle/backup:backupsection', $coursecontext, $admin, false));
1563         $this->assertFalse(has_capability('moodle/backup:backupcourse', $coursecontext, $admin, false));
1564         $this->assertFalse(has_capability('moodle/site:approvecourse', $coursecontext, $admin, false));
1565         $this->assertFalse(has_any_capability($sca, $coursecontext, $admin, false));
1566         $this->assertFalse(has_all_capabilities($sc, $coursecontext, $admin, false));
1567         $this->assertFalse(has_all_capabilities($sca, $coursecontext, $admin, false));
1569         $this->setUser($teacher);
1570         $this->assertTrue(has_capability('moodle/backup:backupsection', $coursecontext));
1571         $this->assertTrue(has_capability('moodle/backup:backupcourse', $coursecontext));
1572         $this->assertFalse(has_capability('moodle/site:approvecourse', $coursecontext));
1573         $this->assertTrue(has_any_capability($sca, $coursecontext));
1574         $this->assertTrue(has_all_capabilities($sc, $coursecontext));
1575         $this->assertFalse(has_all_capabilities($sca, $coursecontext));
1577         $this->setAdminUser();
1578         $this->assertTrue(has_capability('moodle/backup:backupsection', $coursecontext));
1579         $this->assertTrue(has_capability('moodle/backup:backupcourse', $coursecontext));
1580         $this->assertTrue(has_capability('moodle/site:approvecourse', $coursecontext));
1581         $this->assertTrue(has_any_capability($sca, $coursecontext));
1582         $this->assertTrue(has_all_capabilities($sc, $coursecontext));
1583         $this->assertTrue(has_all_capabilities($sca, $coursecontext));
1585         $this->assertFalse(has_capability('moodle/backup:backupsection', $coursecontext, 0));
1586         $this->assertFalse(has_capability('moodle/backup:backupcourse', $coursecontext, 0));
1587         $this->assertFalse(has_capability('moodle/site:approvecourse', $coursecontext, 0));
1588         $this->assertFalse(has_any_capability($sca, $coursecontext, 0));
1589         $this->assertFalse(has_all_capabilities($sca, $coursecontext, 0));
1590     }
1592     /**
1593      * Test if course creator future capability lookup works.
1594      */
1595     public function test_guess_if_creator_will_have_course_capability() {
1596         global $DB, $CFG, $USER;
1598         $this->resetAfterTest();
1600         $category = $this->getDataGenerator()->create_category();
1601         $course = $this->getDataGenerator()->create_course(array('category'=>$category->id));
1603         $syscontext = context_system::instance();
1604         $categorycontext = context_coursecat::instance($category->id);
1605         $coursecontext = context_course::instance($course->id);
1606         $studentrole = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST);
1607         $teacherrole = $DB->get_record('role', array('shortname'=>'editingteacher'), '*', MUST_EXIST);
1608         $creatorrole = $DB->get_record('role', array('shortname'=>'coursecreator'), '*', MUST_EXIST);
1609         $managerrole = $DB->get_record('role', array('shortname'=>'manager'), '*', MUST_EXIST);
1611         $this->assertEquals($teacherrole->id, $CFG->creatornewroleid);
1613         $creator = $this->getDataGenerator()->create_user();
1614         $manager = $this->getDataGenerator()->create_user();
1615         role_assign($managerrole->id, $manager->id, $categorycontext);
1617         $this->assertFalse(has_capability('moodle/course:view', $categorycontext, $creator));
1618         $this->assertFalse(has_capability('moodle/role:assign', $categorycontext, $creator));
1619         $this->assertFalse(has_capability('moodle/course:visibility', $categorycontext, $creator));
1620         $this->assertFalse(has_capability('moodle/course:visibility', $coursecontext, $creator));
1621         $this->assertFalse(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext, $creator));
1622         $this->assertFalse(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext, $creator));
1624         $this->assertTrue(has_capability('moodle/role:assign', $categorycontext, $manager));
1625         $this->assertTrue(has_capability('moodle/course:visibility', $categorycontext, $manager));
1626         $this->assertTrue(has_capability('moodle/course:visibility', $coursecontext, $manager));
1627         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext, $manager->id));
1628         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext, $manager->id));
1630         $this->assertEquals(0, $USER->id);
1631         $this->assertFalse(has_capability('moodle/course:view', $categorycontext));
1632         $this->assertFalse(has_capability('moodle/role:assign', $categorycontext));
1633         $this->assertFalse(has_capability('moodle/course:visibility', $categorycontext));
1634         $this->assertFalse(has_capability('moodle/course:visibility', $coursecontext));
1635         $this->assertFalse(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext));
1636         $this->assertFalse(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext));
1638         $this->setUser($manager);
1639         $this->assertTrue(has_capability('moodle/role:assign', $categorycontext));
1640         $this->assertTrue(has_capability('moodle/course:visibility', $categorycontext));
1641         $this->assertTrue(has_capability('moodle/course:visibility', $coursecontext));
1642         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext));
1643         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext));
1645         $this->setAdminUser();
1646         $this->assertTrue(has_capability('moodle/role:assign', $categorycontext));
1647         $this->assertTrue(has_capability('moodle/course:visibility', $categorycontext));
1648         $this->assertTrue(has_capability('moodle/course:visibility', $coursecontext));
1649         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext));
1650         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext));
1651         $this->setUser(0);
1653         role_assign($creatorrole->id, $creator->id, $categorycontext);
1655         $this->assertFalse(has_capability('moodle/role:assign', $categorycontext, $creator));
1656         $this->assertFalse(has_capability('moodle/course:visibility', $categorycontext, $creator));
1657         $this->assertFalse(has_capability('moodle/course:visibility', $coursecontext, $creator));
1658         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext, $creator));
1659         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext, $creator));
1661         $this->setUser($creator);
1662         $this->assertFalse(has_capability('moodle/role:assign', $categorycontext, null));
1663         $this->assertFalse(has_capability('moodle/course:visibility', $categorycontext, null));
1664         $this->assertFalse(has_capability('moodle/course:visibility', $coursecontext, null));
1665         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext, null));
1666         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext, null));
1667         $this->setUser(0);
1669         set_config('creatornewroleid', $studentrole->id);
1671         $this->assertFalse(has_capability('moodle/course:visibility', $categorycontext, $creator));
1672         $this->assertFalse(has_capability('moodle/course:visibility', $coursecontext, $creator));
1673         $this->assertFalse(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext, $creator));
1674         $this->assertFalse(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext, $creator));
1676         set_config('creatornewroleid', $teacherrole->id);
1678         role_change_permission($managerrole->id, $categorycontext, 'moodle/course:visibility', CAP_PREVENT);
1679         role_assign($creatorrole->id, $manager->id, $categorycontext);
1681         $this->assertTrue(has_capability('moodle/course:view', $categorycontext, $manager));
1682         $this->assertTrue(has_capability('moodle/course:view', $coursecontext, $manager));
1683         $this->assertTrue(has_capability('moodle/role:assign', $categorycontext, $manager));
1684         $this->assertTrue(has_capability('moodle/role:assign', $coursecontext, $manager));
1685         $this->assertFalse(has_capability('moodle/course:visibility', $categorycontext, $manager));
1686         $this->assertFalse(has_capability('moodle/course:visibility', $coursecontext, $manager));
1687         $this->assertFalse(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext, $manager));
1688         $this->assertFalse(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext, $manager));
1690         role_change_permission($managerrole->id, $categorycontext, 'moodle/course:view', CAP_PREVENT);
1691         $this->assertTrue(has_capability('moodle/role:assign', $categorycontext, $manager));
1692         $this->assertFalse(has_capability('moodle/course:visibility', $categorycontext, $manager));
1693         $this->assertFalse(has_capability('moodle/course:visibility', $coursecontext, $manager));
1694         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext, $manager));
1695         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext, $manager));
1697         $this->getDataGenerator()->enrol_user($manager->id, $course->id, 0);
1699         $this->assertTrue(has_capability('moodle/role:assign', $categorycontext, $manager));
1700         $this->assertTrue(has_capability('moodle/role:assign', $coursecontext, $manager));
1701         $this->assertTrue(is_enrolled($coursecontext, $manager));
1702         $this->assertFalse(has_capability('moodle/course:visibility', $categorycontext, $manager));
1703         $this->assertFalse(has_capability('moodle/course:visibility', $coursecontext, $manager));
1704         $this->assertTrue(guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext, $manager));
1705         $this->assertFalse(guess_if_creator_will_have_course_capability('moodle/course:visibility', $coursecontext, $manager));
1707         // Test problems.
1709         try {
1710             guess_if_creator_will_have_course_capability('moodle/course:visibility', $syscontext, $creator);
1711             $this->fail('Exception expected when non course/category context passed to guess_if_creator_will_have_course_capability()');
1712         } catch (moodle_exception $e) {
1713             $this->assertInstanceOf('coding_exception', $e);
1714         }
1715     }
1717     /**
1718      * Test require_capability() exceptions.
1719      */
1720     public function test_require_capability() {
1721         $this->resetAfterTest();
1723         $syscontext = context_system::instance();
1725         $this->setUser(0);
1726         $this->assertFalse(has_capability('moodle/site:config', $syscontext));
1727         try {
1728             require_capability('moodle/site:config', $syscontext);
1729             $this->fail('Exception expected from require_capability()');
1730         } catch (moodle_exception $e) {
1731             $this->assertInstanceOf('required_capability_exception', $e);
1732         }
1733         $this->setAdminUser();
1734         $this->assertFalse(has_capability('moodle/site:config', $syscontext, 0));
1735         try {
1736             require_capability('moodle/site:config', $syscontext, 0);
1737             $this->fail('Exception expected from require_capability()');
1738         } catch (moodle_exception $e) {
1739             $this->assertInstanceOf('required_capability_exception', $e);
1740         }
1741         $this->assertFalse(has_capability('moodle/site:config', $syscontext, null, false));
1742         try {
1743             require_capability('moodle/site:config', $syscontext, null, false);
1744             $this->fail('Exception expected from require_capability()');
1745         } catch (moodle_exception $e) {
1746             $this->assertInstanceOf('required_capability_exception', $e);
1747         }
1748     }
1750     /**
1751      * A small functional test of permission evaluations.
1752      */
1753     public function test_permission_evaluation() {
1754         global $USER, $SITE, $CFG, $DB, $ACCESSLIB_PRIVATE;
1756         $this->resetAfterTest();
1758         $generator = $this->getDataGenerator();
1760         // Fill the site with some real data.
1761         $testcategories = array();
1762         $testcourses = array();
1763         $testpages = array();
1764         $testblocks = array();
1765         $allroles = $DB->get_records_menu('role', array(), 'id', 'archetype, id');
1767         $systemcontext = context_system::instance();
1768         $frontpagecontext = context_course::instance(SITEID);
1770         // Add block to system context.
1771         $bi = $generator->create_block('online_users');
1772         context_block::instance($bi->id);
1773         $testblocks[] = $bi->id;
1775         // Some users.
1776         $testusers = array();
1777         for ($i=0; $i<20; $i++) {
1778             $user = $generator->create_user();
1779             $testusers[$i] = $user->id;
1780             $usercontext = context_user::instance($user->id);
1782             // Add block to user profile.
1783             $bi = $generator->create_block('online_users', array('parentcontextid'=>$usercontext->id));
1784             $testblocks[] = $bi->id;
1785         }
1786         // Deleted user - should be ignored everywhere, can not have context.
1787         $generator->create_user(array('deleted'=>1));
1789         // Add block to frontpage.
1790         $bi = $generator->create_block('online_users', array('parentcontextid'=>$frontpagecontext->id));
1791         $frontpageblockcontext = context_block::instance($bi->id);
1792         $testblocks[] = $bi->id;
1794         // Add a resource to frontpage.
1795         $page = $generator->create_module('page', array('course'=>$SITE->id));
1796         $testpages[] = $page->id;
1797         $frontpagepagecontext = context_module::instance($page->cmid);
1799         // Add block to frontpage resource.
1800         $bi = $generator->create_block('online_users', array('parentcontextid'=>$frontpagepagecontext->id));
1801         $frontpagepageblockcontext = context_block::instance($bi->id);
1802         $testblocks[] = $bi->id;
1804         // Some nested course categories with courses.
1805         $manualenrol = enrol_get_plugin('manual');
1806         $parentcat = 0;
1807         for ($i=0; $i<5; $i++) {
1808             $cat = $generator->create_category(array('parent'=>$parentcat));
1809             $testcategories[] = $cat->id;
1810             $catcontext = context_coursecat::instance($cat->id);
1811             $parentcat = $cat->id;
1813             if ($i >= 4) {
1814                 continue;
1815             }
1817             // Add resource to each category.
1818             $bi = $generator->create_block('online_users', array('parentcontextid'=>$catcontext->id));
1819             context_block::instance($bi->id);
1821             // Add a few courses to each category.
1822             for ($j=0; $j<6; $j++) {
1823                 $course = $generator->create_course(array('category'=>$cat->id));
1824                 $testcourses[] = $course->id;
1825                 $coursecontext = context_course::instance($course->id);
1827                 if ($j >= 5) {
1828                     continue;
1829                 }
1830                 // Add manual enrol instance.
1831                 $manualenrol->add_default_instance($DB->get_record('course', array('id'=>$course->id)));
1833                 // Add block to each course.
1834                 $bi = $generator->create_block('online_users', array('parentcontextid'=>$coursecontext->id));
1835                 $testblocks[] = $bi->id;
1837                 // Add a resource to each course.
1838                 $page = $generator->create_module('page', array('course'=>$course->id));
1839                 $testpages[] = $page->id;
1840                 $modcontext = context_module::instance($page->cmid);
1842                 // Add block to each module.
1843                 $bi = $generator->create_block('online_users', array('parentcontextid'=>$modcontext->id));
1844                 $testblocks[] = $bi->id;
1845             }
1846         }
1848         // Make sure all contexts were created properly.
1849         $count = 1; // System.
1850         $count += $DB->count_records('user', array('deleted'=>0));
1851         $count += $DB->count_records('course_categories');
1852         $count += $DB->count_records('course');
1853         $count += $DB->count_records('course_modules');
1854         $count += $DB->count_records('block_instances');
1855         $this->assertEquals($count, $DB->count_records('context'));
1856         $this->assertEquals(0, $DB->count_records('context', array('depth'=>0)));
1857         $this->assertEquals(0, $DB->count_records('context', array('path'=>null)));
1860         // Test context_helper::get_level_name() method.
1862         $levels = context_helper::get_all_levels();
1863         foreach ($levels as $level => $classname) {
1864             $name = context_helper::get_level_name($level);
1865             $this->assertNotEmpty($name);
1866         }
1869         // Test context::instance_by_id(), context_xxx::instance() methods.
1871         $context = context::instance_by_id($frontpagecontext->id);
1872         $this->assertSame(CONTEXT_COURSE, $context->contextlevel);
1873         $this->assertFalse(context::instance_by_id(-1, IGNORE_MISSING));
1874         try {
1875             context::instance_by_id(-1);
1876             $this->fail('exception expected');
1877         } catch (moodle_exception $e) {
1878             $this->assertTrue(true);
1879         }
1880         $this->assertInstanceOf('context_system', context_system::instance());
1881         $this->assertInstanceOf('context_coursecat', context_coursecat::instance($testcategories[0]));
1882         $this->assertInstanceOf('context_course', context_course::instance($testcourses[0]));
1883         $this->assertInstanceOf('context_module', context_module::instance($testpages[0]));
1884         $this->assertInstanceOf('context_block', context_block::instance($testblocks[0]));
1886         $this->assertFalse(context_coursecat::instance(-1, IGNORE_MISSING));
1887         $this->assertFalse(context_course::instance(-1, IGNORE_MISSING));
1888         $this->assertFalse(context_module::instance(-1, IGNORE_MISSING));
1889         $this->assertFalse(context_block::instance(-1, IGNORE_MISSING));
1890         try {
1891             context_coursecat::instance(-1);
1892             $this->fail('exception expected');
1893         } catch (moodle_exception $e) {
1894             $this->assertTrue(true);
1895         }
1896         try {
1897             context_course::instance(-1);
1898             $this->fail('exception expected');
1899         } catch (moodle_exception $e) {
1900             $this->assertTrue(true);
1901         }
1902         try {
1903             context_module::instance(-1);
1904             $this->fail('exception expected');
1905         } catch (moodle_exception $e) {
1906             $this->assertTrue(true);
1907         }
1908         try {
1909             context_block::instance(-1);
1910             $this->fail('exception expected');
1911         } catch (moodle_exception $e) {
1912             $this->assertTrue(true);
1913         }
1916         // Test $context->get_url(), $context->get_context_name(), $context->get_capabilities() methods.
1918         $testcontexts = array();
1919         $testcontexts[CONTEXT_SYSTEM]    = context_system::instance();
1920         $testcontexts[CONTEXT_COURSECAT] = context_coursecat::instance($testcategories[0]);
1921         $testcontexts[CONTEXT_COURSE]    = context_course::instance($testcourses[0]);
1922         $testcontexts[CONTEXT_MODULE]    = context_module::instance($testpages[0]);
1923         $testcontexts[CONTEXT_BLOCK]     = context_block::instance($testblocks[0]);
1925         foreach ($testcontexts as $context) {
1926             $name = $context->get_context_name(true, true);
1927             $this->assertNotEmpty($name);
1929             $this->assertInstanceOf('moodle_url', $context->get_url());
1931             $caps = $context->get_capabilities();
1932             $this->assertTrue(is_array($caps));
1933             foreach ($caps as $cap) {
1934                 $cap = (array)$cap;
1935                 $this->assertSame(array_keys($cap), array('id', 'name', 'captype', 'contextlevel', 'component', 'riskbitmask'));
1936             }
1937         }
1938         unset($testcontexts);
1940         // Test $context->get_course_context() method.
1942         $this->assertFalse($systemcontext->get_course_context(false));
1943         try {
1944             $systemcontext->get_course_context();
1945             $this->fail('exception expected');
1946         } catch (moodle_exception $e) {
1947             $this->assertInstanceOf('coding_exception', $e);
1948         }
1949         $context = context_coursecat::instance($testcategories[0]);
1950         $this->assertFalse($context->get_course_context(false));
1951         try {
1952             $context->get_course_context();
1953             $this->fail('exception expected');
1954         } catch (moodle_exception $e) {
1955             $this->assertInstanceOf('coding_exception', $e);
1956         }
1957         $this->assertEquals($frontpagecontext, $frontpagecontext->get_course_context(true));
1958         $this->assertEquals($frontpagecontext, $frontpagepagecontext->get_course_context(true));
1959         $this->assertEquals($frontpagecontext, $frontpagepageblockcontext->get_course_context(true));
1962         // Test $context->get_parent_context(), $context->get_parent_contexts(), $context->get_parent_context_ids() methods.
1964         $userid = reset($testusers);
1965         $usercontext = context_user::instance($userid);
1966         $this->assertEquals($systemcontext, $usercontext->get_parent_context());
1967         $this->assertEquals(array($systemcontext->id=>$systemcontext), $usercontext->get_parent_contexts());
1968         $this->assertEquals(array($usercontext->id=>$usercontext, $systemcontext->id=>$systemcontext), $usercontext->get_parent_contexts(true));
1970         $this->assertEquals(array(), $systemcontext->get_parent_contexts());
1971         $this->assertEquals(array($systemcontext->id=>$systemcontext), $systemcontext->get_parent_contexts(true));
1972         $this->assertEquals(array(), $systemcontext->get_parent_context_ids());
1973         $this->assertEquals(array($systemcontext->id), $systemcontext->get_parent_context_ids(true));
1975         $this->assertEquals($systemcontext, $frontpagecontext->get_parent_context());
1976         $this->assertEquals(array($systemcontext->id=>$systemcontext), $frontpagecontext->get_parent_contexts());
1977         $this->assertEquals(array($frontpagecontext->id=>$frontpagecontext, $systemcontext->id=>$systemcontext), $frontpagecontext->get_parent_contexts(true));
1978         $this->assertEquals(array($systemcontext->id), $frontpagecontext->get_parent_context_ids());
1979         $this->assertEquals(array($frontpagecontext->id, $systemcontext->id), $frontpagecontext->get_parent_context_ids(true));
1981         $this->assertFalse($systemcontext->get_parent_context());
1982         $frontpagecontext = context_course::instance($SITE->id);
1983         $parent = $systemcontext;
1984         foreach ($testcategories as $catid) {
1985             $catcontext = context_coursecat::instance($catid);
1986             $this->assertEquals($parent, $catcontext->get_parent_context());
1987             $parent = $catcontext;
1988         }
1989         $this->assertEquals($frontpagecontext, $frontpagepagecontext->get_parent_context());
1990         $this->assertEquals($frontpagecontext, $frontpageblockcontext->get_parent_context());
1991         $this->assertEquals($frontpagepagecontext, $frontpagepageblockcontext->get_parent_context());
1994         // Test $context->get_child_contexts() method.
1996         $children = $systemcontext->get_child_contexts();
1997         $this->resetDebugging();
1998         $this->assertEquals(count($children)+1, $DB->count_records('context'));
2000         $context = context_coursecat::instance($testcategories[3]);
2001         $children = $context->get_child_contexts();
2002         $countcats    = 0;
2003         $countcourses = 0;
2004         $countblocks  = 0;
2005         foreach ($children as $child) {
2006             if ($child->contextlevel == CONTEXT_COURSECAT) {
2007                 $countcats++;
2008             }
2009             if ($child->contextlevel == CONTEXT_COURSE) {
2010                 $countcourses++;
2011             }
2012             if ($child->contextlevel == CONTEXT_BLOCK) {
2013                 $countblocks++;
2014             }
2015         }
2016         $this->assertCount(8, $children);
2017         $this->assertEquals(1, $countcats);
2018         $this->assertEquals(6, $countcourses);
2019         $this->assertEquals(1, $countblocks);
2021         $context = context_course::instance($testcourses[2]);
2022         $children = $context->get_child_contexts();
2023         $this->assertCount(7, $children); // Depends on number of default blocks.
2025         $context = context_module::instance($testpages[3]);
2026         $children = $context->get_child_contexts();
2027         $this->assertCount(1, $children);
2029         $context = context_block::instance($testblocks[1]);
2030         $children = $context->get_child_contexts();
2031         $this->assertCount(0, $children);
2033         unset($children);
2034         unset($countcats);
2035         unset($countcourses);
2036         unset($countblocks);
2039         // Test context_helper::reset_caches() method.
2041         context_helper::reset_caches();
2042         $this->assertEquals(0, context_inspection::test_context_cache_size());
2043         context_course::instance($SITE->id);
2044         $this->assertEquals(1, context_inspection::test_context_cache_size());
2047         // Test context preloading.
2049         context_helper::reset_caches();
2050         $sql = "SELECT ".context_helper::get_preload_record_columns_sql('c')."
2051                   FROM {context} c
2052                  WHERE c.contextlevel <> ".CONTEXT_SYSTEM;
2053         $records = $DB->get_records_sql($sql);
2054         $firstrecord = reset($records);
2055         $columns = context_helper::get_preload_record_columns('c');
2056         $firstrecord = (array)$firstrecord;
2057         $this->assertSame(array_keys($firstrecord), array_values($columns));
2058         context_helper::reset_caches();
2059         foreach ($records as $record) {
2060             context_helper::preload_from_record($record);
2061             $this->assertEquals(new stdClass(), $record);
2062         }
2063         $this->assertEquals(count($records), context_inspection::test_context_cache_size());
2064         unset($records);
2065         unset($columns);
2067         context_helper::reset_caches();
2068         context_helper::preload_course($SITE->id);
2069         $numfrontpagemodules = $DB->count_records('course_modules', array('course' => $SITE->id));
2070         $this->assertEquals(6 + $numfrontpagemodules, context_inspection::test_context_cache_size()); // Depends on number of default blocks.
2072         // Test assign_capability(), unassign_capability() functions.
2074         $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
2075         $this->assertFalse($rc);
2076         assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $allroles['teacher'], $frontpagecontext->id);
2077         $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
2078         $this->assertEquals(CAP_ALLOW, $rc->permission);
2079         assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $allroles['teacher'], $frontpagecontext->id);
2080         $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
2081         $this->assertEquals(CAP_ALLOW, $rc->permission);
2082         assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $allroles['teacher'], $frontpagecontext, true);
2083         $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
2084         $this->assertEquals(CAP_PREVENT, $rc->permission);
2086         assign_capability('moodle/site:accessallgroups', CAP_INHERIT, $allroles['teacher'], $frontpagecontext);
2087         $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
2088         $this->assertFalse($rc);
2089         assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $allroles['teacher'], $frontpagecontext);
2090         unassign_capability('moodle/site:accessallgroups', $allroles['teacher'], $frontpagecontext, true);
2091         $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
2092         $this->assertFalse($rc);
2093         unassign_capability('moodle/site:accessallgroups', $allroles['teacher'], $frontpagecontext->id, true);
2094         unset($rc);
2096         accesslib_clear_all_caches(false); // Must be done after assign_capability().
2099         // Test role_assign(), role_unassign(), role_unassign_all() functions.
2101         $context = context_course::instance($testcourses[1]);
2102         $this->assertEquals(0, $DB->count_records('role_assignments', array('contextid'=>$context->id)));
2103         role_assign($allroles['teacher'], $testusers[1], $context->id);
2104         role_assign($allroles['teacher'], $testusers[2], $context->id);
2105         role_assign($allroles['manager'], $testusers[1], $context->id);
2106         $this->assertEquals(3, $DB->count_records('role_assignments', array('contextid'=>$context->id)));
2107         role_unassign($allroles['teacher'], $testusers[1], $context->id);
2108         $this->assertEquals(2, $DB->count_records('role_assignments', array('contextid'=>$context->id)));
2109         role_unassign_all(array('contextid'=>$context->id));
2110         $this->assertEquals(0, $DB->count_records('role_assignments', array('contextid'=>$context->id)));
2111         unset($context);
2113         accesslib_clear_all_caches(false); // Just in case.
2116         // Test has_capability(), get_users_by_capability(), role_switch(), reload_all_capabilities() and friends functions.
2118         $adminid = get_admin()->id;
2119         $guestid = $CFG->siteguest;
2121         // Enrol some users into some courses.
2122         $course1 = $DB->get_record('course', array('id'=>$testcourses[22]), '*', MUST_EXIST);
2123         $course2 = $DB->get_record('course', array('id'=>$testcourses[7]), '*', MUST_EXIST);
2124         $cms = $DB->get_records('course_modules', array('course'=>$course1->id), 'id');
2125         $cm1 = reset($cms);
2126         $blocks = $DB->get_records('block_instances', array('parentcontextid'=>context_module::instance($cm1->id)->id), 'id');
2127         $block1 = reset($blocks);
2128         $instance1 = $DB->get_record('enrol', array('enrol'=>'manual', 'courseid'=>$course1->id));
2129         $instance2 = $DB->get_record('enrol', array('enrol'=>'manual', 'courseid'=>$course2->id));
2130         for ($i=0; $i<9; $i++) {
2131             $manualenrol->enrol_user($instance1, $testusers[$i], $allroles['student']);
2132         }
2133         $manualenrol->enrol_user($instance1, $testusers[8], $allroles['teacher']);
2134         $manualenrol->enrol_user($instance1, $testusers[9], $allroles['editingteacher']);
2136         for ($i=10; $i<15; $i++) {
2137             $manualenrol->enrol_user($instance2, $testusers[$i], $allroles['student']);
2138         }
2139         $manualenrol->enrol_user($instance2, $testusers[15], $allroles['editingteacher']);
2141         // Add tons of role assignments - the more the better.
2142         role_assign($allroles['coursecreator'], $testusers[11], context_coursecat::instance($testcategories[2]));
2143         role_assign($allroles['manager'], $testusers[12], context_coursecat::instance($testcategories[1]));
2144         role_assign($allroles['student'], $testusers[9], context_module::instance($cm1->id));
2145         role_assign($allroles['teacher'], $testusers[8], context_module::instance($cm1->id));
2146         role_assign($allroles['guest'], $testusers[13], context_course::instance($course1->id));
2147         role_assign($allroles['teacher'], $testusers[7], context_block::instance($block1->id));
2148         role_assign($allroles['manager'], $testusers[9], context_block::instance($block1->id));
2149         role_assign($allroles['editingteacher'], $testusers[9], context_course::instance($course1->id));
2151         role_assign($allroles['teacher'], $adminid, context_course::instance($course1->id));
2152         role_assign($allroles['editingteacher'], $adminid, context_block::instance($block1->id));
2154         // Add tons of overrides - the more the better.
2155         assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultuserroleid, $frontpageblockcontext, true);
2156         assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpageblockcontext, true);
2157         assign_capability('moodle/block:view', CAP_PROHIBIT, $allroles['guest'], $frontpageblockcontext, true);
2158         assign_capability('block/online_users:viewlist', CAP_PREVENT, $allroles['user'], $frontpageblockcontext, true);
2159         assign_capability('block/online_users:viewlist', CAP_PREVENT, $allroles['student'], $frontpageblockcontext, true);
2161         assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $CFG->defaultuserroleid, $frontpagepagecontext, true);
2162         assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpagepagecontext, true);
2163         assign_capability('mod/page:view', CAP_PREVENT, $allroles['guest'], $frontpagepagecontext, true);
2164         assign_capability('mod/page:view', CAP_ALLOW, $allroles['user'], $frontpagepagecontext, true);
2165         assign_capability('moodle/page:view', CAP_ALLOW, $allroles['student'], $frontpagepagecontext, true);
2167         assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultuserroleid, $frontpagecontext, true);
2168         assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpagecontext, true);
2169         assign_capability('mod/page:view', CAP_ALLOW, $allroles['guest'], $frontpagecontext, true);
2170         assign_capability('mod/page:view', CAP_PROHIBIT, $allroles['user'], $frontpagecontext, true);
2172         assign_capability('mod/page:view', CAP_PREVENT, $allroles['guest'], $systemcontext, true);
2174         accesslib_clear_all_caches(false); // Must be done after assign_capability().
2176         // Extra tests for guests and not-logged-in users because they can not be verified by cross checking
2177         // with get_users_by_capability() where they are ignored.
2178         $this->assertFalse(has_capability('moodle/block:view', $frontpageblockcontext, $guestid));
2179         $this->assertFalse(has_capability('mod/page:view', $frontpagepagecontext, $guestid));
2180         $this->assertTrue(has_capability('mod/page:view', $frontpagecontext, $guestid));
2181         $this->assertFalse(has_capability('mod/page:view', $systemcontext, $guestid));
2183         $this->assertFalse(has_capability('moodle/block:view', $frontpageblockcontext, 0));
2184         $this->assertFalse(has_capability('mod/page:view', $frontpagepagecontext, 0));
2185         $this->assertTrue(has_capability('mod/page:view', $frontpagecontext, 0));
2186         $this->assertFalse(has_capability('mod/page:view', $systemcontext, 0));
2188         $this->assertFalse(has_capability('moodle/course:create', $systemcontext, $testusers[11]));
2189         $this->assertTrue(has_capability('moodle/course:create', context_coursecat::instance($testcategories[2]), $testusers[11]));
2190         $this->assertFalse(has_capability('moodle/course:create', context_course::instance($testcourses[1]), $testusers[11]));
2191         $this->assertTrue(has_capability('moodle/course:create', context_course::instance($testcourses[19]), $testusers[11]));
2193         $this->assertFalse(has_capability('moodle/course:update', context_course::instance($testcourses[1]), $testusers[9]));
2194         $this->assertFalse(has_capability('moodle/course:update', context_course::instance($testcourses[19]), $testusers[9]));
2195         $this->assertFalse(has_capability('moodle/course:update', $systemcontext, $testusers[9]));
2197         // Test the list of enrolled users.
2198         $coursecontext = context_course::instance($course1->id);
2199         $enrolled = get_enrolled_users($coursecontext);
2200         $this->assertCount(10, $enrolled);
2201         for ($i=0; $i<10; $i++) {
2202             $this->assertTrue(isset($enrolled[$testusers[$i]]));
2203         }
2204         $enrolled = get_enrolled_users($coursecontext, 'moodle/course:update');
2205         $this->assertCount(1, $enrolled);
2206         $this->assertTrue(isset($enrolled[$testusers[9]]));
2207         unset($enrolled);
2209         // Role switching.
2210         $userid = $testusers[9];
2211         $USER = $DB->get_record('user', array('id'=>$userid));
2212         load_all_capabilities();
2213         $coursecontext = context_course::instance($course1->id);
2214         $this->assertTrue(has_capability('moodle/course:update', $coursecontext));
2215         $this->assertFalse(is_role_switched($course1->id));
2216         role_switch($allroles['student'], $coursecontext);
2217         $this->assertTrue(is_role_switched($course1->id));
2218         $this->assertEquals($allroles['student'], $USER->access['rsw'][$coursecontext->path]);
2219         $this->assertFalse(has_capability('moodle/course:update', $coursecontext));
2220         reload_all_capabilities();
2221         $this->assertFalse(has_capability('moodle/course:update', $coursecontext));
2222         role_switch(0, $coursecontext);
2223         $this->assertTrue(has_capability('moodle/course:update', $coursecontext));
2224         $userid = $adminid;
2225         $USER = $DB->get_record('user', array('id'=>$userid));
2226         load_all_capabilities();
2227         $coursecontext = context_course::instance($course1->id);
2228         $blockcontext = context_block::instance($block1->id);
2229         $this->assertTrue(has_capability('moodle/course:update', $blockcontext));
2230         role_switch($allroles['student'], $coursecontext);
2231         $this->assertEquals($allroles['student'], $USER->access['rsw'][$coursecontext->path]);
2232         $this->assertFalse(has_capability('moodle/course:update', $blockcontext));
2233         reload_all_capabilities();
2234         $this->assertFalse(has_capability('moodle/course:update', $blockcontext));
2235         load_all_capabilities();
2236         $this->assertTrue(has_capability('moodle/course:update', $blockcontext));
2238         // Temp course role for enrol.
2239         $DB->delete_records('cache_flags', array()); // This prevents problem with dirty contexts immediately resetting the temp role - this is a known problem...
2240         $userid = $testusers[5];
2241         $roleid = $allroles['editingteacher'];
2242         $USER = $DB->get_record('user', array('id'=>$userid));
2243         load_all_capabilities();
2244         $coursecontext = context_course::instance($course1->id);
2245         $this->assertFalse(has_capability('moodle/course:update', $coursecontext));
2246         $this->assertFalse(isset($USER->access['ra'][$coursecontext->path][$roleid]));
2247         load_temp_course_role($coursecontext, $roleid);
2248         $this->assertEquals($USER->access['ra'][$coursecontext->path][$roleid], $roleid);
2249         $this->assertTrue(has_capability('moodle/course:update', $coursecontext));
2250         remove_temp_course_roles($coursecontext);
2251         $this->assertFalse(has_capability('moodle/course:update', $coursecontext, $userid));
2252         load_temp_course_role($coursecontext, $roleid);
2253         reload_all_capabilities();
2254         $this->assertFalse(has_capability('moodle/course:update', $coursecontext, $userid));
2255         $USER = new stdClass();
2256         $USER->id = 0;
2258         // Now cross check has_capability() with get_users_by_capability(), each using different code paths,
2259         // they have to be kept in sync, usually only one of them breaks, so we know when something is wrong,
2260         // at the same time validate extra restrictions (guest read only no risks, admin exception, non existent and deleted users).
2261         $contexts = $DB->get_records('context', array(), 'id');
2262         $contexts = array_values($contexts);
2263         $capabilities = $DB->get_records('capabilities', array(), 'id');
2264         $capabilities = array_values($capabilities);
2265         $roles = array($allroles['guest'], $allroles['user'], $allroles['teacher'], $allroles['editingteacher'], $allroles['coursecreator'], $allroles['manager']);
2266         $userids = array_values($testusers);
2267         $userids[] = get_admin()->id;
2269         if (!PHPUNIT_LONGTEST) {
2270             $contexts = array_slice($contexts, 0, 10);
2271             $capabilities = array_slice($capabilities, 0, 5);
2272             $userids = array_slice($userids, 0, 5);
2273         }
2275         // Random time!
2276         // srand(666);
2277         foreach ($userids as $userid) { // No guest or deleted.
2278             // Each user gets 0-10 random roles.
2279             $rcount = rand(0, 10);
2280             for ($j=0; $j<$rcount; $j++) {
2281                 $roleid = $roles[rand(0, count($roles)-1)];
2282                 $contextid = $contexts[rand(0, count($contexts)-1)]->id;
2283                 role_assign($roleid, $userid, $contextid);
2284             }
2285         }
2287         $permissions = array(CAP_ALLOW, CAP_PREVENT, CAP_INHERIT, CAP_PREVENT);
2288         $maxoverrides = count($contexts)*10;
2289         for ($j=0; $j<$maxoverrides; $j++) {
2290             $roleid = $roles[rand(0, count($roles)-1)];
2291             $contextid = $contexts[rand(0, count($contexts)-1)]->id;
2292             $permission = $permissions[rand(0, count($permissions)-1)];
2293             $capname = $capabilities[rand(0, count($capabilities)-1)]->name;
2294             assign_capability($capname, $permission, $roleid, $contextid, true);
2295         }
2296         unset($permissions);
2297         unset($roles);
2299         accesslib_clear_all_caches(false); // Must be done after assign_capability().
2301         // Test time - let's set up some real user, just in case the logic for USER affects the others...
2302         $USER = $DB->get_record('user', array('id'=>$testusers[3]));
2303         load_all_capabilities();
2305         $userids[] = $CFG->siteguest;
2306         $userids[] = 0; // Not-logged-in user.
2307         $userids[] = -1; // Non-existent user.
2309         foreach ($contexts as $crecord) {
2310             $context = context::instance_by_id($crecord->id);
2311             if ($coursecontext = $context->get_course_context(false)) {
2312                 $enrolled = get_enrolled_users($context);
2313             } else {
2314                 $enrolled = array();
2315             }
2316             foreach ($capabilities as $cap) {
2317                 $allowed = get_users_by_capability($context, $cap->name, 'u.id, u.username');
2318                 if ($enrolled) {
2319                     $enrolledwithcap = get_enrolled_users($context, $cap->name);
2320                 } else {
2321                     $enrolledwithcap = array();
2322                 }
2323                 foreach ($userids as $userid) {
2324                     if ($userid == 0 or isguestuser($userid)) {
2325                         if ($userid == 0) {
2326                             $CFG->forcelogin = true;
2327                             $this->assertFalse(has_capability($cap->name, $context, $userid));
2328                             unset($CFG->forcelogin);
2329                         }
2330                         if (($cap->captype === 'write') or ($cap->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
2331                             $this->assertFalse(has_capability($cap->name, $context, $userid));
2332                         }
2333                         $this->assertFalse(isset($allowed[$userid]));
2334                     } else {
2335                         if (is_siteadmin($userid)) {
2336                             $this->assertTrue(has_capability($cap->name, $context, $userid, true));
2337                         }
2338                         $hascap = has_capability($cap->name, $context, $userid, false);
2339                         $this->assertSame($hascap, isset($allowed[$userid]), "Capability result mismatch user:$userid, context:$context->id, $cap->name, hascap: ".(int)$hascap." ");
2340                         if (isset($enrolled[$userid])) {
2341                             $this->assertSame(isset($allowed[$userid]), isset($enrolledwithcap[$userid]), "Enrolment with capability result mismatch user:$userid, context:$context->id, $cap->name, hascap: ".(int)$hascap." ");
2342                         }
2343                     }
2344                 }
2345             }
2346         }
2347         // Back to nobody.
2348         $USER = new stdClass();
2349         $USER->id = 0;
2350         unset($contexts);
2351         unset($userids);
2352         unset($capabilities);
2354         // Now let's do all the remaining tests that break our carefully prepared fake site.
2357         // Test $context->mark_dirty() method.
2359         $DB->delete_records('cache_flags', array());
2360         accesslib_clear_all_caches(false);
2361         $systemcontext->mark_dirty();
2362         $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2);
2363         $this->assertTrue(isset($dirty[$systemcontext->path]));
2364         $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$systemcontext->path]));
2367         // Test $context->reload_if_dirty() method.
2369         $DB->delete_records('cache_flags', array());
2370         accesslib_clear_all_caches(false);
2371         load_all_capabilities();
2372         $context = context_course::instance($testcourses[2]);
2373         $page = $DB->get_record('page', array('course'=>$testcourses[2]));
2374         $pagecm = get_coursemodule_from_instance('page', $page->id);
2375         $pagecontext = context_module::instance($pagecm->id);
2377         $context->mark_dirty();
2378         $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$context->path]));
2379         $USER->access['test'] = true;
2380         $context->reload_if_dirty();
2381         $this->assertFalse(isset($USER->access['test']));
2383         $context->mark_dirty();
2384         $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$context->path]));
2385         $USER->access['test'] = true;
2386         $pagecontext->reload_if_dirty();
2387         $this->assertFalse(isset($USER->access['test']));
2390         // Test context_helper::build_all_paths() method.
2392         $oldcontexts = $DB->get_records('context', array(), 'id');
2393         $DB->set_field_select('context', 'path', null, "contextlevel <> ".CONTEXT_SYSTEM);
2394         $DB->set_field_select('context', 'depth', 0, "contextlevel <> ".CONTEXT_SYSTEM);
2395         context_helper::build_all_paths();
2396         $newcontexts = $DB->get_records('context', array(), 'id');
2397         $this->assertEquals($oldcontexts, $newcontexts);
2398         unset($oldcontexts);
2399         unset($newcontexts);
2402         // Test $context->reset_paths() method.
2404         $context = context_course::instance($testcourses[2]);
2405         $children = $context->get_child_contexts();
2406         $context->reset_paths(false);
2407         $this->assertNull($DB->get_field('context', 'path', array('id'=>$context->id)));
2408         $this->assertEquals(0, $DB->get_field('context', 'depth', array('id'=>$context->id)));
2409         foreach ($children as $child) {
2410             $this->assertNull($DB->get_field('context', 'path', array('id'=>$child->id)));
2411             $this->assertEquals(0, $DB->get_field('context', 'depth', array('id'=>$child->id)));
2412         }
2413         $this->assertEquals(count($children)+1, $DB->count_records('context', array('depth'=>0)));
2414         $this->assertEquals(count($children)+1, $DB->count_records('context', array('path'=>null)));
2416         $context = context_course::instance($testcourses[2]);
2417         $context->reset_paths(true);
2418         $context = context_course::instance($testcourses[2]);
2419         $this->assertSame($context->path, $DB->get_field('context', 'path', array('id'=>$context->id)));
2420         $this->assertSame($context->depth, $DB->get_field('context', 'depth', array('id'=>$context->id)));
2421         $this->assertEquals(0, $DB->count_records('context', array('depth'=>0)));
2422         $this->assertEquals(0, $DB->count_records('context', array('path'=>null)));
2425         // Test $context->update_moved() method.
2427         accesslib_clear_all_caches(false);
2428         $DB->delete_records('cache_flags', array());
2429         $course = $DB->get_record('course', array('id'=>$testcourses[0]));
2430         $context = context_course::instance($course->id);
2431         $oldpath = $context->path;
2432         $miscid = $DB->get_field_sql("SELECT MIN(id) FROM {course_categories}");
2433         $categorycontext = context_coursecat::instance($miscid);
2434         $course->category = $miscid;
2435         $DB->update_record('course', $course);
2436         $context->update_moved($categorycontext);
2438         $context = context_course::instance($course->id);
2439         $this->assertEquals($categorycontext, $context->get_parent_context());
2440         $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2);
2441         $this->assertTrue(isset($dirty[$oldpath]));
2442         $this->assertTrue(isset($dirty[$context->path]));
2445         // Test $context->delete_content() method.
2447         context_helper::reset_caches();
2448         $context = context_module::instance($testpages[3]);
2449         $this->assertTrue($DB->record_exists('context', array('id'=>$context->id)));
2450         $this->assertEquals(1, $DB->count_records('block_instances', array('parentcontextid'=>$context->id)));
2451         $context->delete_content();
2452         $this->assertTrue($DB->record_exists('context', array('id'=>$context->id)));
2453         $this->assertEquals(0, $DB->count_records('block_instances', array('parentcontextid'=>$context->id)));
2456         // Test $context->delete() method.
2458         context_helper::reset_caches();
2459         $context = context_module::instance($testpages[4]);
2460         $this->assertTrue($DB->record_exists('context', array('id'=>$context->id)));
2461         $this->assertEquals(1, $DB->count_records('block_instances', array('parentcontextid'=>$context->id)));
2462         $bi = $DB->get_record('block_instances', array('parentcontextid'=>$context->id));
2463         $bicontext = context_block::instance($bi->id);
2464         $DB->delete_records('cache_flags', array());
2465         $context->delete(); // Should delete also linked blocks.
2466         $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2);
2467         $this->assertTrue(isset($dirty[$context->path]));
2468         $this->assertFalse($DB->record_exists('context', array('id'=>$context->id)));
2469         $this->assertFalse($DB->record_exists('context', array('id'=>$bicontext->id)));
2470         $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$testpages[4])));
2471         $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$bi->id)));
2472         $this->assertEquals(0, $DB->count_records('block_instances', array('parentcontextid'=>$context->id)));
2473         context_module::instance($testpages[4]);
2476         // Test context_helper::delete_instance() method.
2478         context_helper::reset_caches();
2479         $lastcourse = array_pop($testcourses);
2480         $this->assertTrue($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$lastcourse)));
2481         $coursecontext = context_course::instance($lastcourse);
2482         $this->assertEquals(1, context_inspection::test_context_cache_size());
2483         $this->assertNotEquals(CONTEXT_COURSE, $coursecontext->instanceid);
2484         $DB->delete_records('cache_flags', array());
2485         context_helper::delete_instance(CONTEXT_COURSE, $lastcourse);
2486         $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2);
2487         $this->assertTrue(isset($dirty[$coursecontext->path]));
2488         $this->assertEquals(0, context_inspection::test_context_cache_size());
2489         $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$lastcourse)));
2490         context_course::instance($lastcourse);
2493         // Test context_helper::create_instances() method.
2495         $prevcount = $DB->count_records('context');
2496         $DB->delete_records('context', array('contextlevel'=>CONTEXT_BLOCK));
2497         context_helper::create_instances(null, true);
2498         $this->assertSame($DB->count_records('context'), $prevcount);
2499         $this->assertEquals(0, $DB->count_records('context', array('depth'=>0)));
2500         $this->assertEquals(0, $DB->count_records('context', array('path'=>null)));
2502         $DB->delete_records('context', array('contextlevel'=>CONTEXT_BLOCK));
2503         $DB->delete_records('block_instances', array());
2504         $prevcount = $DB->count_records('context');
2505         $DB->delete_records_select('context', 'contextlevel <> '.CONTEXT_SYSTEM);
2506         context_helper::create_instances(null, true);
2507         $this->assertSame($prevcount, $DB->count_records('context'));
2508         $this->assertEquals(0, $DB->count_records('context', array('depth'=>0)));
2509         $this->assertEquals(0, $DB->count_records('context', array('path'=>null)));
2511         // Test context_helper::cleanup_instances() method.
2513         $lastcourse = $DB->get_field_sql("SELECT MAX(id) FROM {course}");
2514         $DB->delete_records('course', array('id'=>$lastcourse));
2515         $lastcategory = $DB->get_field_sql("SELECT MAX(id) FROM {course_categories}");
2516         $DB->delete_records('course_categories', array('id'=>$lastcategory));
2517         $lastuser = $DB->get_field_sql("SELECT MAX(id) FROM {user} WHERE deleted=0");
2518         $DB->delete_records('user', array('id'=>$lastuser));
2519         $DB->delete_records('block_instances', array('parentcontextid'=>$frontpagepagecontext->id));
2520         $DB->delete_records('course_modules', array('id'=>$frontpagepagecontext->instanceid));
2521         context_helper::cleanup_instances();
2522         $count = 1; // System.
2523         $count += $DB->count_records('user', array('deleted'=>0));
2524         $count += $DB->count_records('course_categories');
2525         $count += $DB->count_records('course');
2526         $count += $DB->count_records('course_modules');
2527         $count += $DB->count_records('block_instances');
2528         $this->assertEquals($count, $DB->count_records('context'));
2531         // Test context cache size restrictions.
2533         $testusers= array();
2534         for ($i=0; $i<CONTEXT_CACHE_MAX_SIZE + 100; $i++) {
2535             $user = $generator->create_user();
2536             $testusers[$i] = $user->id;
2537         }
2538         context_helper::create_instances(null, true);
2539         context_helper::reset_caches();
2540         for ($i=0; $i<CONTEXT_CACHE_MAX_SIZE + 100; $i++) {
2541             context_user::instance($testusers[$i]);
2542             if ($i == CONTEXT_CACHE_MAX_SIZE - 1) {
2543                 $this->assertEquals(CONTEXT_CACHE_MAX_SIZE, context_inspection::test_context_cache_size());
2544             } else if ($i == CONTEXT_CACHE_MAX_SIZE) {
2545                 // Once the limit is reached roughly 1/3 of records should be removed from cache.
2546                 $this->assertEquals((int)ceil(CONTEXT_CACHE_MAX_SIZE * (2/3) + 101), context_inspection::test_context_cache_size());
2547             }
2548         }
2549         // We keep the first 100 cached.
2550         $prevsize = context_inspection::test_context_cache_size();
2551         for ($i=0; $i<100; $i++) {
2552             context_user::instance($testusers[$i]);
2553             $this->assertEquals($prevsize, context_inspection::test_context_cache_size());
2554         }
2555         context_user::instance($testusers[102]);
2556         $this->assertEquals($prevsize+1, context_inspection::test_context_cache_size());
2557         unset($testusers);
2561         // Test basic test of legacy functions.
2562         // Note: watch out, the fake site might be pretty borked already.
2564         $this->assertEquals(get_system_context(), context_system::instance());
2566         foreach ($DB->get_records('context') as $contextid => $record) {
2567             $context = context::instance_by_id($contextid);
2568             $this->assertEquals($context, get_context_instance_by_id($contextid, IGNORE_MISSING));
2569             $this->assertEquals($context, get_context_instance($record->contextlevel, $record->instanceid));
2570             $this->assertEquals($context->get_parent_context_ids(), get_parent_contexts($context));
2571             if ($context->id == SYSCONTEXTID) {
2572                 $this->assertFalse(get_parent_contextid($context));
2573             } else {
2574                 $this->assertSame($context->get_parent_context()->id, get_parent_contextid($context));
2575             }
2576         }
2578         $children = get_child_contexts($systemcontext);
2579         // Using assertEquals here as assertSame fails for some reason...
2580         $this->assertEquals($children, $systemcontext->get_child_contexts());
2581         $this->assertEquals(count($children), $DB->count_records('context')-1);
2582         $this->resetDebugging();
2583         unset($children);
2585         // Make sure a debugging is thrown.
2586         get_context_instance($record->contextlevel, $record->instanceid);
2587         $this->assertDebuggingCalled('get_context_instance() is deprecated, please use context_xxxx::instance() instead.', DEBUG_DEVELOPER);
2588         get_context_instance_by_id($record->id);
2589         $this->assertDebuggingCalled('get_context_instance_by_id() is deprecated, please use context::instance_by_id($id) instead.', DEBUG_DEVELOPER);
2590         get_system_context();
2591         $this->assertDebuggingCalled('get_system_context() is deprecated, please use context_system::instance() instead.', DEBUG_DEVELOPER);
2592         get_parent_contexts($context);
2593         $this->assertDebuggingCalled('get_parent_contexts() is deprecated, please use $context->get_parent_context_ids() instead.', DEBUG_DEVELOPER);
2594         get_parent_contextid($context);
2595         $this->assertDebuggingCalled('get_parent_contextid() is deprecated, please use $context->get_parent_context() instead.', DEBUG_DEVELOPER);
2596         get_child_contexts($frontpagecontext);
2597         $this->assertDebuggingCalled('get_child_contexts() is deprecated, please use $context->get_child_contexts() instead.', DEBUG_DEVELOPER);
2599         $DB->delete_records('context', array('contextlevel'=>CONTEXT_BLOCK));
2600         create_contexts();
2601         $this->assertDebuggingCalled('create_contexts() is deprecated, please use context_helper::create_instances() instead.', DEBUG_DEVELOPER);
2602         $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_BLOCK)));
2604         $DB->set_field('context', 'depth', 0, array('contextlevel'=>CONTEXT_BLOCK));
2605         build_context_path();
2606         $this->assertDebuggingCalled('build_context_path() is deprecated, please use context_helper::build_all_paths() instead.', DEBUG_DEVELOPER);
2607         $this->assertFalse($DB->record_exists('context', array('depth'=>0)));
2609         $lastcourse = $DB->get_field_sql("SELECT MAX(id) FROM {course}");
2610         $DB->delete_records('course', array('id'=>$lastcourse));
2611         $lastcategory = $DB->get_field_sql("SELECT MAX(id) FROM {course_categories}");
2612         $DB->delete_records('course_categories', array('id'=>$lastcategory));
2613         $lastuser = $DB->get_field_sql("SELECT MAX(id) FROM {user} WHERE deleted=0");
2614         $DB->delete_records('user', array('id'=>$lastuser));
2615         $DB->delete_records('block_instances', array('parentcontextid'=>$frontpagepagecontext->id));
2616         $DB->delete_records('course_modules', array('id'=>$frontpagepagecontext->instanceid));
2617         cleanup_contexts();
2618         $this->assertDebuggingCalled('cleanup_contexts() is deprecated, please use context_helper::cleanup_instances() instead.', DEBUG_DEVELOPER);
2619         $count = 1; // System.
2620         $count += $DB->count_records('user', array('deleted'=>0));
2621         $count += $DB->count_records('course_categories');
2622         $count += $DB->count_records('course');
2623         $count += $DB->count_records('course_modules');
2624         $count += $DB->count_records('block_instances');
2625         $this->assertEquals($count, $DB->count_records('context'));
2627         // Test legacy rebuild_contexts().
2628         $context = context_course::instance($testcourses[2]);
2629         rebuild_contexts(array($context));
2630         $this->assertDebuggingCalled('rebuild_contexts() is deprecated, please use $context->reset_paths(true) instead.', DEBUG_DEVELOPER);
2631         $context = context_course::instance($testcourses[2]);
2632         $this->assertSame($context->path, $DB->get_field('context', 'path', array('id' => $context->id)));
2633         $this->assertSame($context->depth, $DB->get_field('context', 'depth', array('id' => $context->id)));
2634         $this->assertEquals(0, $DB->count_records('context', array('depth' => 0)));
2635         $this->assertEquals(0, $DB->count_records('context', array('path' => null)));
2637         context_helper::reset_caches();
2638         preload_course_contexts($SITE->id);
2639         $this->assertDebuggingCalled('preload_course_contexts() is deprecated, please use context_helper::preload_course() instead.', DEBUG_DEVELOPER);
2640         $this->assertEquals(1 + $DB->count_records('course_modules', array('course' => $SITE->id)),
2641                 context_inspection::test_context_cache_size());
2643         context_helper::reset_caches();
2644         list($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSECAT, 'ctx');
2645         $this->assertDebuggingCalled('context_instance_preload_sql() is deprecated, please use context_helper::get_preload_record_columns_sql() instead.', DEBUG_DEVELOPER);
2646         $this->assertEquals(', ' . context_helper::get_preload_record_columns_sql('ctx'), $select);
2647         $this->assertEquals('LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = ' . CONTEXT_COURSECAT . ')', $join);
2648         $sql = "SELECT c.id $select FROM {course_categories} c $join";
2649         $records = $DB->get_records_sql($sql);
2650         foreach ($records as $record) {
2651             context_instance_preload($record);
2652             $this->assertDebuggingCalled('context_instance_preload() is deprecated, please use context_helper::preload_from_record() instead.',
2653                     DEBUG_DEVELOPER);
2654             $record = (array)$record;
2655             $this->assertEquals(1, count($record)); // Only id left.
2656         }
2657         $this->assertEquals(count($records), context_inspection::test_context_cache_size());
2659         accesslib_clear_all_caches(true);
2660         $DB->delete_records('cache_flags', array());
2661         mark_context_dirty($systemcontext->path);
2662         $this->assertDebuggingCalled('mark_context_dirty() is deprecated, please use $context->mark_dirty() instead.', DEBUG_DEVELOPER);
2663         $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2);
2664         $this->assertTrue(isset($dirty[$systemcontext->path]));
2666         accesslib_clear_all_caches(false);
2667         $DB->delete_records('cache_flags', array());
2668         $course = $DB->get_record('course', array('id'=>$testcourses[2]));
2669         $context = context_course::instance($course->id);
2670         $oldpath = $context->path;
2671         $miscid = $DB->get_field_sql("SELECT MIN(id) FROM {course_categories}");
2672         $categorycontext = context_coursecat::instance($miscid);
2673         $course->category = $miscid;
2674         $DB->update_record('course', $course);
2675         context_moved($context, $categorycontext);
2676         $this->assertDebuggingCalled('context_moved() is deprecated, please use context::update_moved() instead.', DEBUG_DEVELOPER);
2677         $context = context_course::instance($course->id);
2678         $this->assertEquals($categorycontext, $context->get_parent_context());
2680         $this->assertTrue($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$testcourses[2])));
2681         delete_context(CONTEXT_COURSE, $testcourses[2]);
2682         $this->assertDebuggingCalled('delete_context() is deprecated, please use context_helper::delete_instance() instead.', DEBUG_DEVELOPER);
2683         $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$testcourses[2])));
2684         delete_context(CONTEXT_COURSE, $testcourses[2], false);
2685         $this->assertDebuggingCalled('delete_context() is deprecated, please use $context->delete_content() instead.', DEBUG_DEVELOPER);
2687         $name = get_contextlevel_name(CONTEXT_COURSE);
2688         $this->assertDebuggingCalled('get_contextlevel_name() is deprecated, please use context_helper::get_level_name() instead.', DEBUG_DEVELOPER);
2689         $this->assertFalse(empty($name));
2691         $context = context_course::instance($testcourses[2]);
2692         $name = print_context_name($context);
2693         $this->assertDebuggingCalled('print_context_name() is deprecated, please use $context->get_context_name() instead.', DEBUG_DEVELOPER);
2694         $this->assertFalse(empty($name));
2696         $url1 = get_context_url($coursecontext);
2697         $this->assertDebuggingCalled('get_context_url() is deprecated, please use $context->get_url() instead.', DEBUG_DEVELOPER);
2698         $url2 = $coursecontext->get_url();
2699         $this->assertEquals($url1, $url2);
2700         $this->assertInstanceOf('moodle_url', $url2);
2702         $pagecm = get_coursemodule_from_instance('page', $testpages[7]);
2703         $context = context_module::instance($pagecm->id);
2704         $coursecontext1 = get_course_context($context);
2705         $this->assertDebuggingCalled('get_course_context() is deprecated, please use $context->get_course_context(true) instead.', DEBUG_DEVELOPER);
2706         $coursecontext2 = $context->get_course_context(true);
2707         $this->assertEquals($coursecontext1, $coursecontext2);
2708         $this->assertEquals(CONTEXT_COURSE, $coursecontext2->contextlevel);
2709         $this->assertEquals($pagecm->course, get_courseid_from_context($context));
2710         $this->assertDebuggingCalled('get_courseid_from_context() is deprecated, please use $context->get_course_context(false) instead.', DEBUG_DEVELOPER);
2712         $caps = fetch_context_capabilities($systemcontext);
2713         $this->assertDebuggingCalled('fetch_context_capabilities() is deprecated, please use $context->get_capabilities() instead.', DEBUG_DEVELOPER);
2714         $this->assertEquals($caps, $systemcontext->get_capabilities());
2715         unset($caps);
2716     }
2718     /**
2719      * Test updating of role capabilities during upgrade
2720      */
2721     public function test_update_capabilities() {
2722         global $DB, $SITE;
2724         $this->resetAfterTest(true);
2726         $froncontext = context_course::instance($SITE->id);
2727         $student = $DB->get_record('role', array('archetype'=>'student'));
2728         $teacher = $DB->get_record('role', array('archetype'=>'teacher'));
2730         $existingcaps = $DB->get_records('capabilities', array(), 'id', 'name, captype, contextlevel, component, riskbitmask');
2732         $this->assertFalse(isset($existingcaps['moodle/site:restore']));         // Moved to new 'moodle/restore:restorecourse'.
2733         $this->assertTrue(isset($existingcaps['moodle/restore:restorecourse'])); // New cap from 'moodle/site:restore'.
2734         $this->assertTrue(isset($existingcaps['moodle/site:sendmessage']));      // New capability.
2735         $this->assertTrue(isset($existingcaps['moodle/backup:backupcourse']));
2736         $this->assertTrue(isset($existingcaps['moodle/backup:backupsection']));  // Cloned from 'moodle/backup:backupcourse'.
2737         $this->assertTrue(isset($existingcaps['moodle/site:approvecourse']));    // Updated bitmask.
2738         $this->assertTrue(isset($existingcaps['moodle/course:manageactivities']));
2739         $this->assertTrue(isset($existingcaps['mod/page:addinstance']));         // Cloned from core 'moodle/course:manageactivities'.
2741         // Fake state before upgrade.
2742         $DB->set_field('capabilities', 'name', 'moodle/site:restore', array('name'=>'moodle/restore:restorecourse'));
2743         $DB->set_field('role_capabilities', 'capability', 'moodle/site:restore', array('capability'=>'moodle/restore:restorecourse'));
2744         assign_capability('moodle/site:restore', CAP_PROHIBIT, $teacher->id, $froncontext->id, true);
2745         $perms1 = array_values($DB->get_records('role_capabilities', array('capability'=>'moodle/site:restore', 'roleid'=>$teacher->id), 'contextid, permission', 'contextid, permission'));
2747         $DB->delete_records('role_capabilities', array('capability'=>'moodle/site:sendmessage'));
2748         $DB->delete_records('capabilities', array('name'=>'moodle/site:sendmessage'));
2750         $DB->delete_records('role_capabilities', array('capability'=>'moodle/backup:backupsection'));
2751         $DB->delete_records('capabilities', array('name'=>'moodle/backup:backupsection'));
2752         assign_capability('moodle/backup:backupcourse', CAP_PROHIBIT, $student->id, $froncontext->id, true);
2753         assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $teacher->id, $froncontext->id, true);
2755         $DB->set_field('capabilities', 'riskbitmask', 0, array('name'=>'moodle/site:approvecourse'));
2757         $DB->delete_records('role_capabilities', array('capability'=>'mod/page:addinstance'));
2758         $DB->delete_records('capabilities', array('name'=>'mod/page:addinstance'));
2759         assign_capability('moodle/course:manageactivities', CAP_PROHIBIT, $student->id, $froncontext->id, true);
2760         assign_capability('moodle/course:manageactivities', CAP_ALLOW, $teacher->id, $froncontext->id, true);
2762         // Execute core.
2763         update_capabilities('moodle');
2765         // Only core should be upgraded.
2766         $caps = $DB->get_records('capabilities', array(), 'id', 'name, captype, contextlevel, component, riskbitmask');
2768         $this->assertFalse(isset($existingcaps['moodle/site:restore']));
2769         $this->assertTrue(isset($caps['moodle/restore:restorecourse']));
2770         $this->assertEquals($existingcaps['moodle/restore:restorecourse'], $caps['moodle/restore:restorecourse']);
2771         $perms2 = array_values($DB->get_records('role_capabilities', array('capability'=>'moodle/restore:restorecourse', 'roleid'=>$teacher->id), 'contextid, permission', 'contextid, permission'));
2772         $this->assertEquals($perms1, $perms2);
2774         $this->assertTrue(isset($caps['moodle/site:sendmessage']));
2775         $this->assertEquals($existingcaps['moodle/site:sendmessage'], $caps['moodle/site:sendmessage']);
2777         $this->assertTrue(isset($caps['moodle/backup:backupsection']));
2778         $this->assertEquals($existingcaps['moodle/backup:backupsection'], $caps['moodle/backup:backupsection']);
2779         $roles = $DB->get_records_sql('SELECT DISTINCT roleid AS id FROM {role_capabilities} WHERE capability=? OR capability=?', array('moodle/backup:backupcourse', 'moodle/backup:backupsection'));
2780         foreach ($roles as $role) {
2781             $perms1 = array_values($DB->get_records('role_capabilities', array('capability'=>'moodle/backup:backupcourse', 'roleid'=>$role->id), 'contextid, permission', 'contextid, permission'));
2782             $perms2 = array_values($DB->get_records('role_capabilities', array('capability'=>'moodle/backup:backupsection', 'roleid'=>$role->id), 'contextid, permission', 'contextid, permission'));
2783             $this->assertEquals($perms1, $perms2);
2784         }
2786         $this->assertTrue(isset($caps['moodle/site:approvecourse']));
2787         $this->assertEquals($existingcaps['moodle/site:approvecourse'], $caps['moodle/site:approvecourse']);
2789         $this->assertFalse(isset($caps['mod/page:addinstance']));
2791         // Execute plugin.
2792         update_capabilities('mod_page');
2793         $caps = $DB->get_records('capabilities', array(), 'id', 'name, captype, contextlevel, component, riskbitmask');
2794         $this->assertTrue(isset($caps['mod/page:addinstance']));
2795         $roles = $DB->get_records_sql('SELECT DISTINCT roleid AS id FROM {role_capabilities} WHERE capability=? OR capability=?', array('moodle/course:manageactivities', 'mod/page:addinstance'));
2796         foreach ($roles as $role) {
2797             $perms1 = array_values($DB->get_records('role_capabilities', array('capability'=>'moodle/course:manageactivities', 'roleid'=>$role->id), 'contextid, permission', 'contextid, permission'));
2798             $perms2 = array_values($DB->get_records('role_capabilities', array('capability'=>'mod/page:addinstance', 'roleid'=>$role->id), 'contextid, permission', 'contextid, permission'));
2799         }
2800         $this->assertEquals($perms1, $perms2);
2801     }
2804 /**
2805  * Context caching fixture
2806  */
2807 class context_inspection extends context_helper {
2808     public static function test_context_cache_size() {
2809         return self::$cache_count;
2810     }