diff --git a/cohort/externallib.php b/cohort/externallib.php index a1241f20911..83ea6249cb8 100644 --- a/cohort/externallib.php +++ b/cohort/externallib.php @@ -405,6 +405,12 @@ class core_cohort_external extends external_api { $results = $results + cohort_get_available_cohorts($context, COHORT_ALL, $limitfrom, $limitnum, $query); } } else if ($includes == 'all') { + $contextsystem = context_system::instance(); + if (!$context instanceof context_system && + !has_any_capability(['moodle/cohort:view', 'moodle/cohort:manage'], $contextsystem)) { + + throw new required_capability_exception($contextsystem, 'moodle/cohort:view', 'nopermissions', ''); + } $results = cohort_get_all_cohorts($limitfrom, $limitnum, $query); $results = $results['cohorts']; } else { diff --git a/cohort/tests/externallib_test.php b/cohort/tests/externallib_test.php index b5b0b2d96db..00907207e6f 100644 --- a/cohort/tests/externallib_test.php +++ b/cohort/tests/externallib_test.php @@ -672,6 +672,7 @@ final class externallib_test extends externallib_advanced_testcase { role_assign($userrole, $catuser->id, $catcontext->id); // Enrol user in the course. + $this->getDataGenerator()->enrol_user($creator->id, $course->id); $this->getDataGenerator()->enrol_user($courseuser->id, $course->id, 'courserole'); $syscontext = array('contextid' => \context_system::instance()->id); @@ -758,18 +759,27 @@ final class externallib_test extends externallib_advanced_testcase { $this->assertCount(4, $result['cohorts']); // A user in the course context with the system cohort:view capability. Check that all the system cohorts are returned. - $this->setUser($courseuser); $result = core_cohort_external::search_cohorts("Cohortsearch", $coursecontext, 'all'); - $this->assertCount(2, $result['cohorts']); - $this->assertEquals('Cohortsearch 1', $result['cohorts'][$cohort1->id]->name); + $this->assertCount(4, $result['cohorts']); + + // A user in the course context without the ability to view system cohorts. + $this->setUser($courseuser); + try { + $result = core_cohort_external::search_cohorts("Cohortsearch", $coursecontext, 'all'); + $this->fail('Exception expected'); + } catch (\Throwable $e) { + $this->assertInstanceOf(\required_capability_exception::class, $e); + $this->assertStringContainsString('(View site-wide cohorts)', $e->getMessage()); + } // Detect invalid parameter $includes. $this->setUser($creator); try { $result = core_cohort_external::search_cohorts("Cohortsearch", $syscontext, 'invalid'); - $this->fail('Invalid parameter includes'); - } catch (\coding_exception $e) { - // All good. + $this->fail('Exception expected'); + } catch (\Throwable $e) { + $this->assertInstanceOf(\coding_exception::class, $e); + $this->assertStringContainsString('Invalid parameter value for \'includes\'', $e->getMessage()); } } }