/** * Tests constructing and using condition. */ public function test_usage() { 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 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); $this->assertRegExp('~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); 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->assertRegExp('~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)); // 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)); $information = $cond->get_description(false, true, $info); $this->assertRegExp('~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); $this->assertRegExp('~You belong to.*\\(Missing group\\)~', $information); }
/** * This function creates a group with a particular name, adds it to the grouping, * and then adds the current user to that group. * * @param string $name The name to assign to the newly created group. * @return int The ID of the group that was group that was created. * */ public function create_group($name) { global $DB, $USER; $sgs = new skills_group_setting($this->courseid); $group = new stdClass(); if ($name === null || trim($name) == '') { $name = $this->name_empty_group(); } $group->name = $name; $group->courseid = $this->courseid; $groupid = groups_create_group($group); groups_assign_grouping($sgs->get_grouping_id(), $groupid); groups_add_member($groupid, $USER->id); return $groupid; }
/** * Validate log message for assigning a group to a grouping is already * belongs to */ public function test_version1importlogsduplicategroupingassignment() { global $CFG, $DB; require_once $CFG->dirroot . '/group/lib.php'; $userid = $this->create_test_user(); $courseid = $this->create_test_course(); $context = context_course::instance($courseid); $roleid = $this->create_test_role(); $group = new stdClass(); $group->courseid = $courseid; $group->name = 'rlipname'; $group->id = groups_create_group($group); $grouping = new stdClass(); $grouping->courseid = $courseid; $grouping->name = 'rlipname'; $grouping->id = groups_create_grouping($grouping); groups_assign_grouping($grouping->id, $group->id); // Make sure they already have a role assignment. role_assign($roleid, $userid, $context->id); // Base data used every time. $basedata = array('action' => 'create', 'context' => 'course', 'instance' => 'rlipshortname', 'role' => 'rlipshortname', 'group' => 'rlipname', 'grouping' => 'rlipname'); // Username. $data = $basedata; $data['username'] = '******'; $expectedmessage = "[enrolment.csv line 2] User with username \"rlipusername\" enrolled in course with shortname "; $expectedmessage .= "\"rlipshortname\". Assigned user with username \"rlipusername\" to group with name \"rlipname\". "; $expectedmessage .= "Group with name \"rlipname\" is already assigned to grouping with name \"rlipname\".\n"; $this->assert_data_produces_error($data, $expectedmessage, 'enrolment'); $DB->delete_records('user_enrolments'); $DB->delete_records('groups_members'); // Email. $data = $basedata; $data['email'] = '*****@*****.**'; $expectedmessage = "[enrolment.csv line 2] User with email \"rlipuser@rlipdomain.com\" enrolled in course with shortname "; $expectedmessage .= "\"rlipshortname\". Assigned user with email \"rlipuser@rlipdomain.com\" to group with name "; $expectedmessage .= "\"rlipname\". Group with name \"rlipname\" is already assigned to grouping with name \"rlipname\".\n"; $this->assert_data_produces_error($data, $expectedmessage, 'enrolment'); $DB->delete_records('user_enrolments'); $DB->delete_records('groups_members'); // Idnumber. $data = $basedata; $data['idnumber'] = 'rlipidnumber'; $expectedmessage = "[enrolment.csv line 2] User with idnumber \"rlipidnumber\" enrolled in course with shortname "; $expectedmessage .= "\"rlipshortname\". Assigned user with idnumber \"rlipidnumber\" to group with name \"rlipname\". "; $expectedmessage .= "Group with name \"rlipname\" is already assigned to grouping with name \"rlipname\".\n"; $this->assert_data_produces_error($data, $expectedmessage, 'enrolment'); $DB->delete_records('user_enrolments'); $DB->delete_records('groups_members'); // Username, email. $data = $basedata; $data['username'] = '******'; $data['email'] = '*****@*****.**'; $expectedmessage = "[enrolment.csv line 2] User with username \"rlipusername\", email \"rlipuser@rlipdomain.com\" "; $expectedmessage .= "enrolled in course with shortname \"rlipshortname\". Assigned user with username \"rlipusername\", "; $expectedmessage .= "email \"rlipuser@rlipdomain.com\" to group with name \"rlipname\". Group with name \"rlipname\" is "; $expectedmessage .= "already assigned to grouping with name \"rlipname\".\n"; $this->assert_data_produces_error($data, $expectedmessage, 'enrolment'); $DB->delete_records('user_enrolments'); $DB->delete_records('groups_members'); // Username, idnumber. $data = $basedata; $data['username'] = '******'; $data['idnumber'] = 'rlipidnumber'; $expectedmessage = "[enrolment.csv line 2] User with username \"rlipusername\", idnumber \"rlipidnumber\" enrolled in "; $expectedmessage .= "course with shortname \"rlipshortname\". Assigned user with username \"rlipusername\", idnumber "; $expectedmessage .= "\"rlipidnumber\" to group with name \"rlipname\". Group with name \"rlipname\" is already assigned "; $expectedmessage .= "to grouping with name \"rlipname\".\n"; $this->assert_data_produces_error($data, $expectedmessage, 'enrolment'); $DB->delete_records('user_enrolments'); $DB->delete_records('groups_members'); // Email, idnumber. $data = $basedata; $data['email'] = '*****@*****.**'; $data['idnumber'] = 'rlipidnumber'; $expectedmessage = "[enrolment.csv line 2] User with email \"rlipuser@rlipdomain.com\", idnumber \"rlipidnumber\" "; $expectedmessage .= "enrolled in course with shortname \"rlipshortname\". Assigned user with email "; $expectedmessage .= "\"rlipuser@rlipdomain.com\", idnumber \"rlipidnumber\" to group with name \"rlipname\". Group with "; $expectedmessage .= "name \"rlipname\" is already assigned to grouping with name \"rlipname\".\n"; $this->assert_data_produces_error($data, $expectedmessage, 'enrolment'); $DB->delete_records('user_enrolments'); $DB->delete_records('groups_members'); // Username, email, idnumber. $data = $basedata; $data['username'] = '******'; $data['email'] = '*****@*****.**'; $data['idnumber'] = 'rlipidnumber'; $expectedmessage = "[enrolment.csv line 2] User with username \"rlipusername\", email \"rlipuser@rlipdomain.com\", "; $expectedmessage .= "idnumber \"rlipidnumber\" enrolled in course with shortname \"rlipshortname\". Assigned user with "; $expectedmessage .= "username \"rlipusername\", email \"rlipuser@rlipdomain.com\", idnumber \"rlipidnumber\" to group "; $expectedmessage .= "with name \"rlipname\". Group with name \"rlipname\" is already assigned to grouping with name "; $expectedmessage .= "\"rlipname\".\n"; $this->assert_data_produces_error($data, $expectedmessage, 'enrolment'); $DB->delete_records('user_enrolments'); $DB->delete_records('groups_members'); }
} if (!($course = get_record('course', 'id', $grouping->courseid))) { print_error('invalidcourse'); } $courseid = $course->id; require_login($course); $context = get_context_instance(CONTEXT_COURSE, $courseid); require_capability('moodle/course:managegroups', $context); $returnurl = $CFG->wwwroot . '/group/groupings.php?id=' . $courseid; if ($frm = data_submitted() and confirm_sesskey()) { if (isset($frm->cancel)) { redirect($returnurl); } else { if (isset($frm->add) and !empty($frm->addselect)) { foreach ($frm->addselect as $groupid) { groups_assign_grouping($grouping->id, (int) $groupid); } } else { if (isset($frm->remove) and !empty($frm->removeselect)) { foreach ($frm->removeselect as $groupid) { groups_unassign_grouping($grouping->id, (int) $groupid); } } } } } $currentmembers = array(); $potentialmembers = array(); if ($groups = get_records('groups', 'courseid', $courseid, 'name')) { if ($assignment = get_records('groupings_groups', 'groupingid', $grouping->id)) { foreach ($assignment as $ass) {
redirect($PAGE->url); } if ($formdata = $mform->get_data()) { // Create a new group and add the creator as a member of it $params = array($course->id); $names = $DB->get_records_sql("SELECT g.name\n FROM {groups} g\n WHERE g.courseid = ?", $params); $max = 0; foreach ($names as $n) { if (intval($n->name) >= $max) { $max = intval($n->name); } } $data = (object) array('name' => strval($max + 1), 'description' => $formdata->description, 'courseid' => $course->id); $id = groups_create_group($data, false); if ($groupselect->targetgrouping != 0) { groups_assign_grouping($groupselect->targetgrouping, $id); } groups_add_member($id, $USER->id); //add_to_log ( $course->id, 'groupselect', 'select', 'view.php?id=' . $cm->id, $groupselect->id, $cm->id ); if ($formdata->password !== '') { $passworddata = (object) array('groupid' => $id, 'password' => password_hash($formdata->password, PASSWORD_DEFAULT), 'instance_id' => $groupselect->id); $DB->insert_record('groupselect_passwords', $passworddata, false); } redirect($PAGE->url); } else { if ($create) { // If create button was clicked, show the form echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('creategroup', 'mod_groupselect')); $mform->display(); echo $OUTPUT->footer();
/** * This unit test checks that groups_get_all_groups returns groups in * alphabetical order even if they are in a grouping. */ public function test_groups_ordering() { $generator = $this->getDataGenerator(); $this->resetAfterTest(); // Create a course category and course. $cat = $generator->create_category(array('parent' => 0)); $course = $generator->create_course(array('category' => $cat->id)); $grouping = $generator->create_grouping(array('courseid' => $course->id, 'name' => 'Grouping')); // Create groups in reverse order. $group2 = $generator->create_group(array('courseid' => $course->id, 'name' => 'Group 2')); $group1 = $generator->create_group(array('courseid' => $course->id, 'name' => 'Group 1')); // Assign the groups to the grouping in reverse order. $this->assertTrue(groups_assign_grouping($grouping->id, $group2->id)); $this->assertTrue(groups_assign_grouping($grouping->id, $group1->id)); // Get all groups and check they are alphabetical. $groups = array_values(groups_get_all_groups($course->id, 0)); $this->assertEquals('Group 1', $groups[0]->name); $this->assertEquals('Group 2', $groups[1]->name); // Now check the same is true when accessed by grouping. $groups = array_values(groups_get_all_groups($course->id, 0, $grouping->id)); $this->assertEquals('Group 1', $groups[0]->name); $this->assertEquals('Group 2', $groups[1]->name); }
/** * Tests the filter_users (bulk checking) function. */ public function test_filter_users() { 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['teacher']); $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); $this->assertEquals(array($teacher->id, $students[1]->id), $result); $result = array_keys($cond->filter_user_list($allusers, true, $info, $checker)); ksort($result); $this->assertEquals(array($teacher->id, $students[0]->id, $students[2]->id), $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)); $this->assertEquals(array($teacher->id, $students[2]->id), $result); }
/** * Test get_groupings */ public function test_get_groupings() { global $DB; $this->resetAfterTest(true); $course = self::getDataGenerator()->create_course(); $groupingdata = array(); $groupingdata['courseid'] = $course->id; $groupingdata['name'] = 'Grouping Test'; $groupingdata['description'] = 'Grouping Test description'; $groupingdata['descriptionformat'] = FORMAT_MOODLE; $grouping = self::getDataGenerator()->create_grouping($groupingdata); // Set the required capabilities by the external function. $context = context_course::instance($course->id); $roleid = $this->assignUserCapability('moodle/course:managegroups', $context->id); $this->assignUserCapability('moodle/course:view', $context->id, $roleid); // Call the external function without specifying the optional parameter. $groupings = core_group_external::get_groupings(array($grouping->id)); // We need to execute the return values cleaning process to simulate the web service server. $groupings = external_api::clean_returnvalue(core_group_external::get_groupings_returns(), $groupings); $this->assertEquals(1, count($groupings)); $group1data = array(); $group1data['courseid'] = $course->id; $group1data['name'] = 'Group Test 1'; $group1data['description'] = 'Group Test 1 description'; $group1data['descriptionformat'] = FORMAT_MOODLE; $group2data = array(); $group2data['courseid'] = $course->id; $group2data['name'] = 'Group Test 2'; $group2data['description'] = 'Group Test 2 description'; $group2data['descriptionformat'] = FORMAT_MOODLE; $group1 = self::getDataGenerator()->create_group($group1data); $group2 = self::getDataGenerator()->create_group($group2data); groups_assign_grouping($grouping->id, $group1->id); groups_assign_grouping($grouping->id, $group2->id); // Call the external function specifying that groups are returned. $groupings = core_group_external::get_groupings(array($grouping->id), true); // We need to execute the return values cleaning process to simulate the web service server. $groupings = external_api::clean_returnvalue(core_group_external::get_groupings_returns(), $groupings); $this->assertEquals(1, count($groupings)); $this->assertEquals(2, count($groupings[0]['groups'])); foreach ($groupings[0]['groups'] as $group) { $dbgroup = $DB->get_record('groups', array('id' => $group['id']), '*', MUST_EXIST); $dbgroupinggroups = $DB->get_record('groupings_groups', array('groupingid' => $groupings[0]['id'], 'groupid' => $group['id']), '*', MUST_EXIST); switch ($dbgroup->name) { case $group1->name: $groupdescription = $group1->description; $groupcourseid = $group1->courseid; break; case $group2->name: $groupdescription = $group2->description; $groupcourseid = $group2->courseid; break; default: throw new moodle_exception('unknowgroupname'); break; } $this->assertEquals($dbgroup->description, $groupdescription); $this->assertEquals($dbgroup->courseid, $groupcourseid); } }
/** * Test is_user_access_restricted_by_group() * * The underlying groups system is more thoroughly tested in lib/tests/grouplib_test.php */ public function test_is_user_access_restricted_by_group() { global $DB, $CFG, $USER; $this->resetAfterTest(true); // Create a course $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); // Create a mod_assign instance $assign = $this->getDataGenerator()->create_module('assign', array('course'=>$course->id)); $cm_info = get_fast_modinfo($course)->instances['assign'][$assign->id]; // Create and enrol a student // Enrolment is necessary for groups to work $studentrole = $DB->get_record('role', array('shortname'=>'student'), '*', MUST_EXIST); $student = $this->getDataGenerator()->create_user(); role_assign($studentrole->id, $student->id, $coursecontext); $enrolplugin = enrol_get_plugin('manual'); $enrolplugin->add_instance($course); $enrolinstances = enrol_get_instances($course->id, false); foreach ($enrolinstances as $enrolinstance) { if ($enrolinstance->enrol === 'manual') { break; } } $enrolplugin->enrol_user($enrolinstance, $student->id); // Switch to a student and reload the context info $this->setUser($student); $cm_info = $this->refresh_cm_info($course, $assign); // Create up a teacher $teacherrole = $DB->get_record('role', array('shortname'=>'editingteacher'), '*', MUST_EXIST); $teacher = $this->getDataGenerator()->create_user(); role_assign($teacherrole->id, $teacher->id, $coursecontext); // Create 2 groupings $grouping1 = $this->getDataGenerator()->create_grouping(array('courseid' => $course->id, 'name' => 'grouping1')); $grouping2 = $this->getDataGenerator()->create_grouping(array('courseid' => $course->id, 'name' => 'grouping2')); // Create 2 groups and put them in the groupings $group1 = $this->getDataGenerator()->create_group(array('courseid' => $course->id, 'idnumber' => 'group1')); groups_assign_grouping($grouping1->id, $group1->id); $group2 = $this->getDataGenerator()->create_group(array('courseid' => $course->id, 'idnumber' => 'group2')); groups_assign_grouping($grouping2->id, $group2->id); // If groups are disabled, the activity isn't restricted. $CFG->enablegroupmembersonly = false; $this->assertFalse($cm_info->is_user_access_restricted_by_group()); // If groups are on but "group members only" is off, the activity isn't restricted. $CFG->enablegroupmembersonly = true; $cm_info->groupmembersonly = NOGROUPS; $this->assertFalse($cm_info->is_user_access_restricted_by_group()); // If "group members only" is on but user is in the wrong group, the activity is restricted. $cm_info->groupmembersonly = SEPARATEGROUPS; $cm_info->groupingid = $grouping1->id; $this->assertTrue(groups_add_member($group2, $USER)); $this->assertTrue($cm_info->is_user_access_restricted_by_group()); // If the user is in the required group, the activity isn't restricted. groups_remove_member($group2, $USER); $this->assertTrue(groups_add_member($group1, $USER)); $cm_info = $this->refresh_cm_info($course, $assign); $this->assertFalse($cm_info->is_user_access_restricted_by_group()); // Switch to a teacher and reload the context info $this->setUser($teacher); $cm_info = $this->refresh_cm_info($course, $assign); // If the user isn't in the required group but has 'moodle/site:accessallgroups', the activity isn't restricted. $this->assertTrue(has_capability('moodle/site:accessallgroups', $coursecontext)); $this->assertFalse($cm_info->is_user_access_restricted_by_group()); }
/** * Outputs the content of the administration tab and manages actions taken in this tab */ public function view_administration() { global $SESSION, $OUTPUT, $PAGE, $DB, $USER, $CFG; $output = $PAGE->get_renderer('mod_grouptool'); $id = $this->cm->id; $context = context_course::instance($this->course->id); // Get applicable roles! $rolenames = array(); if ($roles = get_profile_roles($context)) { foreach ($roles as $role) { $rolenames[$role->id] = strip_tags(role_get_name($role, $context)); } } $filter = optional_param('filter', null, PARAM_INT); if ($filter !== null) { set_user_preference('mod_grouptool_group_filter', $filter, $USER->id); } else { $filter = get_user_preferences('mod_grouptool_group_filter', self::FILTER_ACTIVE, $USER->id); } $inactivetabs = array(); $filtertabs['active'] = new tabobject(self::FILTER_ACTIVE, $CFG->wwwroot . '/mod/grouptool/view.php?id=' . $id . '&tab=group_admin&filter=' . self::FILTER_ACTIVE, get_string('active', 'grouptool'), '', false); $filtertabs['inactive'] = new tabobject(self::FILTER_INACTIVE, $CFG->wwwroot . '/mod/grouptool/view.php?id=' . $id . '&tab=group_admin&filter=' . self::FILTER_INACTIVE, get_string('inactive'), '', false); $filtertabs['all'] = new tabobject(self::FILTER_ALL, $CFG->wwwroot . '/mod/grouptool/view.php?id=' . $id . '&tab=group_admin&filter=' . self::FILTER_ALL, get_string('all'), '', false); echo html_writer::tag('div', $OUTPUT->tabtree($filtertabs, $filter, $inactivetabs), array('id' => 'filtertabs')); // Check if everything has been confirmed, so we can finally start working! if (optional_param('confirm', 0, PARAM_BOOL)) { if (isset($SESSION->grouptool->view_administration->createGroupings)) { require_capability('mod/grouptool:create_groupings', $this->context); $target = required_param('target', PARAM_INT); switch ($target) { // ...grpg_target | grpg_groupingname | use_all (0 sel | 1 all). case 0: // Invalid - no action! TODO Add message! $error = true; $preview = ''; break; case -2: // One grouping per group! list($error, $preview) = $this->create_group_groupings(); break; case -1: // One new grouping for all! list($error, $preview) = $this->update_grouping($target, required_param('name', PARAM_ALPHANUMEXT)); break; default: list($error, $preview) = $this->update_grouping($target); break; } $preview = html_writer::tag('div', $preview, array('class' => 'centered')); echo $OUTPUT->box($preview, 'generalbox'); } unset($SESSION->grouptool->view_administration); } if ($rename = optional_param('rename', 0, PARAM_INT)) { // Show Rename Form! $gform = new \mod_grouptool\group_rename_form(null, array('id' => $this->cm->id, 'instance' => $this->cm->instance, 'rename' => $rename)); if (!$gform->is_cancelled() && ($fromform = $gform->get_data())) { $group = new stdClass(); $group->id = $fromform->rename; $group->name = $fromform->name; $group->courseid = $fromform->courseid; groups_update_group($group); } else { if (!$gform->is_cancelled()) { $data = new stdClass(); $data->name = $DB->get_field('groups', 'name', array('id' => $rename)); $gform->set_data($data); $gform->display(); echo $OUTPUT->footer(); die; } } } if ($resize = optional_param('resize', 0, PARAM_INT)) { // Show Rename Form! $gform = new \mod_grouptool\group_resize_form(null, array('id' => $this->cm->id, 'instance' => $this->cm->instance, 'resize' => $resize)); if (!$gform->is_cancelled() && ($fromform = $gform->get_data())) { if (empty($fromform->size)) { $DB->set_field('grouptool_agrps', 'grpsize', null, array('groupid' => $fromform->resize, 'grouptoolid' => $this->cm->id)); } else { $group = new stdClass(); $group->id = $DB->get_field('grouptool_agrps', 'id', array('groupid' => $fromform->resize, 'grouptoolid' => $this->cm->instance)); $group->grpsize = $fromform->size; $DB->update_record('grouptool_agrps', $group); } } else { if (!$gform->is_cancelled()) { $data = new stdClass(); $data->size = $DB->get_field('grouptool_agrps', 'grpsize', array('groupid' => $resize, 'grouptoolid' => $this->cm->instance)); $gform->set_data($data); $gform->display(); echo $OUTPUT->footer(); die; } } } if ($delete = optional_param('delete', 0, PARAM_INT)) { if (!optional_param('confirm', 0, PARAM_BOOL)) { // Show Confirm! $cancel = new moodle_url($PAGE->url); $continue = new moodle_url($cancel, array('confirm' => 1, 'delete' => $delete)); $cancel = new single_button($cancel, get_string('no'), 'post'); $continue = new single_button($continue, get_string('yes'), 'post'); $confirmtext = get_string('confirm_delete', 'grouptool'); echo $this->confirm($confirmtext, $continue, $cancel); echo $OUTPUT->footer(); die; } else { // Delete it! groups_delete_group($delete); } } if ($toggle = optional_param('toggle', 0, PARAM_INT)) { if (!empty($toggle)) { $conditions = array('grouptoolid' => $this->cm->instance, 'groupid' => $toggle); if (!$DB->record_exists('grouptool_agrps', $conditions)) { echo $OUTPUT->box($OUTPUT->notification(get_string('group_not_found', 'grouptool'), 'notifyproblem', $conditions), 'generalbox'); } else { $record = $DB->get_record('grouptool_agrps', $conditions); if (!empty($record->active)) { $DB->set_field('grouptool_agrps', 'active', 0, $conditions); } else { $DB->set_field('grouptool_agrps', 'active', 1, $conditions); } } } } if (($bulkaction = optional_param('bulkaction', null, PARAM_ALPHA)) && ($selected = optional_param_array('selected', array(), PARAM_INT)) && optional_param('start_bulkaction', 0, PARAM_BOOL)) { switch ($bulkaction) { case 'activate': // ...also via ajax bulk action? // Activate now! $groups = optional_param_array('selected', null, PARAM_INT); if (!empty($groups)) { list($grpsql, $grpparams) = $DB->get_in_or_equal($groups); $DB->set_field_select("grouptool_agrps", "active", 1, " grouptoolid = ? AND groupid " . $grpsql, array_merge(array($this->cm->instance), $grpparams)); } echo $OUTPUT->notification(get_string('activated_groups', 'grouptool'), 'notifysuccess'); $continue = new moodle_url($PAGE->url, array('tab' => 'group_admin')); echo $this->confirm('', $continue); break; case 'deactivate': // ...also via ajax bulk action? // Deactivate now! $groups = optional_param_array('selected', null, PARAM_INT); if (!empty($groups)) { list($grpsql, $grpparams) = $DB->get_in_or_equal($groups); $DB->set_field_select("grouptool_agrps", "active", 0, " grouptoolid = ? AND groupid " . $grpsql, array_merge(array($this->cm->instance), $grpparams)); } echo $OUTPUT->notification(get_string('deactivated_groups', 'grouptool'), 'notifysuccess'); $continue = new moodle_url($PAGE->url, array('tab' => 'group_admin')); echo $this->confirm('', $continue); break; case 'delete': // ...also via ajax bulk action? // Show confirmation dialogue! if (optional_param('confirm', 0, PARAM_BOOL)) { $groups = optional_param_array('selected', null, PARAM_INT); $groups = $DB->get_records_list('groups', 'id', $groups); foreach ($groups as $group) { groups_delete_group($group); } echo $OUTPUT->notification(get_string('successfully_deleted_groups', 'grouptool'), 'notifysuccess'); $continue = new moodle_url($PAGE->url, array('tab' => 'group_admin')); echo $this->confirm('', $continue); } else { $cancel = new moodle_url($PAGE->url, array('tab' => 'group_admin')); $params = array('confirm' => 1, 'bulkaction' => 'delete', 'start_bulkaction' => 1); $text = get_string('confirm_delete', 'grouptool') . html_writer::start_tag('ul'); $groups = $DB->get_records_list('groups', 'id', $selected); foreach ($selected as $select) { $params['selected[' . $select . ']'] = $select; $text .= html_writer::tag('li', $groups[$select]->name); } $text .= html_writer::end_tag('ul'); $continue = new moodle_url($cancel, $params); echo $this->confirm($text, $continue, $cancel); echo $OUTPUT->footer(); die; } break; case 'grouping': // Show grouping creation form! $selected = optional_param_array('selected', array(), PARAM_INT); $mform = new \mod_grouptool\groupings_creation_form(null, array('id' => $id, 'selected' => $selected)); $groups = $DB->get_records_list('groups', 'id', $selected); if ($mform->is_cancelled()) { $bulkaction = null; $selected = array(); } else { if ($fromform = $mform->get_data()) { // Some groupings should be created... if ($fromform->target == -2) { // One new grouping per group! foreach ($groups as $group) { $grouping = new stdClass(); if (!($grouping->id = groups_get_grouping_by_name($this->course->id, $group->name))) { $grouping = new stdClass(); $grouping->courseid = $this->course->id; $grouping->name = $group->name; $grouping->id = groups_create_grouping($grouping); } // Insert group! groups_assign_grouping($grouping->id, $group->id); } } else { if ($fromform->target == -1) { // One new grouping! // Create grouping if it doesn't exist... $grouping = new stdClass(); if (!($grouping->id = groups_get_grouping_by_name($this->course->id, $fromform->name))) { $grouping = new stdClass(); $grouping->courseid = $this->course->id; $grouping->name = trim($fromform->name); $grouping->id = groups_create_grouping($grouping); } // Insert groups! foreach ($groups as $group) { groups_assign_grouping($grouping->id, $group->id); } } else { if ($fromform->target > 0) { // Existing Grouping! $grouping = groups_get_grouping($fromform->target); if ($grouping) { foreach ($groups as $group) { groups_assign_grouping($grouping->id, $group->id); } } } } } // ...redirect to show sortlist again! $url = new moodle_url('/mod/grouptool/view.php', array('id' => $this->cm->id, 'tab' => 'group_admin', 'filter' => $filter)); $text = $OUTPUT->notification(get_string('groupings_created_and_groups_added', 'grouptool'), 'notifymessage'); echo $this->confirm($text, $url); } else { $mform->display(); } } break; } } if (!$bulkaction || !$selected || !optional_param('start_bulkaction', 0, PARAM_BOOL)) { // Show form! $formaction = new moodle_url('/mod/grouptool/view.php', array('id' => $this->cm->id, 'tab' => 'group_admin', 'filter' => $filter)); $mform = new MoodleQuickForm('bulk', 'post', $formaction, ''); $mform->addElement('hidden', 'sesskey'); $mform->setDefault('sesskey', sesskey()); $sortlist = new \mod_grouptool\output\sortlist($this->course->id, $this->cm, $filter); $sortlistcontroller = new \mod_grouptool\output\sortlist_controller($sortlist); $mform->addElement('html', $output->render($sortlistcontroller)); $mform->addElement('html', $output->render($sortlist)); $actions = array('' => get_string('choose', 'grouptool'), 'activate' => get_string('setactive', 'grouptool'), 'deactivate' => get_string('setinactive', 'grouptool'), 'delete' => get_string('delete'), 'grouping' => get_string('createinsertgrouping', 'grouptool')); $grp = array(); $grp[] =& $mform->createElement('static', 'with_selection', '', get_string('with_selection', 'grouptool')); $grp[] =& $mform->createElement('select', 'bulkaction', '', $actions); $grp[] =& $mform->createElement('submit', 'start_bulkaction', get_string('start', 'grouptool')); $mform->addGroup($grp, 'actiongrp', '', ' ', false); $mform->disable_form_change_checker(); $mform->display(); switch ($filter) { case self::FILTER_ACTIVE: $curfilter = 'active'; break; case self::FILTER_INACTIVE: $curfilter = 'inactive'; break; case self::FILTER_ALL: $curfilter = 'all'; break; } $PAGE->requires->yui_module('moodle-mod_grouptool-administration', 'M.mod_grouptool.init_administration', array(array('lang' => current_language(), 'contextid' => $this->context->id, 'filter' => $curfilter, 'filterid' => $filter, 'globalsize' => $this->grouptool->grpsize))); $PAGE->requires->strings_for_js(array('active', 'inactive', 'confirm_delete'), 'mod_grouptool'); $PAGE->requires->string_for_js('ajax_edit_size_help', 'mod_grouptool'); $PAGE->requires->strings_for_js(array('yes', 'no'), 'moodle'); } }
/** * Updates all parent cluster's groupings with the existence of a group for this cluster * * @param int $clusterid The cluster to check the parents for * @param boolean $include_children If true, make child cluster-groups trickle up the tree * @return boolean Returns true to satisfy event handlers */ function cluster_groups_update_grouping_closure($clusterid, $include_children = false) { global $CFG, $CURMAN; if (empty($CFG->enablegroupings) || empty($CURMAN->config->cluster_groupings) || !cluster_groups_grouping_allowed($clusterid)) { return true; } $cluster = new cluster($clusterid); //get the group id for this cluster if ($groupid = groups_get_group_by_name(SITEID, $cluster->name)) { //go through the chain of parent clusters while (!empty($cluster->parent)) { $cluster = new cluster($cluster->parent); //add this to grouping if applicable $grouping = groups_get_grouping_by_name(SITEID, $cluster->name); if ($grouping = groups_get_grouping($grouping)) { groups_assign_grouping($grouping->id, $groupid); //recurse into children if possible if ($include_children) { //get all child clusters $child_cluster_ids = cluster_groups_get_child_clusters($cluster->id); foreach ($child_cluster_ids as $child_cluster_id) { //children only if ($child_cluster_id != $cluster->id) { $child_cluster = new cluster($child_cluster_id); //make sure the group exists if ($child_groupid = groups_get_group_by_name(SITEID, $child_cluster->name) and cluster_groups_cluster_allows_groups($child_cluster->id)) { groups_assign_grouping($grouping->id, $child_groupid); } } } } } } } return true; }
/** * This function creates the groups for testing. We enroll the last users first, rather than * the ones at the start. This way I can use user0 for testing. * */ protected function create_groups() { for ($i = 0; $i < self::NUMBEROFGROUPS; $i++) { $group = $this->getDataGenerator()->create_group(array('courseid' => $this->courseid)); groups_assign_grouping($this->groupingid, $group->id); $this->groupids[] = $group->id; groups_add_member($group->id, $this->users[self::NUMBEROFUSERS - 2 * $i - 1]->id); groups_add_member($group->id, $this->users[self::NUMBEROFUSERS - 2 * $i - 2]->id); } }
$grouping = $grouping->id; } } foreach ($teams as $k => $teamstr) { $name = $team_names[$k]; $team = explode(",", $teamstr); $oname = !$nogrouping && $inherit_grouping_name ? "{$grouping_name} {$name}" : $name; $groupdata = new stdClass(); $groupdata->courseid = $course->id; $groupdata->name = $oname; $group = groups_create_group($groupdata); foreach ($team as $user) { groups_add_member($group, $user); } if (!$nogrouping) { groups_assign_grouping($grouping, $group); } } $feedback = "Your groups were successfully created."; } else { if ($teambuilder->groupid) { $group = $teambuilder->groupid; } else { $group = ''; } $students = get_enrolled_users($ctxt, 'mod/teambuilder:respond', $group, 'u.id,u.firstname,u.lastname'); $responses = teambuilder_get_responses($teambuilder->id); $questions = teambuilder_get_questions($teambuilder->id); echo '<script type="text/javascript">'; echo 'var students = ' . json_encode($students) . ';'; echo 'var responses = ' . json_encode($responses) . ';';
/** * Tests the behaviour of the counter in unique_sql_parameter(). * * There was a problem with static counters used to implement a sequence of * parameter placeholders (MDL-53481). As always with static variables, it * is a bit tricky to unit test the behaviour reliably as it depends on the * actual tests executed and also their order. * * To minimise risk of false expected behaviour, this test method should be * first one where {@link core_availability\tree::get_user_list_sql()} is * used. We also use higher number of condition instances to increase the * risk of the counter collision, should there remain a problem. */ public function test_unique_sql_parameter_behaviour() { global $DB; $this->resetAfterTest(); $generator = $this->getDataGenerator(); // Create a test course with multiple groupings and groups and a student in each of them. $course = $generator->create_course(); $user = $generator->create_user(); $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student')); $generator->enrol_user($user->id, $course->id, $studentroleid); // The total number of groupings and groups must not be greater than 61. // There is a limit in MySQL on the max number of joined tables. $groups = []; for ($i = 0; $i < 25; $i++) { $group = $generator->create_group(array('courseid' => $course->id)); groups_add_member($group, $user); $groups[] = $group; } $groupings = []; for ($i = 0; $i < 25; $i++) { $groupings[] = $generator->create_grouping(array('courseid' => $course->id)); } foreach ($groupings as $grouping) { foreach ($groups as $group) { groups_assign_grouping($grouping->id, $group->id); } } $info = new \core_availability\mock_info($course); // Make a huge tree with 'AND' of all groups and groupings conditions. $conditions = []; foreach ($groups as $group) { $conditions[] = \availability_group\condition::get_json($group->id); } foreach ($groupings as $groupingid) { $conditions[] = \availability_grouping\condition::get_json($grouping->id); } shuffle($conditions); $tree = new tree(tree::get_root_json($conditions)); list($sql, $params) = $tree->get_user_list_sql(false, $info, false); // This must not throw exception. $DB->fix_sql_params($sql, $params); }
/** * Validate that the import prevents assigning a user to the same grouping * twice */ public function test_version1importpreventsduplicategroupgroupingassignments() { global $CFG, $DB; require_once $CFG->dirroot . '/group/lib.php'; // Set up the "pre-existing" group. $groupid = $this->create_test_group(self::$courseid); // Set up the "pre-existing" grouping. $groupingid = $this->create_test_grouping(self::$courseid); // Assign the group to the grouping. groups_assign_grouping($groupingid, $groupid); // Validate setup. $this->assertEquals($DB->count_records('groupings_groups'), 1); // Run the import. $data = $this->get_core_enrolment_data(); $data['group'] = 'rlipgroup'; $data['grouping'] = 'rlipgrouping'; $this->run_core_enrolment_import($data, false); // Compare data. $this->assertEquals($DB->count_records('groupings_groups'), 1); }
/** * Tests for groups_get_user_groups() method. */ public function test_groups_get_user_groups() { $this->resetAfterTest(true); $generator = $this->getDataGenerator(); // Create courses. $course1 = $generator->create_course(); $course2 = $generator->create_course(); // Create users. $user1 = $generator->create_user(); $user2 = $generator->create_user(); $user3 = $generator->create_user(); // Enrol users. $generator->enrol_user($user1->id, $course1->id); $generator->enrol_user($user1->id, $course2->id); $generator->enrol_user($user2->id, $course2->id); $generator->enrol_user($user3->id, $course2->id); // Create groups. $group1 = $generator->create_group(array('courseid' => $course1->id)); $group2 = $generator->create_group(array('courseid' => $course2->id)); $group3 = $generator->create_group(array('courseid' => $course2->id)); // Assign users to groups. $this->assertTrue($generator->create_group_member(array('groupid' => $group1->id, 'userid' => $user1->id))); $this->assertTrue($generator->create_group_member(array('groupid' => $group2->id, 'userid' => $user2->id))); // Get user groups. $usergroups1 = groups_get_user_groups($course1->id, $user1->id); $usergroups2 = groups_get_user_groups($course2->id, $user2->id); // Assert return data. $this->assertEquals($group1->id, $usergroups1[0][0]); $this->assertEquals($group2->id, $usergroups2[0][0]); // Now, test with groupings. $grouping1 = $generator->create_grouping(array('courseid' => $course1->id)); $grouping2 = $generator->create_grouping(array('courseid' => $course2->id)); // Assign the groups to grouping. groups_assign_grouping($grouping1->id, $group1->id); groups_assign_grouping($grouping2->id, $group2->id); groups_assign_grouping($grouping2->id, $group3->id); // Test with grouping. $usergroups1 = groups_get_user_groups($course1->id, $user1->id); $usergroups2 = groups_get_user_groups($course2->id, $user2->id); $this->assertArrayHasKey($grouping1->id, $usergroups1); $this->assertArrayHasKey($grouping2->id, $usergroups2); // Test user without a group. $usergroups1 = groups_get_user_groups($course2->id, $user3->id); $this->assertCount(0, $usergroups1[0]); // Test with userid = 0. $usergroups1 = groups_get_user_groups($course1->id, 0); $usergroups2 = groups_get_user_groups($course2->id, 0); $this->assertCount(0, $usergroups1[0]); $this->assertCount(0, $usergroups2[0]); // Test with courseid = 0. $usergroups1 = groups_get_user_groups(0, $user1->id); $usergroups2 = groups_get_user_groups(0, $user2->id); $this->assertCount(0, $usergroups1[0]); $this->assertCount(0, $usergroups2[0]); }
/** * Testing get_shared_group_members */ public function test_get_shared_group_members() { $this->create_extra_users(); $this->setAdminUser(); // Force create an assignment with SEPARATEGROUPS. $data = new stdClass(); $data->courseid = $this->course->id; $data->name = 'Grouping'; $groupingid = groups_create_grouping($data); groups_assign_grouping($groupingid, $this->groups[0]->id); groups_assign_grouping($groupingid, $this->groups[1]->id); $assign = $this->create_instance(array('groupingid' => $groupingid, 'groupmode' => SEPARATEGROUPS)); $cm = $assign->get_course_module(); // Add the capability to access allgroups. $roleid = create_role('Access all groups role', 'accessallgroupsrole', ''); assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $roleid, $assign->get_context()->id); role_assign($roleid, $this->extrastudents[3]->id, $assign->get_context()->id); accesslib_clear_all_caches_for_unit_testing(); // Get shared group members for students 0 and 1. $groupmembers = array(); $groupmembers[0] = $assign->get_shared_group_members($cm, $this->students[0]->id); $groupmembers[1] = $assign->get_shared_group_members($cm, $this->students[1]->id); // They should share groups with extrastudents 0 and 1. $this->assertTrue(in_array($this->extrastudents[0]->id, $groupmembers[0])); $this->assertFalse(in_array($this->extrastudents[0]->id, $groupmembers[1])); $this->assertTrue(in_array($this->extrastudents[1]->id, $groupmembers[1])); $this->assertFalse(in_array($this->extrastudents[1]->id, $groupmembers[0])); // Lists of group members for students and extrastudents should be the same. $this->assertEquals($groupmembers[0], $assign->get_shared_group_members($cm, $this->extrastudents[0]->id)); $this->assertEquals($groupmembers[1], $assign->get_shared_group_members($cm, $this->extrastudents[1]->id)); // Get all group members for extrastudent 3 wich can access all groups. $allgroupmembers = $assign->get_shared_group_members($cm, $this->extrastudents[3]->id); // Extrastudent 3 should see students 0 and 1, extrastudent 0 and 1. $this->assertTrue(in_array($this->students[0]->id, $allgroupmembers)); $this->assertTrue(in_array($this->students[1]->id, $allgroupmembers)); $this->assertTrue(in_array($this->extrastudents[0]->id, $allgroupmembers)); $this->assertTrue(in_array($this->extrastudents[1]->id, $allgroupmembers)); }
private function make_group($courseid, $name, $groupingid=0) { global $CFG; require_once($CFG->dirroot . '/group/lib.php'); $groupid = groups_create_group((object)array('courseid' => $courseid, 'name' => $name)); if ($groupingid) { groups_assign_grouping($groupingid, $groupid); } return $groupid; }
/** * Tests user restrictions, as they affect lists of users returned by * core API functions. * * This includes the groupingid option (when group mode is in use), and * standard activity restrictions using the availability API. */ public function test_user_restrictions() { global $DB, $CFG; $this->resetAfterTest(); // Use existing sample course from setUp. $courseid = $this->workshop->course->id; // Make a test grouping and two groups. $generator = $this->getDataGenerator(); $grouping = $generator->create_grouping(array('courseid' => $courseid)); $group1 = $generator->create_group(array('courseid' => $courseid)); groups_assign_grouping($grouping->id, $group1->id); $group2 = $generator->create_group(array('courseid' => $courseid)); groups_assign_grouping($grouping->id, $group2->id); // Group 3 is not in the grouping. $group3 = $generator->create_group(array('courseid' => $courseid)); // Enrol some students. $roleids = $DB->get_records_menu('role', null, '', 'shortname, id'); $student1 = $generator->create_user(); $student2 = $generator->create_user(); $student3 = $generator->create_user(); $generator->enrol_user($student1->id, $courseid, $roleids['student']); $generator->enrol_user($student2->id, $courseid, $roleids['student']); $generator->enrol_user($student3->id, $courseid, $roleids['student']); // Place students in groups (except student 3). groups_add_member($group1, $student1); groups_add_member($group2, $student2); groups_add_member($group3, $student3); // The existing workshop doesn't have any restrictions, so user lists // should include all three users. $allusers = get_enrolled_users(context_course::instance($courseid)); $result = $this->workshop->get_grouped($allusers); $this->assertCount(4, $result); $users = array_keys($result[0]); sort($users); $this->assertEquals(array($student1->id, $student2->id, $student3->id), $users); $this->assertEquals(array($student1->id), array_keys($result[$group1->id])); $this->assertEquals(array($student2->id), array_keys($result[$group2->id])); $this->assertEquals(array($student3->id), array_keys($result[$group3->id])); // Test get_users_with_capability_sql (via get_potential_authors). $users = $this->workshop->get_potential_authors(false); $this->assertCount(3, $users); $users = $this->workshop->get_potential_authors(false, $group2->id); $this->assertEquals(array($student2->id), array_keys($users)); // Create another test workshop with grouping set. $workshopitem = $this->getDataGenerator()->create_module('workshop', array('course' => $courseid, 'groupmode' => SEPARATEGROUPS, 'groupingid' => $grouping->id)); $cm = get_coursemodule_from_instance('workshop', $workshopitem->id, $courseid, false, MUST_EXIST); $workshopgrouping = new testable_workshop($workshopitem, $cm, $this->workshop->course); // This time the result should only include users and groups in the // selected grouping. $result = $workshopgrouping->get_grouped($allusers); $this->assertCount(3, $result); $users = array_keys($result[0]); sort($users); $this->assertEquals(array($student1->id, $student2->id), $users); $this->assertEquals(array($student1->id), array_keys($result[$group1->id])); $this->assertEquals(array($student2->id), array_keys($result[$group2->id])); // Test get_users_with_capability_sql (via get_potential_authors). $users = $workshopgrouping->get_potential_authors(false); $userids = array_keys($users); sort($userids); $this->assertEquals(array($student1->id, $student2->id), $userids); $users = $workshopgrouping->get_potential_authors(false, $group2->id); $this->assertEquals(array($student2->id), array_keys($users)); // Enable the availability system and create another test workshop with // availability restriction on grouping. $CFG->enableavailability = true; $workshopitem = $this->getDataGenerator()->create_module('workshop', array('course' => $courseid, 'availability' => json_encode(\core_availability\tree::get_root_json(array(\availability_grouping\condition::get_json($grouping->id)), \core_availability\tree::OP_AND, false)))); $cm = get_coursemodule_from_instance('workshop', $workshopitem->id, $courseid, false, MUST_EXIST); $workshoprestricted = new testable_workshop($workshopitem, $cm, $this->workshop->course); // The get_grouped function isn't intended to apply this restriction, // so it should be the same as the base workshop. (Note: in reality, // get_grouped is always run with the parameter being the result of // one of the get_potential_xxx functions, so it works.) $result = $workshoprestricted->get_grouped($allusers); $this->assertCount(4, $result); $this->assertCount(3, $result[0]); // The get_users_with_capability_sql-based functions should apply it. $users = $workshoprestricted->get_potential_authors(false); $userids = array_keys($users); sort($userids); $this->assertEquals(array($student1->id, $student2->id), $userids); $users = $workshoprestricted->get_potential_authors(false, $group2->id); $this->assertEquals(array($student2->id), array_keys($users)); }
/** * Updates all parent cluster's groupings with the existence of a group for this cluster * * @param int $clusterid The cluster to check the parents for * @param boolean $include_children If true, make child cluster-groups trickle up the tree * @return boolean Returns true to satisfy event handlers */ function userset_groups_update_grouping_closure($clusterid, $include_children = false) { global $CFG; $enabled = get_config('elisprogram_usetgroups', 'userset_groupings'); if (empty($enabled) || !userset_groups_grouping_allowed($clusterid)) { return true; } $cluster = new userset($clusterid); //get the group id for this cluster if ($groupid = groups_get_group_by_name(SITEID, $cluster->name)) { //go through the chain of parent clusters while (!empty($cluster->parent)) { $cluster = new userset($cluster->parent); //add this to grouping if applicable $grouping = groups_get_grouping_by_name(SITEID, $cluster->name); if ($grouping = groups_get_grouping($grouping)) { groups_assign_grouping($grouping->id, $groupid); //recurse into children if possible if ($include_children) { //get all child clusters $child_cluster_ids = userset_groups_get_child_usersets($cluster->id); foreach ($child_cluster_ids as $child_cluster_id) { //children only if ($child_cluster_id != $cluster->id) { $child_cluster = new userset($child_cluster_id); //make sure the group exists if ($child_groupid = groups_get_group_by_name(SITEID, $child_cluster->name) and userset_groups_userset_allows_groups($child_cluster->id)) { groups_assign_grouping($grouping->id, $child_groupid); } } } } } } } return true; }
public function process_grouping_group($data) { global $CFG; require_once $CFG->dirroot . '/group/lib.php'; $data = (object) $data; groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded); }
$groupingname = $newgroup->groupingname; if (!($groupingid = groups_get_grouping_by_name($newgroup->courseid, $groupingname))) { $data = new stdClass(); $data->courseid = $newgroup->courseid; $data->name = $groupingname; if ($groupingid = groups_create_grouping($data)) { echo $OUTPUT->notification(get_string('groupingaddedsuccesfully', 'group', $groupingname), 'notifysuccess'); } else { echo $OUTPUT->notification(get_string('groupingnotaddederror', 'error', $groupingname)); continue; } } // if we have reached here we definitely have a groupingid $a = array('groupname' => $groupname, 'groupingname' => $groupingname); try { groups_assign_grouping($groupingid, $groupid); echo $OUTPUT->notification(get_string('groupaddedtogroupingsuccesfully', 'group', $a), 'notifysuccess'); } catch (Exception $e) { echo $OUTPUT->notification(get_string('groupnotaddedtogroupingerror', 'error', $a)); } } } } unset($newgroup); } } echo $OUTPUT->single_button($returnurl, get_string('continue'), 'get'); echo $OUTPUT->footer(); die; } }
/** * Test save grades for a team submission */ public function test_save_grades_with_group_submission() { global $DB, $USER, $CFG; require_once $CFG->dirroot . '/group/lib.php'; $this->resetAfterTest(true); // Create a course and assignment and users. $course = self::getDataGenerator()->create_course(); $teacher = self::getDataGenerator()->create_user(); $teacherrole = $DB->get_record('role', array('shortname' => 'teacher')); $this->getDataGenerator()->enrol_user($teacher->id, $course->id, $teacherrole->id); $groupingdata = array(); $groupingdata['courseid'] = $course->id; $groupingdata['name'] = 'Group assignment grouping'; $grouping = self::getDataGenerator()->create_grouping($groupingdata); $group1data = array(); $group1data['courseid'] = $course->id; $group1data['name'] = 'Team 1'; $group2data = array(); $group2data['courseid'] = $course->id; $group2data['name'] = 'Team 2'; $group1 = self::getDataGenerator()->create_group($group1data); $group2 = self::getDataGenerator()->create_group($group2data); groups_assign_grouping($grouping->id, $group1->id); groups_assign_grouping($grouping->id, $group2->id); $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign'); $params['course'] = $course->id; $params['teamsubmission'] = 1; $params['teamsubmissiongroupingid'] = $grouping->id; $instance = $generator->create_instance($params); $cm = get_coursemodule_from_instance('assign', $instance->id); $context = context_module::instance($cm->id); $assign = new assign($context, $cm, $course); $student1 = self::getDataGenerator()->create_user(); $student2 = self::getDataGenerator()->create_user(); $student3 = self::getDataGenerator()->create_user(); $student4 = self::getDataGenerator()->create_user(); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->getDataGenerator()->enrol_user($student1->id, $course->id, $studentrole->id); $this->getDataGenerator()->enrol_user($student2->id, $course->id, $studentrole->id); $this->getDataGenerator()->enrol_user($student3->id, $course->id, $studentrole->id); $this->getDataGenerator()->enrol_user($student4->id, $course->id, $studentrole->id); groups_add_member($group1->id, $student1->id); groups_add_member($group1->id, $student2->id); groups_add_member($group1->id, $student3->id); groups_add_member($group2->id, $student4->id); $this->setUser($teacher); $feedbackpluginparams = array(); $feedbackpluginparams['files_filemanager'] = 0; $feedbackeditorparams = array('text' => '', 'format' => 1); $feedbackpluginparams['assignfeedbackcomments_editor'] = $feedbackeditorparams; $grades1 = array(); $student1gradeinfo = array(); $student1gradeinfo['userid'] = $student1->id; $student1gradeinfo['grade'] = 50; $student1gradeinfo['attemptnumber'] = -1; $student1gradeinfo['addattempt'] = true; $student1gradeinfo['workflowstate'] = 'released'; $student1gradeinfo['plugindata'] = $feedbackpluginparams; $grades1[] = $student1gradeinfo; $student2gradeinfo = array(); $student2gradeinfo['userid'] = $student2->id; $student2gradeinfo['grade'] = 75; $student2gradeinfo['attemptnumber'] = -1; $student2gradeinfo['addattempt'] = true; $student2gradeinfo['workflowstate'] = 'released'; $student2gradeinfo['plugindata'] = $feedbackpluginparams; $grades1[] = $student2gradeinfo; $this->setExpectedException('invalid_parameter_exception'); // Expect an exception since 2 grades have been submitted for the same team. $result = mod_assign_external::save_grades($instance->id, true, $grades1); $result = external_api::clean_returnvalue(mod_assign_external::save_grades_returns(), $result); $grades2 = array(); $student3gradeinfo = array(); $student3gradeinfo['userid'] = $student3->id; $student3gradeinfo['grade'] = 50; $student3gradeinfo['attemptnumber'] = -1; $student3gradeinfo['addattempt'] = true; $student3gradeinfo['workflowstate'] = 'released'; $student3gradeinfo['plugindata'] = $feedbackpluginparams; $grades2[] = $student3gradeinfo; $student4gradeinfo = array(); $student4gradeinfo['userid'] = $student4->id; $student4gradeinfo['grade'] = 75; $student4gradeinfo['attemptnumber'] = -1; $student4gradeinfo['addattempt'] = true; $student4gradeinfo['workflowstate'] = 'released'; $student4gradeinfo['plugindata'] = $feedbackpluginparams; $grades2[] = $student4gradeinfo; $result = mod_assign_external::save_grades($instance->id, true, $grades2); $result = external_api::clean_returnvalue(mod_assign_external::save_grades_returns(), $result); // There should be no warnings. $this->assertEquals(0, count($result)); $student3grade = $DB->get_record('assign_grades', array('userid' => $student3->id, 'assignment' => $instance->id), '*', MUST_EXIST); $this->assertEquals($student3grade->grade, '50.0'); $student4grade = $DB->get_record('assign_grades', array('userid' => $student4->id, 'assignment' => $instance->id), '*', MUST_EXIST); $this->assertEquals($student4grade->grade, '75.0'); }
/** * Create a test grouping group * @param array|stdClass $record * @throws coding_exception * @return boolean */ public function create_grouping_group($record) { global $DB, $CFG; require_once($CFG->dirroot . '/group/lib.php'); $record = (array)$record; if (empty($record['groupingid'])) { throw new coding_exception('grouping must be present in testing::create_grouping_group() $record'); } if (!isset($record['groupid'])) { throw new coding_exception('group must be present in testing_util::create_grouping_group() $record'); } return groups_assign_grouping($record['groupingid'], $record['groupid']); }
/** * Tests for get_groups() method. */ public function test_get_groups() { $this->resetAfterTest(); $generator = $this->getDataGenerator(); // Create courses. $course1 = $generator->create_course(); $course2 = $generator->create_course(); $course3 = $generator->create_course(); // Create users. $user1 = $generator->create_user(); $user2 = $generator->create_user(); $user3 = $generator->create_user(); // Enrol users on courses. $generator->enrol_user($user1->id, $course1->id); $generator->enrol_user($user2->id, $course2->id); $generator->enrol_user($user3->id, $course2->id); $generator->enrol_user($user3->id, $course3->id); // Create groups. $group1 = $generator->create_group(array('courseid' => $course1->id)); $group2 = $generator->create_group(array('courseid' => $course2->id)); $group3 = $generator->create_group(array('courseid' => $course2->id)); // Assign users to groups and assert the result. $this->assertTrue($generator->create_group_member(array('groupid' => $group1->id, 'userid' => $user1->id))); $this->assertTrue($generator->create_group_member(array('groupid' => $group2->id, 'userid' => $user2->id))); $this->assertTrue($generator->create_group_member(array('groupid' => $group3->id, 'userid' => $user2->id))); $this->assertTrue($generator->create_group_member(array('groupid' => $group2->id, 'userid' => $user3->id))); // Create groupings. $grouping1 = $generator->create_grouping(array('courseid' => $course1->id)); $grouping2 = $generator->create_grouping(array('courseid' => $course2->id)); // Assign and assert group to groupings. groups_assign_grouping($grouping1->id, $group1->id); groups_assign_grouping($grouping2->id, $group2->id); groups_assign_grouping($grouping2->id, $group3->id); // Test with one single group. $modinfo = get_fast_modinfo($course1, $user1->id); $groups = $modinfo->get_groups($grouping1->id); $this->assertCount(1, $groups); $this->assertArrayHasKey($group1->id, $groups); // Test with two groups. $modinfo = get_fast_modinfo($course2, $user2->id); $groups = $modinfo->get_groups(); $this->assertCount(2, $groups); $this->assertTrue(in_array($group2->id, $groups)); $this->assertTrue(in_array($group3->id, $groups)); // Test with no groups. $modinfo = get_fast_modinfo($course3, $user3->id); $groups = $modinfo->get_groups(); $this->assertCount(0, $groups); $this->assertArrayNotHasKey($group1->id, $groups); }
/** * Assign a group to a grouping * * @param array $assignments of arrays with keys groupid, groupingid * @return void * @since Moodle 2.3 */ public static function assign_grouping($assignments) { global $CFG, $DB; require_once "{$CFG->dirroot}/group/lib.php"; $params = self::validate_parameters(self::assign_grouping_parameters(), array('assignments' => $assignments)); $transaction = $DB->start_delegated_transaction(); foreach ($params['assignments'] as $assignment) { // Validate params. $groupingid = $assignment['groupingid']; $groupid = $assignment['groupid']; $grouping = groups_get_grouping($groupingid, 'id, courseid', MUST_EXIST); $group = groups_get_group($groupid, 'id, courseid', MUST_EXIST); if ($DB->record_exists('groupings_groups', array('groupingid' => $groupingid, 'groupid' => $groupid))) { // Continue silently if the group is yet assigned to the grouping. continue; } // Now security checks. $context = context_course::instance($grouping->courseid); try { self::validate_context($context); } catch (Exception $e) { $exceptionparam = new stdClass(); $exceptionparam->message = $e->getMessage(); $exceptionparam->courseid = $group->courseid; throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam); } require_capability('moodle/course:managegroups', $context); groups_assign_grouping($groupingid, $groupid); } $transaction->allow_commit(); }
/** * Testing can_edit_submission */ public function test_can_edit_submission() { global $PAGE, $DB; $this->create_extra_users(); $this->setAdminUser(); // Create assignment (onlinetext). $assign = $this->create_instance(array('assignsubmission_onlinetext_enabled' => 1, 'submissiondrafts' => 1)); $PAGE->set_url(new moodle_url('/mod/assign/view.php', array('id' => $assign->get_course_module()->id))); // Check student can edit their own submission. $this->assertTrue($assign->can_edit_submission($this->students[0]->id, $this->students[0]->id)); // Check student cannot edit others submission. $this->assertFalse($assign->can_edit_submission($this->students[0]->id, $this->students[1]->id)); // Check teacher cannot (by default) edit a students submission. $this->assertFalse($assign->can_edit_submission($this->students[0]->id, $this->teachers[0]->id)); // Add the required capability to edit a student submission. $roleid = create_role('Dummy role', 'dummyrole', 'dummy role description'); assign_capability('mod/assign:editothersubmission', CAP_ALLOW, $roleid, $assign->get_context()->id); role_assign($roleid, $this->teachers[0]->id, $assign->get_context()->id); accesslib_clear_all_caches_for_unit_testing(); // Retest - should now have access. $this->assertTrue($assign->can_edit_submission($this->students[0]->id, $this->teachers[0]->id)); // Force create an assignment with SEPARATEGROUPS. $data = new stdClass(); $data->courseid = $this->course->id; $data->name = 'Grouping'; $groupingid = groups_create_grouping($data); groups_assign_grouping($groupingid, $this->groups[0]->id); groups_assign_grouping($groupingid, $this->groups[1]->id); $assign = $this->create_instance(array('groupingid' => $groupingid, 'groupmode' => SEPARATEGROUPS)); // Add the capability to the new assignment for extra students 0 and 1. assign_capability('mod/assign:editothersubmission', CAP_ALLOW, $roleid, $assign->get_context()->id); role_assign($roleid, $this->extrastudents[0]->id, $assign->get_context()->id); role_assign($roleid, $this->extrastudents[1]->id, $assign->get_context()->id); accesslib_clear_all_caches_for_unit_testing(); // Verify the extra student does not have the capability to edit a submission not in their group. $this->assertFalse($assign->can_edit_submission($this->students[0]->id, $this->extrastudents[1]->id)); // Verify the extra student does have the capability to edit a submission in their group. $this->assertTrue($assign->can_edit_submission($this->students[0]->id, $this->extrastudents[0]->id)); }
if (groups_get_group_by_name($courseid, $group['name'])) { $error = get_string('groupnameexists', 'group', $group['name']); $failed = true; break; } $newgroup = new stdClass(); $newgroup->courseid = $data->courseid; $newgroup->name = $group['name']; $groupid = groups_create_group($newgroup); $createdgroups[] = $groupid; foreach ($group['members'] as $user) { groups_add_member($groupid, $user->id); } if ($grouping) { // Ask this function not to invalidate the cache, we'll do that manually once at the end. groups_assign_grouping($grouping->id, $groupid, null, false); } } // Invalidate the course groups cache seeing as we've changed it. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid)); if ($failed) { foreach ($createdgroups as $groupid) { groups_delete_group($groupid); } if ($createdgrouping) { groups_delete_grouping($createdgrouping); } } else { redirect($returnurl); } }
public function test_group_members_only() { global $CFG; $this->setAdminUser(); $this->create_extra_users(); $CFG->enablegroupmembersonly = true; $grouping = $this->getDataGenerator()->create_grouping(array('courseid' => $this->course->id)); groups_assign_grouping($grouping->id, $this->groups[0]->id); // Force create an assignment with SEPARATEGROUPS. $instance = $this->getDataGenerator()->create_module('assign', array('course' => $this->course->id), array('groupmembersonly' => SEPARATEGROUPS, 'groupingid' => $grouping->id)); $cm = get_coursemodule_from_instance('assign', $instance->id); $context = context_module::instance($cm->id); $assign = new testable_assign($context, $cm, $this->course); $this->setUser($this->teachers[0]); $this->assertCount(5, $assign->list_participants(0, true)); }
function blended_actualizar_agrupamiento($updated_teams, grade_item $item, $blended, $delete_empty) { global $DB; $output = ''; $r = 0; //obtengo el identificador del curso $grouping = blended_get_grouping($item, $blended); //groups_get_grouping($groupingid,'*',MUST_EXIST);//$DB->get_record('groupings',array('id'=>$groupingid)); $courseid = $grouping->courseid; //Obtención de la lista de id de los usuarios introducidos en el curso: $lista_usuarios = get_enrolled_users(context_course::instance($courseid), '', 0, 'u.id,u.idnumber'); $lista_idnumbers = array(); // //Obtenci�n de la lista de 'idnumber' de estos usuarios foreach ($lista_usuarios as $id => $lista) { if (!empty($lista->idnumber)) { $lista_idnumbers[$id] = $lista->idnumber; } // $r++; } // $r=0; // $lista_id=array(); // foreach($lista_idnumbers as $lista){ // $lista_id[$r]=blended_clean_idnumber($lista); // $r++; // } $members_processed = array(); /* Actualizo los grupos actualizando el nombre del grupo y volviendo a introducir los miembros comprobando que el usuario introducido existe */ $r = 0; foreach ($updated_teams as $i => $updatedteam) { // Check members $form_members = array(); foreach ($updatedteam->members as $memberid) { //compruebo que el usuario introducido existe y si es as� que lo guarde if (key_exists($memberid, $lista_idnumbers)) { // user is specified by moodle id if (array_search($memberid, $form_members) === false) { $form_members[] = $memberid; } } else { if (key_exists($memberid, $lista_usuarios)) { // user is specified by id_number if (array_search($memberid, $form_members) === false) { $form_members[] = $memberid; } } } } // Update/Create/delete Group // Create/Update Group information // if (count($form_members) == 0 && $delete_empty) { // An empty membership deletes the group ?? groups_delete_group($updatedteam->id); } else { //guardo los miembros en un array $current_team = blended_get_team($updatedteam->id); if ($current_team) { //si existe lo actualizo $current_team->name = $updatedteam->name; groups_update_group($current_team); } else { if (count($form_members) > 0 || $updatedteam->name != '') { //si no existe lo creo $itemname = blended_get_item_name($item); $data = new stdClass(); $data->courseid = $courseid; $data->name = $updatedteam->name; $data->description_editor['text'] = "Group for activity: '{$itemname}'."; $data->description_editor['format'] = FORMAT_PLAIN; $updatedteam->id = groups_create_group($data); groups_assign_grouping($grouping->id, $updatedteam->id, time(), true); } else { continue; // team with no id, no name, and no components } } $current_team = blended_get_team($updatedteam->id, true); $current_members = array_keys($current_team->members); // find members to remove $members_to_delete = array_diff($current_members, $form_members); $members_to_add = array_diff($form_members, $current_members); // remove old members $need_reelect_leader = false; foreach ($members_to_delete as $memberid) { $need_reelect_leader = $current_team->leaderid == $memberid; blended_remove_team_member($current_team, $memberid); // groups_remove_member($team->id, $member->id); } // update team conf $current_team = blended_get_team($current_team); // Add current members foreach ($members_to_add as $memberid) { groups_add_member($current_team->id, $memberid); if ($memberid == $current_team->leaderid) { $need_reelect_leader = false; } if (key_exists($memberid, $members_processed)) { $members_processed[$memberid]++; } else { $members_processed[$memberid] = 1; } } if (!isset($current_team->leaderid)) { $need_reelect_leader = true; } // check leadership if (count($members_to_add) > 0 && count($members_to_delete) > 0 && $need_reelect_leader) { // elect new leader blended_set_team_leaderid($current_team->id, $form_members[0]); global $OUTPUT, $DB; $a = new stdClass(); $a->username = fullname($DB->get_record('user', array('id' => $form_members[0]))); $a->teamname = $current_team->name; $output .= $OUTPUT->notification(get_string('userpromotedtoleader', 'blended', $a)); } } } return $output; // //Actualizaci�n de las calificaciones(si existen) : comparar los miembros con los de "grade_grades" y si // //no estan en el vector borrarlos de la tabla $grades_moodle = grade_get_grades($courseid, $item->itemtype, $item->itemmodule, $item->iteminstance); $grades_item = $grades_moodle->items[0]; $grades = $grades_item->grades; //Para cada miembro de la tabla miro si esta en el vector $miembros_grupos $cont_gr = 0; $cont_group = 0; foreach ($grades as $grade) { foreach ($miembros_grupos as $miembro_gr) { foreach ($miembro_gr as $miembro) { if ($grade->userid != $miembro->id) { $cont_gr++; } if ($cont_gr == count($miembro_gr)) { $cont_group++; continue; } } if ($cont_gr == count($miembros_grupos)) { print_error("borra en tabla!!"); //Entonces ese id no esta en los mimebros y hay que borrarlo de la tabla $DB->delete_records('grade_grades', array('itemid' => $grade_item->id, 'userid' => $grade->userid)); continue; } } } // $DB->delete_records('grade_grades',array('itemid'=>$grade_item->id)); //Comprobaci�n de la repetici�n de miembros en distintos equipos: $contador = array(); foreach ($lista_idnumbers as $t) { $valor = 1; foreach ($miembros_grupos as $miembro_gr) { foreach ($miembro_gr as $miembro) { if ($miembro->idnumber == $t) { //meto en un contador para el valor del id de cada usuario las veces que se repite $contador[$miembro->id] = $valor; $valor++; } } } } return $contador; }