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,310 @@
<?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_grouping
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace availability_grouping;
defined('MOODLE_INTERNAL') || die();
/**
* Condition main class.
*
* @package availability_grouping
* @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 grouping id => name */
protected static $groupingnames = array();
/** @var int ID of grouping that this condition requires */
protected $groupingid = 0;
/** @var bool If true, indicates that activity $cm->grouping is used */
protected $activitygrouping = false;
/**
* Constructor.
*
* @param \stdClass $structure Data structure from JSON decode
* @throws \coding_exception If invalid data structure.
*/
public function __construct($structure) {
// Get grouping id.
if (isset($structure->id)) {
if (is_int($structure->id)) {
$this->groupingid = $structure->id;
} else {
throw new \coding_exception('Invalid ->id for grouping condition');
}
} else if (isset($structure->activity)) {
if (is_bool($structure->activity) && $structure->activity) {
$this->activitygrouping = true;
} else {
throw new \coding_exception('Invalid ->activity for grouping condition');
}
} else {
throw new \coding_exception('Missing ->id / ->activity for grouping condition');
}
}
public function save() {
$result = (object)array('type' => 'grouping');
if ($this->groupingid) {
$result->id = $this->groupingid;
} else {
$result->activity = true;
}
return $result;
}
public function is_available($not, \core_availability\info $info, $grabthelot, $userid) {
$context = \context_course::instance($info->get_course()->id);
$allow = true;
if (!has_capability('moodle/site:accessallgroups', $context, $userid)) {
// If the activity has 'group members only' and you don't have accessallgroups...
$groups = $info->get_modinfo()->get_groups($this->get_grouping_id($info));
if (!$groups) {
// ...and you don't belong to a group, then set it so you can't see/access it.
$allow = false;
}
// The NOT condition applies before accessallgroups (i.e. if you
// set something to be available to those NOT in grouping X,
// people with accessallgroups can still access it even if
// they are in grouping X).
if ($not) {
$allow = !$allow;
}
}
return $allow;
}
/**
* Gets the actual grouping id for the condition. This is either a specified
* id, or a special flag indicating that we use the one for the current cm.
*
* @param \core_availability\info $info Info about context cm
* @return int Grouping id
* @throws \coding_exception If it's set to use a cm but there isn't grouping
*/
protected function get_grouping_id(\core_availability\info $info) {
if ($this->activitygrouping) {
$groupingid = $info->get_course_module()->groupingid;
if (!$groupingid) {
throw new \coding_exception(
'Not supposed to be able to turn on activitygrouping when no grouping');
}
return $groupingid;
} else {
return $this->groupingid;
}
}
public function get_description($full, $not, \core_availability\info $info) {
global $DB;
$course = $info->get_course();
// Need to get the name for the grouping. Unfortunately this requires
// a database query. To save queries, get all groupings for course at
// once in a static cache.
$groupingid = $this->get_grouping_id($info);
if (!array_key_exists($groupingid, self::$groupingnames)) {
$coursegroupings = $DB->get_records(
'groupings', array('courseid' => $course->id), '', 'id, name');
foreach ($coursegroupings as $rec) {
self::$groupingnames[$rec->id] = $rec->name;
}
}
// If it still doesn't exist, it must have been misplaced.
if (!array_key_exists($groupingid, self::$groupingnames)) {
$name = get_string('missing', 'availability_grouping');
} else {
// Not safe to call format_string here; use the special function to call it later.
$name = self::description_format_string(self::$groupingnames[$groupingid]);
}
return get_string($not ? 'requires_notgrouping' : 'requires_grouping',
'availability_grouping', $name);
}
protected function get_debug_string() {
if ($this->activitygrouping) {
return 'CM';
} else {
return '#' . $this->groupingid;
}
}
/**
* 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->groupingid || $task->get_setting_value('groups');
}
public function update_after_restore($restoreid, $courseid, \base_logger $logger, $name) {
global $DB;
if (!$this->groupingid) {
// If using 'same as activity' option, no need to change it.
return false;
}
$rec = \restore_dbops::get_backup_ids_record($restoreid, 'grouping', $this->groupingid);
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('groupings',
array('id' => $this->groupingid, 'courseid' => $courseid))) {
return false;
}
// Otherwise it's a warning.
$this->groupingid = -1;
$logger->process('Restored item (' . $name .
') has availability condition on grouping that was not restored',
\backup::LOG_WARNING);
} else {
$this->groupingid = (int)$rec->newitemid;
}
return true;
}
public function update_dependency_id($table, $oldid, $newid) {
if ($table === 'groupings' && (int)$this->groupingid === (int)$oldid) {
$this->groupingid = $newid;
return true;
} else {
return false;
}
}
/**
* Wipes the static cache used to store grouping names.
*/
public static function wipe_static_cache() {
self::$groupingnames = array();
}
public function is_applied_to_user_lists() {
// Grouping 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;
}
// List users for this course who match the condition.
$groupingusers = $DB->get_records_sql("
SELECT DISTINCT gm.userid
FROM {groupings_groups} gg
JOIN {groups_members} gm ON gm.groupid = gg.groupid
WHERE gg.groupingid = ?",
array($this->get_grouping_id($info)));
// 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 grouping membership.
$allow = array_key_exists($id, $groupingusers);
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 $groupingid Required grouping id (0 = grouping linked to activity)
* @return stdClass Object representing condition
*/
public static function get_json($groupingid = 0) {
$result = (object)array('type' => 'grouping');
if ($groupingid) {
$result->id = (int)$groupingid;
} else {
$result->activity = true;
}
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();
$matchsql = "SELECT 1
FROM {groups_members} gm
JOIN {groupings_groups} gg ON gg.groupid = gm.groupid
WHERE gm.userid = userids.id
AND gg.groupingid = " .
self::unique_sql_parameter($matchparams, $this->get_grouping_id($info));
// 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,83 @@
<?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_grouping
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace availability_grouping;
defined('MOODLE_INTERNAL') || die();
/**
* Front-end class.
*
* @package availability_grouping
* @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 grouping info for course */
protected $allgroupings;
/** @var int Course id that $allgroupings is for */
protected $allgroupingscourseid;
protected function get_javascript_init_params($course, \cm_info $cm = null,
\section_info $section = null) {
// Get all groups for course.
$groupings = $this->get_all_groupings($course->id);
// Change to JS array format and return.
$jsarray = array();
$context = \context_course::instance($course->id);
foreach ($groupings as $rec) {
$jsarray[] = (object)array('id' => $rec->id, 'name' =>
format_string($rec->name, true, array('context' => $context)));
}
return array($jsarray);
}
/**
* Gets all the groupings on the course.
*
* @param int $courseid Course id
* @return array Array of grouping objects
*/
protected function get_all_groupings($courseid) {
global $DB;
if ($courseid != $this->allgroupingscourseid) {
$this->allgroupings = $DB->get_records('groupings',
['courseid' => $courseid], 'name');
$this->allgroupingscourseid = $courseid;
}
return $this->allgroupings;
}
protected function allow_add($course, \cm_info $cm = null,
\section_info $section = null) {
global $CFG, $DB;
// Check if groupings are in use for the course. (Unlike the 'group'
// condition there is no case where you might want to set up the
// condition before you set a grouping - there is no 'any grouping'
// option.)
return count($this->get_all_groupings($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_grouping.
*
* @package availability_grouping
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace availability_grouping\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for availability_grouping 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,32 @@
<?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_grouping
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['description'] = 'Allow only students who belong to a group within a specified grouping.';
$string['error_selectgrouping'] = 'You must select a grouping.';
$string['missing'] = '(Missing grouping)';
$string['pluginname'] = 'Restriction by grouping';
$string['requires_grouping'] = 'You belong to a group in <strong>{$a}</strong>';
$string['requires_notgrouping'] = 'You do not belong to a group in <strong>{$a}</strong>';
$string['title'] = 'Grouping';
$string['privacy:metadata'] = 'The Restriction by grouping plugin does not store any personal data.';
@@ -0,0 +1,129 @@
@availability @availability_grouping
Feature: availability_grouping
In order to control student access to activities
As a teacher
I need to set grouping conditions which prevent student access
Background:
Given the following "courses" exist:
| fullname | shortname | format | enablecompletion |
| Course 1 | C1 | topics | 1 |
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 "groups" exist:
| name | course | idnumber |
| G1 | C1 | GI1 |
And the following "group members" exist:
| user | group |
| student1 | GI1 |
# Basic setup.
And the following "activities" exist:
| activity | course | name |
| page | C1 | P1 |
| page | C1 | P2 |
@javascript
Scenario: Test condition
# Start to add a Page. If there aren't any groupings, there's no Grouping option.
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 "Grouping" "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.
# 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 "Course 1" course homepage
And the following "groupings" exist:
| name | course | idnumber |
| GX1 | C1 | GXI1 |
| GX2 | C1 | GXI2 |
And I am on the "P1" "page activity editing" page
And I expand all fieldsets
And I click on "Add restriction..." "button"
Then "Grouping" "button" should exist in the "Add restriction..." "dialogue"
# Page P1 grouping GX1.
Given I click on "Grouping" "button"
And I set the field "Grouping" to "GX1"
And I click on ".availability-item .availability-eye img" "css_element"
And I click on "Save and return to course" "button"
# Page P2 with grouping GX2.
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 "Grouping" "button"
And I set the field "Grouping" to "GX2"
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"
# Add group to grouping and log out/in again.
And the following "grouping groups" exist:
| grouping | group |
| GXI1 | GI1 |
And I am on the "Course 1" "course" page logged in as "student1"
# P1 should show but not B2.
Then I should see "P1" in the "region-main" "region"
And I should not see "P2" in the "region-main" "region"
@javascript
Scenario: Check grouping access restriction message on course homepage
Given the following "groupings" exist:
| name | course | idnumber |
| Grouping A | C1 | GA |
And the following "grouping groups" exist:
| grouping | group |
| GA | GI1 |
And the following "activities" exist:
| activity | name | intro | course | idnumber | groupmode | grouping |
| assign | Test assign | Assign description | C1 | assign1 | 1 | GA |
And I log in as "teacher1"
And I am on "Course 1" course homepage
And I turn editing mode on
And I open "Test assign" actions menu
And I choose "Edit settings" in the open action menu
And I expand all fieldsets
And the field "groupingid" matches value "Grouping A"
And I press "Add group/grouping access restriction"
When I press "Save and return to course"
Then I should see "Not available unless: You belong to a group in Grouping A"
@javascript
Scenario: Condition display with filters
# Teacher sets up a restriction on group G1, using multilang filter.
Given the following "groupings" exist:
| name | course | idnumber |
| <span lang="en" class="multilang">Gr-One</span><span lang="fr" class="multilang">Gr-Un</span> | C1 | GA |
And the following "activities" exist:
| activity | name | intro | course | idnumber | groupmode | grouping |
| assign | Test assign | Assign description | C1 | assign1 | 1 | GA |
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 "Test assign" "assign activity editing" page logged in as "teacher1"
And I expand all fieldsets
And I press "Add group/grouping access restriction"
And I press "Save and return to course"
# 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 a group in Gr-One"
And I should not see "Gr-Un"
@@ -0,0 +1,287 @@
<?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_grouping;
/**
* Unit tests for the condition.
*
* @package availability_grouping
* @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_user();
$generator->enrol_user($user->id, $course->id);
$info = new \core_availability\mock_info($course, $user->id);
// Make a test grouping and group.
$grouping = $generator->create_grouping(array('courseid' => $course->id,
'name' => 'Grouping!'));
$group = $generator->create_group(array('courseid' => $course->id));
groups_assign_grouping($grouping->id, $group->id);
// Do test (not in grouping).
$structure = (object)array('type' => 'grouping', 'id' => (int)$grouping->id);
$cond = new condition($structure);
// Check if available (when not available).
$this->assertFalse($cond->is_available(false, $info, true, $user->id));
$information = $cond->get_description(false, false, $info);
$this->assertMatchesRegularExpression('~belong to a group in.*Grouping!~', $information);
$this->assertTrue($cond->is_available(true, $info, true, $user->id));
// Add user to grouping and refresh cache.
groups_add_member($group, $user);
get_fast_modinfo($course->id, 0, true);
// Recheck.
$this->assertTrue($cond->is_available(false, $info, true, $user->id));
$this->assertFalse($cond->is_available(true, $info, true, $user->id));
$information = $cond->get_description(false, true, $info);
$this->assertMatchesRegularExpression('~do not belong to a group in.*Grouping!~', $information);
// Admin user doesn't belong to the grouping, but they can access it
// either way (positive or NOT) because of accessallgroups.
$this->setAdminUser();
$infoadmin = new \core_availability\mock_info($course, $USER->id);
$this->assertTrue($cond->is_available(false, $infoadmin, true, $USER->id));
$this->assertTrue($cond->is_available(true, $infoadmin, true, $USER->id));
// Grouping that doesn't exist uses 'missing' text.
$cond = new condition((object)array('id' => $grouping->id + 1000));
$this->assertFalse($cond->is_available(false, $info, true, $user->id));
$information = $cond->get_description(false, false, $info);
$this->assertMatchesRegularExpression('~belong to a group in.*(Missing grouping)~', $information);
// We need an actual cm object to test the 'grouping from cm' option.
$pagegen = $generator->get_plugin_generator('mod_page');
$page = $pagegen->create_instance(array('course' => $course->id,
'groupingid' => $grouping->id, 'availability' =>
'{"op":"|","show":true,"c":[{"type":"grouping","activity":true}]}'));
rebuild_course_cache($course->id, true);
// Check if available using the 'from course-module' grouping option.
$modinfo = get_fast_modinfo($course, $user->id);
$cm = $modinfo->get_cm($page->cmid);
$info = new \core_availability\info_module($cm);
$information = '';
$this->assertTrue($info->is_available($information, false, $user->id));
// Remove user from grouping again and recheck.
groups_remove_member($group, $user);
get_fast_modinfo($course->id, 0, true);
$this->assertFalse($info->is_available($information, false, $user->id));
$this->assertMatchesRegularExpression('~belong to a group in.*Grouping!~', $information);
}
/**
* Tests the constructor including error conditions. Also tests the
* string conversion feature (intended for debugging only).
*/
public function test_constructor(): void {
// No parameters.
$structure = new \stdClass();
try {
$cond = new condition($structure);
$this->fail();
} catch (\coding_exception $e) {
$this->assertStringContainsString('Missing ->id / ->activity', $e->getMessage());
}
// Invalid id (not int).
$structure->id = 'bourne';
try {
$cond = new condition($structure);
$this->fail();
} catch (\coding_exception $e) {
$this->assertStringContainsString('Invalid ->id', $e->getMessage());
}
// Invalid activity option (not bool).
unset($structure->id);
$structure->activity = 42;
try {
$cond = new condition($structure);
$this->fail();
} catch (\coding_exception $e) {
$this->assertStringContainsString('Invalid ->activity', $e->getMessage());
}
// Invalid activity option (false).
$structure->activity = false;
try {
$cond = new condition($structure);
$this->fail();
} catch (\coding_exception $e) {
$this->assertStringContainsString('Invalid ->activity', $e->getMessage());
}
// Valid with id.
$structure->id = 123;
$cond = new condition($structure);
$this->assertEquals('{grouping:#123}', (string)$cond);
// Valid with activity.
unset($structure->id);
$structure->activity = true;
$cond = new condition($structure);
$this->assertEquals('{grouping:CM}', (string)$cond);
}
/**
* Tests the save() function.
*/
public function test_save(): void {
$structure = (object)array('id' => 123);
$cond = new condition($structure);
$structure->type = 'grouping';
$this->assertEquals($structure, $cond->save());
$structure = (object)array('activity' => true);
$cond = new condition($structure);
$structure->type = 'grouping';
$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('groupings', 12, 34));
$this->assertTrue($cond->update_dependency_id('groupings', 123, 456));
$after = $cond->save();
$this->assertEquals(456, $after->id);
$cond = new condition((object)array('activity' => true));
$this->assertFalse($cond->update_dependency_id('frogs', 123, 456));
}
/**
* Tests the filter_users (bulk checking) function. Also tests the SQL
* variant get_user_list_sql.
*/
public function test_filter_users(): void {
global $DB, $CFG;
$this->resetAfterTest();
$CFG->enableavailability = true;
// 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);
$checker = new \core_availability\capability_checker($info->get_context());
// Make test groups.
$group1 = $generator->create_group(array('courseid' => $course->id));
$group2 = $generator->create_group(array('courseid' => $course->id));
$grouping1 = $generator->create_grouping(array('courseid' => $course->id));
$grouping2 = $generator->create_grouping(array('courseid' => $course->id));
groups_assign_grouping($grouping1->id, $group1->id);
groups_assign_grouping($grouping2->id, $group2->id);
// Make page in grouping 2.
$pagegen = $generator->get_plugin_generator('mod_page');
$page = $pagegen->create_instance(array('course' => $course->id,
'groupingid' => $grouping2->id, 'availability' =>
'{"op":"|","show":true,"c":[{"type":"grouping","activity":true}]}'));
// Assign students to groups as follows (teacher is not in a group):
// 0: no groups.
// 1: in group 1/grouping 1.
// 2: in group 2/grouping 2.
groups_add_member($group1, $students[1]);
groups_add_member($group2, $students[2]);
// Test specific grouping.
$cond = new condition((object)array('id' => (int)$grouping1->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);
// 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);
// NOT test.
$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);
// NOT 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 course-module grouping.
$modinfo = get_fast_modinfo($course);
$cm = $modinfo->get_cm($page->cmid);
$info = new \core_availability\info_module($cm);
$result = array_keys($info->filter_user_list($allusers, $course));
$expected = array($teacher->id, $students[2]->id);
$this->assertEquals($expected, $result);
// With get_user_list_sql.
list ($sql, $params) = $info->get_user_list_sql(true);
$result = $DB->get_fieldset_sql($sql, $params);
sort($result);
$this->assertEquals($expected, $result);
}
}
@@ -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_grouping
* @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_grouping';
@@ -0,0 +1,87 @@
YUI.add('moodle-availability_grouping-form', function (Y, NAME) {
/**
* JavaScript for form editing grouping conditions.
*
* @module moodle-availability_grouping-form
*/
M.availability_grouping = M.availability_grouping || {};
/**
* @class M.availability_grouping.form
* @extends M.core_availability.plugin
*/
M.availability_grouping.form = Y.Object(M.core_availability.plugin);
/**
* Groupings available for selection (alphabetical order).
*
* @property groupings
* @type Array
*/
M.availability_grouping.form.groupings = null;
/**
* Initialises this plugin.
*
* @method initInner
* @param {Array} groupings Array of objects containing groupingid => name
*/
M.availability_grouping.form.initInner = function(groupings) {
this.groupings = groupings;
};
M.availability_grouping.form.getNode = function(json) {
// Create HTML structure.
var html = '<label><span class="pr-3">' + M.util.get_string('title', 'availability_grouping') + '</span> ' +
'<span class="availability-group">' +
'<select name="id" class="custom-select">' +
'<option value="choose">' + M.util.get_string('choosedots', 'moodle') + '</option>';
for (var i = 0; i < this.groupings.length; i++) {
var grouping = this.groupings[i];
// String has already been escaped using format_string.
html += '<option value="' + grouping.id + '">' + grouping.name + '</option>';
}
html += '</select></span></label>';
var node = Y.Node.create('<span class="d-flex flex-wrap align-items-center">' + html + '</span>');
// Set initial value if specified.
if (json.id !== undefined &&
node.one('select[name=id] > option[value=' + json.id + ']')) {
node.one('select[name=id]').set('value', '' + json.id);
}
// Add event handlers (first time only).
if (!M.availability_grouping.form.addedEvents) {
M.availability_grouping.form.addedEvents = true;
var root = Y.one('.availability-field');
root.delegate('change', function() {
// Just update the form fields.
M.core_availability.form.update();
}, '.availability_grouping select');
}
return node;
};
M.availability_grouping.form.fillValue = function(value, node) {
var selected = node.one('select[name=id]').get('value');
if (selected === 'choose') {
value.id = 'choose';
} else {
value.id = parseInt(selected, 10);
}
};
M.availability_grouping.form.fillErrors = function(errors, node) {
var value = {};
this.fillValue(value, node);
// Check grouping item id.
if (value.id === 'choose') {
errors.push('availability_grouping:error_selectgrouping');
}
};
}, '@VERSION@', {"requires": ["base", "node", "event", "moodle-core_availability-form"]});
@@ -0,0 +1 @@
YUI.add("moodle-availability_grouping-form",function(n,i){M.availability_grouping=M.availability_grouping||{},M.availability_grouping.form=n.Object(M.core_availability.plugin),M.availability_grouping.form.groupings=null,M.availability_grouping.form.initInner=function(i){this.groupings=i},M.availability_grouping.form.getNode=function(i){for(var a,e,l='<label><span class="pr-3">'+M.util.get_string("title","availability_grouping")+'</span> <span class="availability-group"><select name="id" class="custom-select"><option value="choose">'+M.util.get_string("choosedots","moodle")+"</option>",o=0;o<this.groupings.length;o++)l+='<option value="'+(a=this.groupings[o]).id+'">'+a.name+"</option>";return e=n.Node.create('<span class="d-flex flex-wrap align-items-center">'+(l+="</select></span></label>")+"</span>"),i.id!==undefined&&e.one("select[name=id] > option[value="+i.id+"]")&&e.one("select[name=id]").set("value",""+i.id),M.availability_grouping.form.addedEvents||(M.availability_grouping.form.addedEvents=!0,n.one(".availability-field").delegate("change",function(){M.core_availability.form.update()},".availability_grouping select")),e},M.availability_grouping.form.fillValue=function(i,a){a=a.one("select[name=id]").get("value");i.id="choose"===a?"choose":parseInt(a,10)},M.availability_grouping.form.fillErrors=function(i,a){var e={};this.fillValue(e,a),"choose"===e.id&&i.push("availability_grouping:error_selectgrouping")}},"@VERSION@",{requires:["base","node","event","moodle-core_availability-form"]});
@@ -0,0 +1,87 @@
YUI.add('moodle-availability_grouping-form', function (Y, NAME) {
/**
* JavaScript for form editing grouping conditions.
*
* @module moodle-availability_grouping-form
*/
M.availability_grouping = M.availability_grouping || {};
/**
* @class M.availability_grouping.form
* @extends M.core_availability.plugin
*/
M.availability_grouping.form = Y.Object(M.core_availability.plugin);
/**
* Groupings available for selection (alphabetical order).
*
* @property groupings
* @type Array
*/
M.availability_grouping.form.groupings = null;
/**
* Initialises this plugin.
*
* @method initInner
* @param {Array} groupings Array of objects containing groupingid => name
*/
M.availability_grouping.form.initInner = function(groupings) {
this.groupings = groupings;
};
M.availability_grouping.form.getNode = function(json) {
// Create HTML structure.
var html = '<label><span class="pr-3">' + M.util.get_string('title', 'availability_grouping') + '</span> ' +
'<span class="availability-group">' +
'<select name="id" class="custom-select">' +
'<option value="choose">' + M.util.get_string('choosedots', 'moodle') + '</option>';
for (var i = 0; i < this.groupings.length; i++) {
var grouping = this.groupings[i];
// String has already been escaped using format_string.
html += '<option value="' + grouping.id + '">' + grouping.name + '</option>';
}
html += '</select></span></label>';
var node = Y.Node.create('<span class="d-flex flex-wrap align-items-center">' + html + '</span>');
// Set initial value if specified.
if (json.id !== undefined &&
node.one('select[name=id] > option[value=' + json.id + ']')) {
node.one('select[name=id]').set('value', '' + json.id);
}
// Add event handlers (first time only).
if (!M.availability_grouping.form.addedEvents) {
M.availability_grouping.form.addedEvents = true;
var root = Y.one('.availability-field');
root.delegate('change', function() {
// Just update the form fields.
M.core_availability.form.update();
}, '.availability_grouping select');
}
return node;
};
M.availability_grouping.form.fillValue = function(value, node) {
var selected = node.one('select[name=id]').get('value');
if (selected === 'choose') {
value.id = 'choose';
} else {
value.id = parseInt(selected, 10);
}
};
M.availability_grouping.form.fillErrors = function(errors, node) {
var value = {};
this.fillValue(value, node);
// Check grouping item id.
if (value.id === 'choose') {
errors.push('availability_grouping:error_selectgrouping');
}
};
}, '@VERSION@', {"requires": ["base", "node", "event", "moodle-core_availability-form"]});
@@ -0,0 +1,10 @@
{
"name": "moodle-availability_grouping-form",
"builds": {
"moodle-availability_grouping-form": {
"jsfiles": [
"form.js"
]
}
}
}
+82
View File
@@ -0,0 +1,82 @@
/**
* JavaScript for form editing grouping conditions.
*
* @module moodle-availability_grouping-form
*/
M.availability_grouping = M.availability_grouping || {};
/**
* @class M.availability_grouping.form
* @extends M.core_availability.plugin
*/
M.availability_grouping.form = Y.Object(M.core_availability.plugin);
/**
* Groupings available for selection (alphabetical order).
*
* @property groupings
* @type Array
*/
M.availability_grouping.form.groupings = null;
/**
* Initialises this plugin.
*
* @method initInner
* @param {Array} groupings Array of objects containing groupingid => name
*/
M.availability_grouping.form.initInner = function(groupings) {
this.groupings = groupings;
};
M.availability_grouping.form.getNode = function(json) {
// Create HTML structure.
var html = '<label><span class="pr-3">' + M.util.get_string('title', 'availability_grouping') + '</span> ' +
'<span class="availability-group">' +
'<select name="id" class="custom-select">' +
'<option value="choose">' + M.util.get_string('choosedots', 'moodle') + '</option>';
for (var i = 0; i < this.groupings.length; i++) {
var grouping = this.groupings[i];
// String has already been escaped using format_string.
html += '<option value="' + grouping.id + '">' + grouping.name + '</option>';
}
html += '</select></span></label>';
var node = Y.Node.create('<span class="d-flex flex-wrap align-items-center">' + html + '</span>');
// Set initial value if specified.
if (json.id !== undefined &&
node.one('select[name=id] > option[value=' + json.id + ']')) {
node.one('select[name=id]').set('value', '' + json.id);
}
// Add event handlers (first time only).
if (!M.availability_grouping.form.addedEvents) {
M.availability_grouping.form.addedEvents = true;
var root = Y.one('.availability-field');
root.delegate('change', function() {
// Just update the form fields.
M.core_availability.form.update();
}, '.availability_grouping select');
}
return node;
};
M.availability_grouping.form.fillValue = function(value, node) {
var selected = node.one('select[name=id]').get('value');
if (selected === 'choose') {
value.id = 'choose';
} else {
value.id = parseInt(selected, 10);
}
};
M.availability_grouping.form.fillErrors = function(errors, node) {
var value = {};
this.fillValue(value, node);
// Check grouping item id.
if (value.id === 'choose') {
errors.push('availability_grouping:error_selectgrouping');
}
};
@@ -0,0 +1,10 @@
{
"moodle-availability_grouping-form": {
"requires": [
"base",
"node",
"event",
"moodle-core_availability-form"
]
}
}