first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
@@ -0,0 +1,291 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Condition main class.
*
* @package availability_group
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace availability_group;
defined('MOODLE_INTERNAL') || die();
/**
* Condition main class.
*
* @package availability_group
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class condition extends \core_availability\condition {
/** @var array Array from group id => name */
protected static $groupnames = array();
/** @var int ID of group that this condition requires, or 0 = any group */
protected $groupid;
/**
* Constructor.
*
* @param \stdClass $structure Data structure from JSON decode
* @throws \coding_exception If invalid data structure.
*/
public function __construct($structure) {
// Get group id.
if (!property_exists($structure, 'id')) {
$this->groupid = 0;
} else if (is_int($structure->id)) {
$this->groupid = $structure->id;
} else {
throw new \coding_exception('Invalid ->id for group condition');
}
}
public function save() {
$result = (object)array('type' => 'group');
if ($this->groupid) {
$result->id = $this->groupid;
}
return $result;
}
public function is_available($not, \core_availability\info $info, $grabthelot, $userid) {
$course = $info->get_course();
$context = \context_course::instance($course->id);
$allow = true;
if (!has_capability('moodle/site:accessallgroups', $context, $userid)) {
// Get all groups the user belongs to.
$groups = $info->get_groups(0, $userid);
if ($this->groupid) {
$allow = in_array($this->groupid, $groups);
} else {
// No specific group. Allow if they belong to any group at all.
$allow = $groups ? true : false;
}
// The NOT condition applies before accessallgroups (i.e. if you
// set something to be available to those NOT in group X,
// people with accessallgroups can still access it even if
// they are in group X).
if ($not) {
$allow = !$allow;
}
}
return $allow;
}
public function get_description($full, $not, \core_availability\info $info) {
global $DB;
if ($this->groupid) {
// Need to get the name for the group. Unfortunately this requires
// a database query. To save queries, get all groups for course at
// once in a static cache.
$course = $info->get_course();
if (!array_key_exists($this->groupid, self::$groupnames)) {
$coursegroups = $DB->get_records(
'groups', array('courseid' => $course->id), '', 'id, name');
foreach ($coursegroups as $rec) {
self::$groupnames[$rec->id] = $rec->name;
}
}
// If it still doesn't exist, it must have been misplaced.
if (!array_key_exists($this->groupid, self::$groupnames)) {
$name = get_string('missing', 'availability_group');
} else {
// Not safe to call format_string here; use the special function to call it later.
$name = self::description_format_string(self::$groupnames[$this->groupid]);
}
} else {
return get_string($not ? 'requires_notanygroup' : 'requires_anygroup',
'availability_group');
}
return get_string($not ? 'requires_notgroup' : 'requires_group',
'availability_group', $name);
}
protected function get_debug_string() {
return $this->groupid ? '#' . $this->groupid : 'any';
}
/**
* Include this condition only if we are including groups in restore, or
* if it's a generic 'same activity' one.
*
* @param int $restoreid The restore Id.
* @param int $courseid The ID of the course.
* @param base_logger $logger The logger being used.
* @param string $name Name of item being restored.
* @param base_task $task The task being performed.
*
* @return Integer groupid
*/
public function include_after_restore($restoreid, $courseid, \base_logger $logger,
$name, \base_task $task) {
return !$this->groupid || $task->get_setting_value('groups');
}
public function update_after_restore($restoreid, $courseid, \base_logger $logger, $name) {
global $DB;
if (!$this->groupid) {
return false;
}
$rec = \restore_dbops::get_backup_ids_record($restoreid, 'group', $this->groupid);
if (!$rec || !$rec->newitemid) {
// If we are on the same course (e.g. duplicate) then we can just
// use the existing one.
if ($DB->record_exists('groups',
array('id' => $this->groupid, 'courseid' => $courseid))) {
return false;
}
// Otherwise it's a warning.
$this->groupid = -1;
$logger->process('Restored item (' . $name .
') has availability condition on group that was not restored',
\backup::LOG_WARNING);
} else {
$this->groupid = (int)$rec->newitemid;
}
return true;
}
public function update_dependency_id($table, $oldid, $newid) {
if ($table === 'groups' && (int)$this->groupid === (int)$oldid) {
$this->groupid = $newid;
return true;
} else {
return false;
}
}
/**
* Wipes the static cache used to store grouping names.
*/
public static function wipe_static_cache() {
self::$groupnames = array();
}
public function is_applied_to_user_lists() {
// Group conditions are assumed to be 'permanent', so they affect the
// display of user lists for activities.
return true;
}
public function filter_user_list(array $users, $not, \core_availability\info $info,
\core_availability\capability_checker $checker) {
global $CFG, $DB;
// If the array is empty already, just return it.
if (!$users) {
return $users;
}
require_once($CFG->libdir . '/grouplib.php');
$course = $info->get_course();
// List users for this course who match the condition.
if ($this->groupid) {
$groupusers = groups_get_members($this->groupid, 'u.id', 'u.id ASC');
} else {
$groupusers = $DB->get_records_sql("
SELECT DISTINCT gm.userid
FROM {groups} g
JOIN {groups_members} gm ON gm.groupid = g.id
WHERE g.courseid = ?", array($course->id));
}
// List users who have access all groups.
$aagusers = $checker->get_users_by_capability('moodle/site:accessallgroups');
// Filter the user list.
$result = array();
foreach ($users as $id => $user) {
// Always include users with access all groups.
if (array_key_exists($id, $aagusers)) {
$result[$id] = $user;
continue;
}
// Other users are included or not based on group membership.
$allow = array_key_exists($id, $groupusers);
if ($not) {
$allow = !$allow;
}
if ($allow) {
$result[$id] = $user;
}
}
return $result;
}
/**
* Returns a JSON object which corresponds to a condition of this type.
*
* Intended for unit testing, as normally the JSON values are constructed
* by JavaScript code.
*
* @param int $groupid Required group id (0 = any group)
* @return stdClass Object representing condition
*/
public static function get_json($groupid = 0) {
$result = (object)array('type' => 'group');
// Id is only included if set.
if ($groupid) {
$result->id = (int)$groupid;
}
return $result;
}
public function get_user_list_sql($not, \core_availability\info $info, $onlyactive) {
global $DB;
// Get enrolled users with access all groups. These always are allowed.
list($aagsql, $aagparams) = get_enrolled_sql(
$info->get_context(), 'moodle/site:accessallgroups', 0, $onlyactive);
// Get all enrolled users.
list ($enrolsql, $enrolparams) =
get_enrolled_sql($info->get_context(), '', 0, $onlyactive);
// Condition for specified or any group.
$matchparams = array();
if ($this->groupid) {
$matchsql = "SELECT 1
FROM {groups_members} gm
WHERE gm.userid = userids.id
AND gm.groupid = " .
self::unique_sql_parameter($matchparams, $this->groupid);
} else {
$matchsql = "SELECT 1
FROM {groups_members} gm
JOIN {groups} g ON g.id = gm.groupid
WHERE gm.userid = userids.id
AND g.courseid = " .
self::unique_sql_parameter($matchparams, $info->get_course()->id);
}
// Overall query combines all this.
$condition = $not ? 'NOT' : '';
$sql = "SELECT userids.id
FROM ($enrolsql) userids
WHERE (userids.id IN ($aagsql)) OR $condition EXISTS ($matchsql)";
return array($sql, array_merge($enrolparams, $aagparams, $matchparams));
}
}
@@ -0,0 +1,88 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Front-end class.
*
* @package availability_group
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace availability_group;
defined('MOODLE_INTERNAL') || die();
/**
* Front-end class.
*
* @package availability_group
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class frontend extends \core_availability\frontend {
/** @var array Array of group info for course */
protected $allgroups;
/** @var int Course id that $allgroups is for */
protected $allgroupscourseid;
protected function get_javascript_strings() {
return array('anygroup');
}
protected function get_javascript_init_params($course, \cm_info $cm = null,
\section_info $section = null) {
// Get all groups for course.
$groups = $this->get_all_groups($course->id);
// Change to JS array format and return.
$jsarray = array();
$context = \context_course::instance($course->id);
foreach ($groups as $rec) {
$jsarray[] = (object)array(
'id' => $rec->id,
'name' => format_string($rec->name, true, array('context' => $context)),
'visibility' => $rec->visibility
);
}
return array($jsarray);
}
/**
* Gets all groups for the given course.
*
* @param int $courseid Course id
* @return array Array of all the group objects
*/
protected function get_all_groups($courseid) {
global $CFG;
require_once($CFG->libdir . '/grouplib.php');
if ($courseid != $this->allgroupscourseid) {
$this->allgroups = groups_get_all_groups($courseid, 0, 0, 'g.id, g.name');
$this->allgroupscourseid = $courseid;
}
return $this->allgroups;
}
protected function allow_add($course, \cm_info $cm = null,
\section_info $section = null) {
global $CFG;
// Only show this option if there are some groups.
return count($this->get_all_groups($course->id)) > 0;
}
}
@@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for availability_group.
*
* @package availability_group
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace availability_group\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for availability_group implementing null_provider.
*
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason(): string {
return 'privacy:metadata';
}
}
@@ -0,0 +1,35 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Language strings.
*
* @package availability_group
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['anygroup'] = '(Any group)';
$string['description'] = 'Allow only students who belong to a specified group, or all groups.';
$string['missing'] = '(Missing group)';
$string['pluginname'] = 'Restriction by group';
$string['error_selectgroup'] = 'You must select a group.';
$string['requires_anygroup'] = 'You belong to any group';
$string['requires_group'] = 'You belong to <strong>{$a}</strong>';
$string['requires_notanygroup'] = 'You do not belong to any group';
$string['requires_notgroup'] = 'You do not belong to <strong>{$a}</strong>';
$string['title'] = 'Group';
$string['privacy:metadata'] = 'The Restriction by group plugin does not store any personal data.';
@@ -0,0 +1,156 @@
@availability @availability_group
Feature: availability_group
In order to control student access to activities
As a teacher
I need to set group conditions which prevent student access
Background:
Given the following "courses" exist:
| fullname | shortname | format | enablecompletion | numsections |
| Course 1 | C1 | topics | 1 | 3 |
And the following "users" exist:
| username |
| teacher1 |
| student1 |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
And the following "activities" exist:
| activity | course | name |
| page | C1 | P1 |
| page | C1 | P2 |
| page | C1 | P3 |
@javascript
Scenario: Test condition
# Basic setup.
Given I am on the "P1" "page activity editing" page logged in as "teacher1"
And I expand all fieldsets
And I click on "Add restriction..." "button"
Then "Group" "button" should not exist in the "Add restriction..." "dialogue"
And I click on "Cancel" "button" in the "Add restriction..." "dialogue"
# Back to course page but add groups.
Given the following "groups" exist:
| name | course | idnumber |
| G1 | C1 | GI1 |
| G2 | C1 | GI2 |
# This step used to be 'And I follow "C1"', but Chrome thinks the breadcrumb
# is not clickable, so we'll go via the home page instead.
And I am on the "P1" "page activity editing" page
And I expand all fieldsets
And I click on "Add restriction..." "button"
Then "Group" "button" should exist in the "Add restriction..." "dialogue"
# Page P1 any group.
Given I click on "Group" "button" in the "Add restriction..." "dialogue"
And I set the field "Group" to "(Any group)"
And I click on ".availability-item .availability-eye img" "css_element"
And I click on "Save and return to course" "button"
# Page P2 with group G1.
And I am on the "P2" "page activity editing" page
And I expand all fieldsets
And I click on "Add restriction..." "button"
And I click on "Group" "button" in the "Add restriction..." "dialogue"
And I set the field "Group" to "G1"
And I click on ".availability-item .availability-eye img" "css_element"
And I click on "Save and return to course" "button"
# Page P3 with group G2
And I am on the "P3" "page activity editing" page
And I expand all fieldsets
And I click on "Add restriction..." "button"
And I click on "Group" "button" in the "Add restriction..." "dialogue"
And I set the field "Group" to "G2"
And I click on ".availability-item .availability-eye img" "css_element"
And I click on "Save and return to course" "button"
# Log back in as student.
When I am on the "Course 1" "course" page logged in as "student1"
# No pages should appear yet.
Then I should not see "P1" in the "region-main" "region"
And I should not see "P2" in the "region-main" "region"
And I should not see "P3" in the "region-main" "region"
# Add to groups and log out/in again.
Given the following "group members" exist:
| user | group |
| student1 | GI1 |
And I am on "Course 1" course homepage
# P1 (any groups) and P2 should show but not P3.
Then I should see "P1" in the "region-main" "region"
And I should see "P2" in the "region-main" "region"
And I should not see "P3" in the "region-main" "region"
@javascript
Scenario: Condition display with filters
# Teacher sets up a restriction on group G1, using multilang filter.
Given the following "groups" exist:
| name | course | idnumber |
| <span lang="en" class="multilang">G-One</span><span lang="fr" class="multilang">G-Un</span> | C1 | GI1 |
And the "multilang" filter is "on"
And the "multilang" filter applies to "content and headings"
# The activity names filter is enabled because it triggered a bug in older versions.
And the "activitynames" filter is "on"
And the "activitynames" filter applies to "content and headings"
And I am on the "P1" "page activity editing" page logged in as "teacher1"
And I expand all fieldsets
And I click on "Add restriction..." "button"
And I click on "Group" "button" in the "Add restriction..." "dialogue"
And I set the field "Group" to "G-One"
And I click on "Save and return to course" "button"
# Student sees information about no access to group, with group name in correct language.
When I am on the "C1" "Course" page logged in as "student1"
Then I should see "Not available unless: You belong to G-One"
And I should not see "G-Un"
@javascript
Scenario: Condition using a hidden group
Given the following "groups" exist:
| name | course | idnumber | visibility |
| Hidden Group | C1 | GA | 3 |
And I log in as "teacher1"
And I add a page activity to course "Course 1" section "1"
And I expand all fieldsets
# Page P1 any group.
And I am on the "P1" "page activity editing" page
And I expand all fieldsets
And I click on "Add restriction..." "button"
And "Group" "button" should exist in the "Add restriction..." "dialogue"
And I click on "Group" "button" in the "Add restriction..." "dialogue"
And I set the field "Group" to "(Any group)"
And I click on ".availability-item .availability-eye img" "css_element"
And I click on "Save and return to course" "button"
# Page P2 with hidden group.
And I am on the "P2" "page activity editing" page
And I expand all fieldsets
And I click on "Add restriction..." "button"
And I click on "Group" "button" in the "Add restriction..." "dialogue"
And I set the field "Group" to "Hidden Group"
And I click on "Save and return to course" "button"
# Log back in as student.
When I am on the "Course 1" "course" page logged in as "student1"
# No pages should appear yet.
Then I should not see "P1" in the "region-main" "region"
And I should not see "P2" in the "region-main" "region"
And I should not see "Hidden Group"
# Add to groups and log out/in again.
And the following "group members" exist:
| user | group |
| student1 | GA |
And I am on "Course 1" course homepage
# P1 (any groups) and P2 should show. The user should not see the hidden group mentioned anywhere.
And I should see "P1" in the "region-main" "region"
And I should see "P2" in the "region-main" "region"
And I should not see "Hidden Group"
@@ -0,0 +1,253 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace availability_group;
/**
* Unit tests for the condition.
*
* @package availability_group
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class condition_test extends \advanced_testcase {
/**
* Load required classes.
*/
public function setUp(): void {
// Load the mock info class so that it can be used.
global $CFG;
require_once($CFG->dirroot . '/availability/tests/fixtures/mock_info.php');
}
/**
* Tests constructing and using condition.
*/
public function test_usage(): void {
global $CFG, $USER;
$this->resetAfterTest();
$CFG->enableavailability = true;
// Erase static cache before test.
condition::wipe_static_cache();
// Make a test course and user.
$generator = $this->getDataGenerator();
$course = $generator->create_course();
$user = $generator->create_and_enrol($course);
$usertwo = $generator->create_and_enrol($course);
$info = new \core_availability\mock_info($course, $user->id);
// Make 2 test groups, one in a grouping and one not.
$grouping = $generator->create_grouping(array('courseid' => $course->id));
$group1 = $generator->create_group(array('courseid' => $course->id, 'name' => 'G1!'));
groups_assign_grouping($grouping->id, $group1->id);
$group2 = $generator->create_group(array('courseid' => $course->id, 'name' => 'G2!'));
// Do test (not in group).
$cond = new condition((object)array('id' => (int)$group1->id));
// Check if available (when not available).
$this->assertFalse($cond->is_available(false, $info, true, $user->id));
$information = $cond->get_description(false, false, $info);
$information = \core_availability\info::format_info($information, $course);
$this->assertMatchesRegularExpression('~You belong to.*G1!~', $information);
$this->assertTrue($cond->is_available(true, $info, true, $user->id));
// Add user to groups and refresh cache.
groups_add_member($group1, $user);
groups_add_member($group2, $user);
$info = new \core_availability\mock_info($course, $user->id);
// Recheck.
$this->assertTrue($cond->is_available(false, $info, true, $user->id));
$this->assertFalse($cond->is_available(true, $info, true, $user->id));
$this->assertFalse($cond->is_available(false, $info, true, $usertwo->id));
$this->assertTrue($cond->is_available(true, $info, true, $usertwo->id));
$information = $cond->get_description(false, true, $info);
$information = \core_availability\info::format_info($information, $course);
$this->assertMatchesRegularExpression('~do not belong to.*G1!~', $information);
// Check group 2 works also.
$cond = new condition((object)array('id' => (int)$group2->id));
$this->assertTrue($cond->is_available(false, $info, true, $user->id));
$this->assertFalse($cond->is_available(false, $info, true, $usertwo->id));
// What about an 'any group' condition?
$cond = new condition((object)array());
$this->assertTrue($cond->is_available(false, $info, true, $user->id));
$this->assertFalse($cond->is_available(true, $info, true, $user->id));
$this->assertFalse($cond->is_available(false, $info, true, $usertwo->id));
$this->assertTrue($cond->is_available(true, $info, true, $usertwo->id));
$information = $cond->get_description(false, true, $info);
$information = \core_availability\info::format_info($information, $course);
$this->assertMatchesRegularExpression('~do not belong to any~', $information);
// Admin user doesn't belong to a group, but they can access it
// either way (positive or NOT).
$this->setAdminUser();
$this->assertTrue($cond->is_available(false, $info, true, $USER->id));
$this->assertTrue($cond->is_available(true, $info, true, $USER->id));
// Group that doesn't exist uses 'missing' text.
$cond = new condition((object)array('id' => $group2->id + 1000));
$this->assertFalse($cond->is_available(false, $info, true, $user->id));
$information = $cond->get_description(false, false, $info);
$information = \core_availability\info::format_info($information, $course);
$this->assertMatchesRegularExpression('~You belong to.*\(Missing group\)~', $information);
}
/**
* Tests the constructor including error conditions. Also tests the
* string conversion feature (intended for debugging only).
*/
public function test_constructor(): void {
// Invalid id (not int).
$structure = (object)array('id' => 'bourne');
try {
$cond = new condition($structure);
$this->fail();
} catch (\coding_exception $e) {
$this->assertStringContainsString('Invalid ->id', $e->getMessage());
}
// Valid (with id).
$structure->id = 123;
$cond = new condition($structure);
$this->assertEquals('{group:#123}', (string)$cond);
// Valid (no id).
unset($structure->id);
$cond = new condition($structure);
$this->assertEquals('{group:any}', (string)$cond);
}
/**
* Tests the save() function.
*/
public function test_save(): void {
$structure = (object)array('id' => 123);
$cond = new condition($structure);
$structure->type = 'group';
$this->assertEquals($structure, $cond->save());
$structure = (object)array();
$cond = new condition($structure);
$structure->type = 'group';
$this->assertEquals($structure, $cond->save());
}
/**
* Tests the update_dependency_id() function.
*/
public function test_update_dependency_id(): void {
$cond = new condition((object)array('id' => 123));
$this->assertFalse($cond->update_dependency_id('frogs', 123, 456));
$this->assertFalse($cond->update_dependency_id('groups', 12, 34));
$this->assertTrue($cond->update_dependency_id('groups', 123, 456));
$after = $cond->save();
$this->assertEquals(456, $after->id);
}
/**
* Tests the filter_users (bulk checking) function. Also tests the SQL
* variant get_user_list_sql.
*/
public function test_filter_users(): void {
global $DB;
$this->resetAfterTest();
// Erase static cache before test.
condition::wipe_static_cache();
// Make a test course and some users.
$generator = $this->getDataGenerator();
$course = $generator->create_course();
$roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
$teacher = $generator->create_user();
$generator->enrol_user($teacher->id, $course->id, $roleids['editingteacher']);
$allusers = array($teacher->id => $teacher);
$students = array();
for ($i = 0; $i < 3; $i++) {
$student = $generator->create_user();
$students[$i] = $student;
$generator->enrol_user($student->id, $course->id, $roleids['student']);
$allusers[$student->id] = $student;
}
$info = new \core_availability\mock_info($course);
// Make test groups.
$group1 = $generator->create_group(array('courseid' => $course->id));
$group2 = $generator->create_group(array('courseid' => $course->id));
// Assign students to groups as follows (teacher is not in a group):
// 0: no groups.
// 1: in group 1.
// 2: in group 2.
groups_add_member($group1, $students[1]);
groups_add_member($group2, $students[2]);
// Test 'any group' condition.
$checker = new \core_availability\capability_checker($info->get_context());
$cond = new condition((object)array());
$result = array_keys($cond->filter_user_list($allusers, false, $info, $checker));
ksort($result);
$expected = array($teacher->id, $students[1]->id, $students[2]->id);
$this->assertEquals($expected, $result);
// Test it with get_user_list_sql.
list ($sql, $params) = $cond->get_user_list_sql(false, $info, true);
$result = $DB->get_fieldset_sql($sql, $params);
sort($result);
$this->assertEquals($expected, $result);
// Test NOT version (note that teacher can still access because AAG works
// both ways).
$result = array_keys($cond->filter_user_list($allusers, true, $info, $checker));
ksort($result);
$expected = array($teacher->id, $students[0]->id);
$this->assertEquals($expected, $result);
// Test with get_user_list_sql.
list ($sql, $params) = $cond->get_user_list_sql(true, $info, true);
$result = $DB->get_fieldset_sql($sql, $params);
sort($result);
$this->assertEquals($expected, $result);
// Test specific group.
$cond = new condition((object)array('id' => (int)$group1->id));
$result = array_keys($cond->filter_user_list($allusers, false, $info, $checker));
ksort($result);
$expected = array($teacher->id, $students[1]->id);
$this->assertEquals($expected, $result);
list ($sql, $params) = $cond->get_user_list_sql(false, $info, true);
$result = $DB->get_fieldset_sql($sql, $params);
sort($result);
$this->assertEquals($expected, $result);
$result = array_keys($cond->filter_user_list($allusers, true, $info, $checker));
ksort($result);
$expected = array($teacher->id, $students[0]->id, $students[2]->id);
$this->assertEquals($expected, $result);
list ($sql, $params) = $cond->get_user_list_sql(true, $info, true);
$result = $DB->get_fieldset_sql($sql, $params);
sort($result);
$this->assertEquals($expected, $result);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Version info.
*
* @package availability_group
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2024042200;
$plugin->requires = 2024041600;
$plugin->component = 'availability_group';
@@ -0,0 +1,117 @@
YUI.add('moodle-availability_group-form', function (Y, NAME) {
/**
* JavaScript for form editing group conditions.
*
* @module moodle-availability_group-form
*/
M.availability_group = M.availability_group || {};
/**
* @class M.availability_group.form
* @extends M.core_availability.plugin
*/
M.availability_group.form = Y.Object(M.core_availability.plugin);
/**
* Groups available for selection (alphabetical order).
*
* @property groups
* @type Array
*/
M.availability_group.form.groups = null;
/**
* Initialises this plugin.
*
* @method initInner
* @param {Array} groups Array of objects containing groupid => name
*/
M.availability_group.form.initInner = function(groups) {
this.groups = groups;
};
M.availability_group.form.getNode = function(json) {
// Create HTML structure.
var html = '<label><span class="pr-3">' + M.util.get_string('title', 'availability_group') + '</span> ' +
'<span class="availability-group">' +
'<select name="id" class="custom-select">' +
'<option value="choose">' + M.util.get_string('choosedots', 'moodle') + '</option>' +
'<option value="any">' + M.util.get_string('anygroup', 'availability_group') + '</option>';
for (var i = 0; i < this.groups.length; i++) {
var group = this.groups[i];
// String has already been escaped using format_string.
html += '<option value="' + group.id + '" data-visibility="' + group.visibility + '">' + group.name + '</option>';
}
html += '</select></span></label>';
var node = Y.Node.create('<span class="d-flex flex-wrap align-items-center">' + html + '</span>');
var select = node.one('select[name=id]');
select.on('change', function(e) {
var value = e.target.get('value');
// Find the visibility of the selected group.
var visibility = e.target.one('option[value=' + value + ']').get('dataset').visibility;
var event;
if (visibility > 0) {
event = 'availability:privateRuleSet';
} else {
event = 'availability:privateRuleUnset';
}
node.fire(event, {plugin: 'group'});
});
// Set initial values (leave default 'choose' if creating afresh).
if (json.creating === undefined) {
if (json.id !== undefined) {
var option = select.one('option[value=' + json.id + ']');
if (option) {
select.set('value', '' + json.id);
var visibility = option.get('dataset').visibility;
if (visibility > 0) {
// Defer firing the event, to allow event bubbling to be set up in M.core_availability.form.
window.setTimeout(function() {
node.fire('availability:privateRuleSet', {plugin: 'group'});
}, 0);
}
}
} else if (json.id === undefined) {
node.one('select[name=id]').set('value', 'any');
}
}
// Add event handlers (first time only).
if (!M.availability_group.form.addedEvents) {
M.availability_group.form.addedEvents = true;
var root = Y.one('.availability-field');
root.delegate('change', function() {
// Just update the form fields.
M.core_availability.form.update();
}, '.availability_group select');
}
return node;
};
M.availability_group.form.fillValue = function(value, node) {
var selected = node.one('select[name=id]').get('value');
if (selected === 'choose') {
value.id = 'choose';
} else if (selected !== 'any') {
value.id = parseInt(selected, 10);
}
};
M.availability_group.form.fillErrors = function(errors, node) {
var value = {};
this.fillValue(value, node);
// Check group item id.
if (value.id && value.id === 'choose') {
errors.push('availability_group:error_selectgroup');
}
};
}, '@VERSION@', {"requires": ["base", "node", "event", "moodle-core_availability-form"]});
@@ -0,0 +1 @@
YUI.add("moodle-availability_group-form",function(r,i){M.availability_group=M.availability_group||{},M.availability_group.form=r.Object(M.core_availability.plugin),M.availability_group.form.groups=null,M.availability_group.form.initInner=function(i){this.groups=i},M.availability_group.form.getNode=function(i){for(var a,e,t,l,o='<label><span class="pr-3">'+M.util.get_string("title","availability_group")+'</span> <span class="availability-group"><select name="id" class="custom-select"><option value="choose">'+M.util.get_string("choosedots","moodle")+'</option><option value="any">'+M.util.get_string("anygroup","availability_group")+"</option>",n=0;n<this.groups.length;n++)o+='<option value="'+(a=this.groups[n]).id+'" data-visibility="'+a.visibility+'">'+a.name+"</option>";return(t=(e=r.Node.create('<span class="d-flex flex-wrap align-items-center">'+(o+="</select></span></label>")+"</span>")).one("select[name=id]")).on("change",function(i){var a=i.target.get("value"),a=i.target.one("option[value="+a+"]").get("dataset").visibility,i=0<a?"availability:privateRuleSet":"availability:privateRuleUnset";e.fire(i,{plugin:"group"})}),i.creating===undefined&&(i.id!==undefined?(l=t.one("option[value="+i.id+"]"))&&(t.set("value",""+i.id),0<l.get("dataset").visibility&&window.setTimeout(function(){e.fire("availability:privateRuleSet",{plugin:"group"})},0)):i.id===undefined&&e.one("select[name=id]").set("value","any")),M.availability_group.form.addedEvents||(M.availability_group.form.addedEvents=!0,r.one(".availability-field").delegate("change",function(){M.core_availability.form.update()},".availability_group select")),e},M.availability_group.form.fillValue=function(i,a){a=a.one("select[name=id]").get("value");"choose"===a?i.id="choose":"any"!==a&&(i.id=parseInt(a,10))},M.availability_group.form.fillErrors=function(i,a){var e={};this.fillValue(e,a),e.id&&"choose"===e.id&&i.push("availability_group:error_selectgroup")}},"@VERSION@",{requires:["base","node","event","moodle-core_availability-form"]});
@@ -0,0 +1,117 @@
YUI.add('moodle-availability_group-form', function (Y, NAME) {
/**
* JavaScript for form editing group conditions.
*
* @module moodle-availability_group-form
*/
M.availability_group = M.availability_group || {};
/**
* @class M.availability_group.form
* @extends M.core_availability.plugin
*/
M.availability_group.form = Y.Object(M.core_availability.plugin);
/**
* Groups available for selection (alphabetical order).
*
* @property groups
* @type Array
*/
M.availability_group.form.groups = null;
/**
* Initialises this plugin.
*
* @method initInner
* @param {Array} groups Array of objects containing groupid => name
*/
M.availability_group.form.initInner = function(groups) {
this.groups = groups;
};
M.availability_group.form.getNode = function(json) {
// Create HTML structure.
var html = '<label><span class="pr-3">' + M.util.get_string('title', 'availability_group') + '</span> ' +
'<span class="availability-group">' +
'<select name="id" class="custom-select">' +
'<option value="choose">' + M.util.get_string('choosedots', 'moodle') + '</option>' +
'<option value="any">' + M.util.get_string('anygroup', 'availability_group') + '</option>';
for (var i = 0; i < this.groups.length; i++) {
var group = this.groups[i];
// String has already been escaped using format_string.
html += '<option value="' + group.id + '" data-visibility="' + group.visibility + '">' + group.name + '</option>';
}
html += '</select></span></label>';
var node = Y.Node.create('<span class="d-flex flex-wrap align-items-center">' + html + '</span>');
var select = node.one('select[name=id]');
select.on('change', function(e) {
var value = e.target.get('value');
// Find the visibility of the selected group.
var visibility = e.target.one('option[value=' + value + ']').get('dataset').visibility;
var event;
if (visibility > 0) {
event = 'availability:privateRuleSet';
} else {
event = 'availability:privateRuleUnset';
}
node.fire(event, {plugin: 'group'});
});
// Set initial values (leave default 'choose' if creating afresh).
if (json.creating === undefined) {
if (json.id !== undefined) {
var option = select.one('option[value=' + json.id + ']');
if (option) {
select.set('value', '' + json.id);
var visibility = option.get('dataset').visibility;
if (visibility > 0) {
// Defer firing the event, to allow event bubbling to be set up in M.core_availability.form.
window.setTimeout(function() {
node.fire('availability:privateRuleSet', {plugin: 'group'});
}, 0);
}
}
} else if (json.id === undefined) {
node.one('select[name=id]').set('value', 'any');
}
}
// Add event handlers (first time only).
if (!M.availability_group.form.addedEvents) {
M.availability_group.form.addedEvents = true;
var root = Y.one('.availability-field');
root.delegate('change', function() {
// Just update the form fields.
M.core_availability.form.update();
}, '.availability_group select');
}
return node;
};
M.availability_group.form.fillValue = function(value, node) {
var selected = node.one('select[name=id]').get('value');
if (selected === 'choose') {
value.id = 'choose';
} else if (selected !== 'any') {
value.id = parseInt(selected, 10);
}
};
M.availability_group.form.fillErrors = function(errors, node) {
var value = {};
this.fillValue(value, node);
// Check group item id.
if (value.id && value.id === 'choose') {
errors.push('availability_group:error_selectgroup');
}
};
}, '@VERSION@', {"requires": ["base", "node", "event", "moodle-core_availability-form"]});
@@ -0,0 +1,10 @@
{
"name": "moodle-availability_group-form",
"builds": {
"moodle-availability_group-form": {
"jsfiles": [
"form.js"
]
}
}
}
+112
View File
@@ -0,0 +1,112 @@
/**
* JavaScript for form editing group conditions.
*
* @module moodle-availability_group-form
*/
M.availability_group = M.availability_group || {};
/**
* @class M.availability_group.form
* @extends M.core_availability.plugin
*/
M.availability_group.form = Y.Object(M.core_availability.plugin);
/**
* Groups available for selection (alphabetical order).
*
* @property groups
* @type Array
*/
M.availability_group.form.groups = null;
/**
* Initialises this plugin.
*
* @method initInner
* @param {Array} groups Array of objects containing groupid => name
*/
M.availability_group.form.initInner = function(groups) {
this.groups = groups;
};
M.availability_group.form.getNode = function(json) {
// Create HTML structure.
var html = '<label><span class="pr-3">' + M.util.get_string('title', 'availability_group') + '</span> ' +
'<span class="availability-group">' +
'<select name="id" class="custom-select">' +
'<option value="choose">' + M.util.get_string('choosedots', 'moodle') + '</option>' +
'<option value="any">' + M.util.get_string('anygroup', 'availability_group') + '</option>';
for (var i = 0; i < this.groups.length; i++) {
var group = this.groups[i];
// String has already been escaped using format_string.
html += '<option value="' + group.id + '" data-visibility="' + group.visibility + '">' + group.name + '</option>';
}
html += '</select></span></label>';
var node = Y.Node.create('<span class="d-flex flex-wrap align-items-center">' + html + '</span>');
var select = node.one('select[name=id]');
select.on('change', function(e) {
var value = e.target.get('value');
// Find the visibility of the selected group.
var visibility = e.target.one('option[value=' + value + ']').get('dataset').visibility;
var event;
if (visibility > 0) {
event = 'availability:privateRuleSet';
} else {
event = 'availability:privateRuleUnset';
}
node.fire(event, {plugin: 'group'});
});
// Set initial values (leave default 'choose' if creating afresh).
if (json.creating === undefined) {
if (json.id !== undefined) {
var option = select.one('option[value=' + json.id + ']');
if (option) {
select.set('value', '' + json.id);
var visibility = option.get('dataset').visibility;
if (visibility > 0) {
// Defer firing the event, to allow event bubbling to be set up in M.core_availability.form.
window.setTimeout(function() {
node.fire('availability:privateRuleSet', {plugin: 'group'});
}, 0);
}
}
} else if (json.id === undefined) {
node.one('select[name=id]').set('value', 'any');
}
}
// Add event handlers (first time only).
if (!M.availability_group.form.addedEvents) {
M.availability_group.form.addedEvents = true;
var root = Y.one('.availability-field');
root.delegate('change', function() {
// Just update the form fields.
M.core_availability.form.update();
}, '.availability_group select');
}
return node;
};
M.availability_group.form.fillValue = function(value, node) {
var selected = node.one('select[name=id]').get('value');
if (selected === 'choose') {
value.id = 'choose';
} else if (selected !== 'any') {
value.id = parseInt(selected, 10);
}
};
M.availability_group.form.fillErrors = function(errors, node) {
var value = {};
this.fillValue(value, node);
// Check group item id.
if (value.id && value.id === 'choose') {
errors.push('availability_group:error_selectgroup');
}
};
@@ -0,0 +1,10 @@
{
"moodle-availability_group-form": {
"requires": [
"base",
"node",
"event",
"moodle-core_availability-form"
]
}
}