function test_groups_grouping_matches() { $groupinginfo->name = 'Grouping Testname:' . $this->getLabel(); $groupinginfo->description = 'Grouing Test Description:' . $this->getLabel(); $this->assertTrue($this->groupingid = groups_create_grouping($this->courseid, $groupinginfo)); $this->assertTrue(groups_grouping_matches($this->courseid, $groupinginfo->name, $groupinginfo->description)); }
/** * Distributes students into groups randomly and creates a grouping with those * groups. * * You need to call groups_seed_random_number_generator() at some point in your * script before calling this function. * * Note that this function does not distribute teachers into groups - this still * needs to be done manually. * * @param int $courseid The id of the course that the grouping should belong to * @param int $nostudentspergroup The number of students to put in each group - * this can be set to false if you prefer to specify the number of groups * instead * @param int $nogroups The number of groups - this can be set to false if you * prefer to specify the number of student in each group. If both are specified * then $nostudentspergroup takes precedence. If neither is * specified then the function does nothing and returns false. * @param boolean $distribevenly If $noofstudentspergroup is specified, then * if this is set to true, any leftover students are distributed evenly among * the groups, whereas if it is set to false then they are put in a separate * group. * @param object $groupsettings The default settings to give each group. * This should contain prefix and defaultgroupdescription fields. The groups * are named with the prefix followed by 1, 2, etc. and given the * default group description set. * @param int $groupid If this is not set to false, then only students in the * specified group are distributed into groups, not all the students enrolled on * the course. * @param boolean $alphabetical If this is set to true, then the students are * not distributed randomly but in alphabetical order of last name. * @return int The id of the grouping */ function groups_create_automatic_grouping($courseid, $nostudentspergroup, $nogroups, $distribevenly, $groupingsettings, $groupid = false, $alphabetical = false) { if (!$nostudentspergroup and !$noteacherspergroup and !$nogroups) { $groupingid = false; } else { // Set $userids to the list of students that we want to put into groups // in the grouping if (!$groupid) { $users = get_course_students($courseid); $userids = groups_users_to_userids($users); } else { $userids = groups_get_members($groupid); } // Distribute the users into sets according to the parameters specified $userarrays = groups_distribute_in_random_sets($userids, $nostudentspergroup, $nogroups, $distribevenly, !$alphabetical); if (!$userarrays) { $groupingid = false; } else { // Create the grouping that the groups we create will go into $groupingid = groups_create_grouping($courseid, $groupingsettings); // Get the prefix for the names of each group and default group // description to give each group if (!$groupingsettings->prefix) { $prefix = get_string('defaultgroupprefix', 'groups'); } else { $prefix = $groupingsettings->prefix; } if (!$groupingsettings->defaultgroupdescription) { $defaultgroupdescription = ''; } else { $defaultgroupdescription = $groupingsettings->defaultgroupdescription; } // Now create a group for each set of students, add the group to the // grouping and then add the students $i = 1; foreach ($userarrays as $userids) { $groupsettings->name = $prefix . ' ' . $i; $groupsettings->description = $defaultgroupdescription; $i++; $groupid = groups_create_group($courseid, $groupsettings); $groupadded = groups_add_group_to_grouping($groupid, $groupingid); if (!$groupid or !$groupadded) { $groupingid = false; } else { if ($userids) { foreach ($userids as $userid) { $usersadded = groups_add_member($groupid, $userid); // If unsuccessful just carry on I guess } } } } } } return $groupingid; }
/** * Validate that the version 1 plugin deletes appropriate associations when * deleting a course */ public function test_version1importdeletecoursedeletesassociations() { global $DB, $CFG, $USER; require_once $CFG->dirroot . '/user/lib.php'; require_once $CFG->dirroot . '/lib/gradelib.php'; require_once $CFG->dirroot . '/group/lib.php'; require_once $CFG->dirroot . '/lib/conditionlib.php'; require_once $CFG->dirroot . '/lib/enrollib.php'; require_once $CFG->dirroot . '/tag/lib.php'; require_once $CFG->dirroot . '/lib/questionlib.php'; // Setup. $initialnumcontexts = $DB->count_records('context', array('contextlevel' => CONTEXT_COURSE)); $DB->delete_records('block_instances'); // Set up the course with one section, including default blocks. set_config('defaultblocks_topics', 'search_forums'); set_config('maxsections', 10, 'moodlecourse'); $this->run_core_course_import(array('shortname' => 'deleteassociationsshortname', 'numsections' => 1)); // Create a user record. $record = new stdClass(); $record->username = '******'; $record->password = '******'; $userid = user_create_user($record); // Create a course-level role. $courseid = $DB->get_field('course', 'id', array('shortname' => 'deleteassociationsshortname')); $coursecontext = context_course::instance($courseid); $roleid = create_role('deleterole', 'deleterole', 'deleterole'); set_role_contextlevels($roleid, array(CONTEXT_COURSE)); $enrol = new stdClass(); $enrol->enrol = 'manual'; $enrol->courseid = $courseid; $enrol->status = ENROL_INSTANCE_ENABLED; if (!$DB->record_exists('enrol', (array) $enrol)) { $DB->insert_record('enrol', $enrol); } // Assign the user to the course-level role. enrol_try_internal_enrol($courseid, $userid, $roleid); // Create a grade item. $gradeitem = new grade_item(array('courseid' => $courseid, 'itemtype' => 'manual', 'itemname' => 'testitem'), false); $gradeitem->insert(); $gradegrade = new grade_grade(array('itemid' => $gradeitem->id, 'userid' => $userid), false); // Assign the user a grade. $gradegrade->insert(); // Create a grade outcome. $gradeoutcome = new grade_outcome(array('courseid' => $courseid, 'shortname' => 'bogusshortname', 'fullname' => 'bogusfullname')); $gradeoutcome->insert(); // Create a grade scale. $gradescale = new grade_scale(array('courseid' => $courseid, 'name' => 'bogusname', 'userid' => $userid, 'scale' => 'bogusscale', 'description' => 'bogusdescription')); $gradescale->insert(); // Set a grade setting value. grade_set_setting($courseid, 'bogus', 'bogus'); // Set up a grade letter. $gradeletter = new stdClass(); $gradeletter->contextid = $coursecontext->id; $gradeletter->lowerboundary = 80; $gradeletter->letter = 'A'; $DB->insert_record('grade_letters', $gradeletter); // Set up a forum instance. $forum = new stdClass(); $forum->course = $courseid; $forum->intro = 'intro'; $forum->id = $DB->insert_record('forum', $forum); // Add it as a course module. $forum->module = $DB->get_field('modules', 'id', array('name' => 'forum')); $forum->instance = $forum->id; $cmid = add_course_module($forum); // Set up a completion record. $completion = new stdClass(); $completion->coursemoduleid = $cmid; $completion->completionstate = 0; $completion->userid = 9999; $completion->timemodified = time(); $DB->insert_record('course_modules_completion', $completion); // Set up a completion condition. $forum->id = $cmid; $ci = new condition_info($forum, CONDITION_MISSING_EVERYTHING, false); $ci->add_completion_condition($cmid, COMPLETION_ENABLED); // Set the blocks position. $instances = $DB->get_records('block_instances', array('parentcontextid' => $coursecontext->id)); $page = new stdClass(); $page->context = $coursecontext; $page->pagetype = 'course-view-*'; $page->subpage = false; foreach ($instances as $instance) { blocks_set_visibility($instance, $page, 1); } // Create a group. $group = new stdClass(); $group->name = 'testgroup'; $group->courseid = $courseid; $groupid = groups_create_group($group); // Add the user to the group. groups_add_member($groupid, $userid); // Create a grouping containing our group. $grouping = new stdClass(); $grouping->name = 'testgrouping'; $grouping->courseid = $courseid; $groupingid = groups_create_grouping($grouping); groups_assign_grouping($groupingid, $groupid); // Set up a user tag. tag_set('course', $courseid, array('testtag')); // Add a course-level log. add_to_log($courseid, 'bogus', 'bogus'); // Set up the default course question category. $newcategory = question_make_default_categories(array($coursecontext)); // Create a test question. $question = new stdClass(); $question->qtype = 'truefalse'; $form = new stdClass(); $form->category = $newcategory->id; $form->name = 'testquestion'; $form->correctanswer = 1; $form->feedbacktrue = array('text' => 'bogustext', 'format' => FORMAT_HTML); $form->feedbackfalse = array('text' => 'bogustext', 'format' => FORMAT_HTML); $question = question_bank::get_qtype('truefalse')->save_question($question, $form); if (function_exists('course_set_display')) { // Set a "course display" setting. course_set_display($courseid, 1); } // Make a bogus backup record. $backupcourse = new stdClass(); $backupcourse->courseid = $courseid; $DB->insert_record('backup_courses', $backupcourse); // Add a user lastaccess record. $lastaccess = new stdClass(); $lastaccess->userid = $userid; $lastaccess->courseid = $courseid; $DB->insert_record('user_lastaccess', $lastaccess); // Make a bogus backup log record. $log = new stdClass(); $log->backupid = $courseid; $log->timecreated = time(); $log->loglevel = 1; $log->message = 'bogus'; $DB->insert_record('backup_logs', $log); // Get initial counts. $initialnumcourse = $DB->count_records('course'); $initialnumroleassignments = $DB->count_records('role_assignments'); $initialnumuserenrolments = $DB->count_records('user_enrolments'); $initialnumgradeitems = $DB->count_records('grade_items'); $initialnumgradegrades = $DB->count_records('grade_grades'); $initialnumgradeoutcomes = $DB->count_records('grade_outcomes'); $initialnumgradeoutcomescourses = $DB->count_records('grade_outcomes_courses'); $initialnumscale = $DB->count_records('scale'); $initialnumgradesettings = $DB->count_records('grade_settings'); $initialnumgradeletters = $DB->count_records('grade_letters'); $initialnumforum = $DB->count_records('forum'); $initialnumcoursemodules = $DB->count_records('course_modules'); $initialnumcoursemodulescompletion = $DB->count_records('course_modules_completion'); $initialnumcoursemodulesavailability = $DB->count_records('course_modules_availability'); $initialnumblockinstances = $DB->count_records('block_instances'); $initialnumblockpositions = $DB->count_records('block_positions'); $initialnumgroups = $DB->count_records('groups'); $initialnumgroupsmembers = $DB->count_records('groups_members'); $initialnumgroupings = $DB->count_records('groupings'); $initialnumgroupingsgroups = $DB->count_records('groupings_groups'); $initialnumtaginstance = $DB->count_records('tag_instance'); $initialnumcoursesections = $DB->count_records('course_sections'); $initialnumquestioncategories = $DB->count_records('question_categories'); $initialnumquestion = $DB->count_records('question'); if (self::$coursedisplay) { $initialnumcoursedisplay = $DB->count_records('course_display'); } $initialnumbackupcourses = $DB->count_records('backup_courses'); $initialnumuserlastaccess = $DB->count_records('user_lastaccess'); $initialnumbackuplogs = $DB->count_records('backup_logs'); // Delete the course. $data = array('action' => 'delete', 'shortname' => 'deleteassociationsshortname'); $this->run_core_course_import($data, false); // Validate the result. $this->assertEquals($DB->count_records('course'), $initialnumcourse - 1); $this->assertEquals($DB->count_records('role_assignments'), $initialnumroleassignments - 1); $this->assertEquals($DB->count_records('user_enrolments'), $initialnumuserenrolments - 1); $this->assertEquals($DB->count_records('grade_items'), $initialnumgradeitems - 2); $this->assertEquals($DB->count_records('grade_grades'), $initialnumgradegrades - 1); $this->assertEquals($DB->count_records('grade_outcomes'), $initialnumgradeoutcomes - 1); $this->assertEquals($DB->count_records('grade_outcomes_courses'), $initialnumgradeoutcomescourses - 1); $this->assertEquals($DB->count_records('scale'), $initialnumscale - 1); $this->assertEquals($DB->count_records('grade_settings'), $initialnumgradesettings - 1); $this->assertEquals($DB->count_records('grade_letters'), $initialnumgradeletters - 1); $this->assertEquals($DB->count_records('forum'), $initialnumforum - 1); $this->assertEquals($DB->count_records('course_modules'), $initialnumcoursemodules - 1); /* Uncomment the two lines below when this fix is available: http://tracker.moodle.org/browse/MDL-32988 $this->assertEquals($DB->count_records('course_modules_completion'), $initialnumcourse_modules_completion - 1); $this->assertEquals($DB->count_records('course_modules_availability'), $initialnumcourse_modules_availability - 1); */ $this->assertEquals($initialnumblockinstances - 4, $DB->count_records('block_instances')); $this->assertEquals($DB->count_records('block_positions'), 0); $this->assertEquals($DB->count_records('groups'), $initialnumgroups - 1); $this->assertEquals($DB->count_records('groups_members'), $initialnumgroupsmembers - 1); $this->assertEquals($DB->count_records('groupings'), $initialnumgroupings - 1); $this->assertEquals($DB->count_records('groupings_groups'), $initialnumgroupingsgroups - 1); $this->assertEquals($DB->count_records('log', array('course' => $courseid)), 0); $this->assertEquals($DB->count_records('tag_instance'), $initialnumtaginstance - 1); $this->assertEquals($DB->count_records('course_sections'), $initialnumcoursesections - 1); $this->assertEquals($DB->count_records('question_categories'), $initialnumquestioncategories - 1); $this->assertEquals($DB->count_records('question'), $initialnumquestion - 1); if (self::$coursedisplay) { $this->assertEquals($DB->count_records('course_display'), $initialnumcoursedisplay - 1); } $this->assertEquals($DB->count_records('backup_courses'), $initialnumbackupcourses - 1); $this->assertEquals($DB->count_records('user_lastaccess'), $initialnumuserlastaccess - 1); }
} else { if ($groupid = groups_create_group($newgroup)) { echo $OUTPUT->notification(get_string('groupaddedsuccesfully', 'group', $groupname), 'notifysuccess'); } else { echo $OUTPUT->notification(get_string('groupnotaddederror', 'error', $groupname)); continue; } } // Add group to grouping if (!empty($newgroup->groupingname) || is_numeric($newgroup->groupingname)) { $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)); } }
$table->data[] = $line; } $preview .= print_table($table, true); } else { $grouping = null; $createdgrouping = null; $createdgroups = array(); $failed = false; // prepare grouping if (!empty($data->grouping)) { $groupingname = trim($data->groupingname); if ($data->grouping < 0) { $grouping = new object(); $grouping->courseid = $COURSE->id; $grouping->name = $groupingname; if (!($grouping->id = groups_create_grouping(addslashes_recursive($grouping)))) { $error = 'Can not create grouping'; //should not happen $failed = true; } $createdgrouping = $grouping->id; } else { $grouping = groups_get_grouping($data->grouping); } } // Save the groups data foreach ($groups as $key => $group) { if (groups_get_group_by_name($courseid, $group['name'])) { $error = get_string('groupnameexists', 'group', $group['name']); $failed = true; break;
} $table->data[] = $line; } $preview .= html_writer::table($table); } else { $grouping = null; $createdgrouping = null; $createdgroups = array(); $failed = false; // prepare grouping if (!empty($data->grouping)) { if ($data->grouping < 0) { $grouping = new stdClass(); $grouping->courseid = $COURSE->id; $grouping->name = trim($data->groupingname); $grouping->id = groups_create_grouping($grouping); $createdgrouping = $grouping->id; } else { $grouping = groups_get_grouping($data->grouping); } } // Save the groups data foreach ($groups as $key => $group) { 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'];
/** * Enter description here ... * @param string $newgroupingname * @param int $courseid * @return int id Moodle id of inserted record */ function mass_enroll_add_grouping($newgroupingname, $courseid) { $newgrouping = new StdClass(); $newgrouping->name = $newgroupingname; $newgrouping->courseid = $courseid; return groups_create_grouping($newgrouping); }
} // preprocess data if ($delete) { if (groups_delete_grouping($id)) { redirect(groups_home_url($course->id)); } else { print_error('erroreditgrouping', 'group', groups_home_url($course->id)); } } if ($editform->is_cancelled()) { redirect(groups_home_url($courseid, false, $id, false)); } elseif ($data = $editform->get_data()) { $success = true; if (empty($grouping)) { // New grouping if (!($id = groups_create_grouping($course->id, $data))) { print_error('erroreditgrouping'); } else { $success = (bool) $id; $data->id = $id; } } else { // Updating grouping if (!groups_update_grouping($data, $course->id)) { print_error('groupingnotupdated'); } } if ($success) { redirect(groups_home_url($courseid, false, $id, false)); } else { print_error('erroreditgrouping', 'group', groups_home_url($courseid));
} /// First create the form $editform = new grouping_form(null, compact('editoroptions')); $editform->set_data($grouping); if ($editform->is_cancelled()) { redirect($returnurl); } elseif ($data = $editform->get_data()) { $success = true; if (!has_capability('moodle/course:changeidnumber', $context)) { // Remove the idnumber if the user doesn't have permission to modify it unset($data->idnumber); } if ($data->id) { groups_update_grouping($data, $editoroptions); } else { groups_create_grouping($data, $editoroptions); } redirect($returnurl); } $strgroupings = get_string('groupings', 'group'); $strparticipants = get_string('participants'); if ($id) { $strheading = get_string('editgroupingsettings', 'group'); } else { $strheading = get_string('creategrouping', 'group'); } $PAGE->navbar->add($strparticipants, new moodle_url('/user/index.php', array('id' => $courseid))); $PAGE->navbar->add($strgroupings, new moodle_url('/group/groupings.php', array('id' => $courseid))); $PAGE->navbar->add($strheading); /// Print header $PAGE->set_title($strgroupings);
/** * Creates a grouping for testing purposes * * @param int $courseid The id of the course where the grouping should live * @param string $name The name of the grouping to create * @return int The id of the grouping created */ private function create_test_grouping($courseid, $name = 'rlipgrouping') { global $CFG; require_once $CFG->dirroot . '/group/lib.php'; $data = new stdClass(); $data->courseid = $courseid; $data->name = $name; return groups_create_grouping($data); }
/** * 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'); }
private function process_action_allocation_to_grouping() { $now = time(); if ($this->ratingallocate->accesstimestop < $now) { global $OUTPUT; $allgroupings = groups_get_all_groupings($this->course->id); $groupingidname = ratingallocate_MOD_NAME . '_instid_' . $this->ratingallocateid; // search if there is already a grouping from us $grouping = groups_get_grouping_by_idnumber($this->course->id, $groupingidname); $groupingid = null; if (!$grouping) { // create grouping $data = new stdClass(); $data->name = get_string('groupingname', ratingallocate_MOD_NAME, $this->ratingallocate->name); $data->idnumber = $groupingidname; $data->courseid = $this->course->id; $groupingid = groups_create_grouping($data); } else { $groupingid = $grouping->id; } $group_identifier_from_choice_id = function ($choiceid) { return ratingallocate_MOD_NAME . '_c_' . $choiceid; }; $choices = $this->get_choices_with_allocationcount(); // make a new array containing only the identifiers of the choices $choice_identifiers = array(); foreach ($choices as $id => $choice) { $choice_identifiers[$group_identifier_from_choice_id($choice->id)] = array('key' => $id); } // find all associated groups in this grouping $groups = groups_get_all_groups($this->course->id, 0, $groupingid); // loop through the groups in the grouping: if the choice does not exist anymore -> delete // otherwise mark it foreach ($groups as $group) { if (array_key_exists($group->idnumber, $choice_identifiers)) { // group exists, mark $choice_identifiers[$group->idnumber]['exists'] = true; $choice_identifiers[$group->idnumber]['groupid'] = $group->id; } else { // delete group $group->id groups_delete_group($group->id); } } // create groups groups for new identifiers or empty group if it exists foreach ($choice_identifiers as $group_idnumber => $choice) { if (key_exists('exists', $choice)) { // remove all members groups_delete_group_members_by_group($choice['groupid']); } else { $data = new stdClass(); $data->courseid = $this->course->id; $data->name = $choices[$choice['key']]->title; $data->idnumber = $group_idnumber; $createdid = groups_create_group($data); groups_assign_grouping($groupingid, $createdid); $choice_identifiers[$group_idnumber]['groupid'] = $createdid; } } // add all participants in the correct group $allocations = $this->get_allocations(); foreach ($allocations as $id => $allocation) { $choice_id = $allocation->choiceid; $user_id = $allocation->userid; $choiceidnumber = $group_identifier_from_choice_id($choice_id); groups_add_member($choice_identifiers[$choiceidnumber]['groupid'], $user_id); } // Invalidate the grouping cache for the course cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->course->id)); $renderer = $this->get_renderer(); $renderer->add_notification(get_string('moodlegroups_created', ratingallocate_MOD_NAME), self::NOTIFY_SUCCESS); } return $this->process_default(); }
function restore_create_groupings($restore, $xml_file) { global $CFG, $db; $status = true; $status2 = true; //Check it exists if (!file_exists($xml_file)) { $status = false; } //Get info from xml if ($status) { //groupings will contain the old_id of every group //in backup_ids->info will be the real info (serialized) $groupings = restore_read_xml_groupings($restore, $xml_file); } //Now, if we have anything in groupings, we have to restore that grouping if ($groupings) { if ($groupings !== true) { //Iterate over each group foreach ($groupings as $grouping) { //Get record from backup_ids $data = backup_getid($restore->backup_unique_code, "groupings", $grouping->id); //Init variables $create_grouping = false; if ($data) { //Now get completed xmlized object $info = $data->info; //Now build the GROUPING record structure $gro = new Object(); ///$gro->id = backup_todb($info['GROUPING']['#']['ID']['0']['#']); $gro->name = backup_todb($info['GROUPING']['#']['NAME']['0']['#']); $gro->description = backup_todb($info['GROUPING']['#']['DESCRIPTION']['0']['#']); $gro->timecreated = backup_todb($info['GROUPING']['#']['TIMECREATED']['0']['#']); //Now search if that group exists (by name and description field) in //restore->course_id course $gro_db = groups_grouping_matches($restore->course_id, $gro->name, $gro->description); //If it doesn't exist, create if (!$gro_db) { $create_grouping = true; } //If we must create the group if ($create_grouping) { //The structure is equal to the db, so insert the grouping TODO: RESTORE. $newid = groups_create_grouping($restore->course_id, $gro); } else { //get current group id $newid = $gro_db->id; } if ($newid) { //We have the newid, update backup_ids backup_putid($restore->backup_unique_code, "groupings", $grouping->id, $newid); } //Now restore links from groupings to groups $status2 = restore_create_groupings_groups($newid, $info, $restore); } } //(Now, restore grouping_files) } } else { $status = false; } return $status && $status2; }
$newgroup->enrolmentkey = ''; $newgroup->picture = 0; $newgroup->hidepicture = 0; $newgroup->id = groups_create_group($newgroup); if (!empty($data->groups) && !is_numeric($data->groups)) { $groupingid = substr($data->groups, 2); groups_assign_grouping($groupingid, $newgroup->id); } } } else { if (!empty($data->groupingsadd)) { /// Create a new grouping if (!empty($data->newgroupingsname)) { $newgrouping->name = $data->newgroupingsname; $newgrouping->courseid = $course->id; groups_create_grouping($newgrouping); } } else { if (!empty($data->groupsremovefrom)) { /// Remove group from groupings if (!empty($data->groups) && is_numeric($data->groups)) { if ($groupings = get_records('groupings_groups', 'groupid', $data->groups)) { foreach ($groupings as $grouping) { groups_unassign_grouping($grouping->groupingid, $data->groups); } } } } else { if (!empty($data->groupingsmove)) { /// Move group to groupings if (!empty($data->groups) && is_numeric($data->groups)) {
function blended_create_unique_grouping($grouping_name, $course) { $data = new stdClass(); if ($grouping_name == '') { $grouping_name = get_string('newgrouping', 'group'); } $data->name = $grouping_name; $data->courseid = $course->id; $data->description_editor['text'] = ' '; $data->description_editor['format'] = 1; // Check existence of grouping name $count = 1; do { $prev_grouping = groups_get_grouping_by_name($course->id, $data->name); if ($prev_grouping !== 0) { $data->name = $grouping_name . " ({$count})"; } else { $data->name = $grouping_name; } $count++; } while ($prev_grouping); $groupingid = groups_create_grouping($data); return $groupingid; }
} } } /// First create the form $editform = new grouping_form(); $editform->set_data($grouping); if ($editform->is_cancelled()) { redirect($returnurl); } elseif ($data = $editform->get_data()) { $success = true; if ($data->id) { if (!groups_update_grouping($data)) { error('Error updating grouping'); } } else { if (!groups_create_grouping($data)) { error('Error creating grouping'); } } redirect($returnurl); } $strgroupings = get_string('groupings', 'group'); $strparticipants = get_string('participants'); if ($id) { $strheading = get_string('editgroupingsettings', 'group'); } else { $strheading = get_string('creategrouping', 'group'); } $navlinks = array(array('name' => $strparticipants, 'link' => $CFG->wwwroot . '/user/index.php?id=' . $courseid, 'type' => 'misc'), array('name' => $strgroupings, 'link' => $CFG->wwwroot . '/group/groupings.php?id=' . $courseid, 'type' => 'misc'), array('name' => $strheading, 'link' => '', 'type' => 'misc')); $navigation = build_navigation($navlinks); /// Print header
public function test_get_graders() { $this->create_extra_users(); $this->setUser($this->editingteachers[0]); // Create an assignment with no groups. $assign = $this->create_instance(); $this->assertCount(self::DEFAULT_TEACHER_COUNT + self::DEFAULT_EDITING_TEACHER_COUNT + self::EXTRA_TEACHER_COUNT + self::EXTRA_EDITING_TEACHER_COUNT, $assign->testable_get_graders($this->students[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); $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign'); $params = array('course'=>$this->course->id); $instance = $generator->create_instance($params); $cm = get_coursemodule_from_instance('assign', $instance->id); set_coursemodule_groupmode($cm->id, SEPARATEGROUPS); $cm->groupmode = SEPARATEGROUPS; $cm->groupingid = $groupingid; $context = context_module::instance($cm->id); $assign = new testable_assign($context, $cm, $this->course); $this->setUser($this->students[1]); $this->assertCount(4, $assign->testable_get_graders($this->students[0]->id)); // Note the second student is in a group that is not in the grouping. // This means that we get all graders that are not in a group in the grouping. $this->assertCount(10, $assign->testable_get_graders($this->students[1]->id)); }
function blended_crear_nuevo_agrupamiento_por_alumno($course, $name_team, $mem, $id_assignment, $blended, $currentuserid) { global $DB; //Pongo el nombre al agrupamiento el mismo que posee la actividad $modulos = get_course_mods($course->id); foreach ($modulos as $modulo) { if ($modulo->id == $id_assignment) { $curse_modulos = get_coursemodule_from_instance($modulo->modname, $modulo->instance); $name = $curse_modulos->name; } } //Creaci�n del agrupamiento $data = new object(); $data->name = $name; $data->courseid = $course->id; $data->description_editor['text'] = ' '; $data->description_editor['format'] = 1; $groupingid = groups_create_grouping($data); $groupid = blended_add_new_group($course->id, $name_team, $mem, $groupingid); $DB->insert_record_raw('blended_assign_grouping', array('id_assign' => $id_assignment, 'id_grouping' => $groupingid)); //Actualizo las tablas de blended dependiendo del tipo de creación de equipos: if ($blended->teammethod == 1) { blended_update_teams_by_groups($course->id, $id_assignment, 0, $groupid); } else { blended_update_teams_by_groups($course->id, $id_assignment, 1, $groupid, $currentuserid); } }
/** * Sets up a grouping based on a particular cluster * * @param int $clusterid The id of the chosen cluster * @param string $name The name of the cluster */ function cluster_groups_grouping_helper($clusterid, $name) { global $CFG, $CURMAN; if (!empty($CFG->enablegroupings) && !empty($CURMAN->config->cluster_groupings) && cluster_groups_grouping_allowed($clusterid)) { //determine if flagged as grouping $contextlevel = context_level_base::get_custom_context_level('cluster', 'block_curr_admin'); $contextinstance = get_context_instance($contextlevel, $clusterid); $data = field_data::get_for_context($contextinstance); //retrieve grouping $grouping = groups_get_grouping_by_name(SITEID, $name); //obtain the grouping record if (empty($grouping)) { $grouping = new stdClass(); $grouping->courseid = SITEID; $grouping->name = addslashes($name); $grouping->id = groups_create_grouping($grouping); } else { $grouping = groups_get_grouping($grouping); } //obtain the child cluster ids $child_clusters = cluster_groups_get_child_clusters($clusterid); //add appropriate cluster-groups to the grouping foreach ($child_clusters as $child_cluster) { if ($cluster_record = get_record(CLSTTABLE, 'id', $child_cluster)) { if ($child_cluster_group = groups_get_group_by_name(SITEID, $cluster_record->name)) { if (cluster_groups_grouping_allowed($cluster_record->id)) { groups_assign_grouping($grouping->id, $child_cluster_group); } } } } } }
/** * 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)); }
/** * 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'); } }
public function test_get_graders() { $this->create_extra_users(); $this->setUser($this->editingteachers[0]); // Create an assignment with no groups. $assign = $this->create_instance(); $this->assertCount(self::DEFAULT_TEACHER_COUNT + self::DEFAULT_EDITING_TEACHER_COUNT + self::EXTRA_TEACHER_COUNT + self::EXTRA_EDITING_TEACHER_COUNT, $assign->testable_get_graders($this->students[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); $assign = $this->create_instance(array('groupingid' => $groupingid, 'groupmode' => SEPARATEGROUPS)); $this->setUser($this->students[1]); $this->assertCount(4, $assign->testable_get_graders($this->students[0]->id)); // Note the second student is in a group that is not in the grouping. // This means that we get all graders that are not in a group in the grouping. $this->assertCount(10, $assign->testable_get_graders($this->students[1]->id)); }
private function make_grouping($courseid, $name) { global $CFG; require_once($CFG->dirroot . '/group/lib.php'); return groups_create_grouping((object)array('courseid' => $courseid, 'name' => $name)); }
/** * 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)); }
/** * Sets up a grouping based on a particular cluster * * @param int $clusterid The id of the chosen cluster * @param string $name The name of the cluster */ function userset_groups_grouping_helper($clusterid, $name) { global $CFG, $DB; $enabled = get_config('elisprogram_usetgroups', 'userset_groupings'); if (!empty($enabled) && userset_groups_grouping_allowed($clusterid)) { //determine if flagged as grouping $contextinstance = \local_elisprogram\context\userset::instance($clusterid); $data = field_data::get_for_context($contextinstance); //retrieve grouping $grouping = groups_get_grouping_by_name(SITEID, $name); //obtain the grouping record if (empty($grouping)) { $grouping = new stdClass(); $grouping->courseid = SITEID; $grouping->name = $name; $grouping->id = groups_create_grouping($grouping); } else { $grouping = groups_get_grouping($grouping); } //obtain the child cluster ids $child_clusters = userset_groups_get_child_usersets($clusterid); //add appropriate cluster-groups to the grouping foreach ($child_clusters as $child_cluster) { if ($cluster_record = $DB->get_record(userset::TABLE, array('id' => $child_cluster))) { if ($child_cluster_group = groups_get_group_by_name(SITEID, $cluster_record->name)) { if (userset_groups_grouping_allowed($cluster_record->id)) { groups_assign_grouping($grouping->id, $child_cluster_group); } } } } } }
/** * Create groupings * * @param array $groupings array of grouping description arrays (with keys groupname and courseid) * @return array of newly created groupings * @since Moodle 2.3 */ public static function create_groupings($groupings) { global $CFG, $DB; require_once "{$CFG->dirroot}/group/lib.php"; $params = self::validate_parameters(self::create_groupings_parameters(), array('groupings' => $groupings)); $transaction = $DB->start_delegated_transaction(); $groupings = array(); foreach ($params['groupings'] as $grouping) { $grouping = (object) $grouping; if (trim($grouping->name) == '') { throw new invalid_parameter_exception('Invalid grouping name'); } if ($DB->count_records('groupings', array('courseid' => $grouping->courseid, 'name' => $grouping->name))) { throw new invalid_parameter_exception('Grouping with the same name already exists in the course'); } // 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 = $grouping->courseid; throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam); } require_capability('moodle/course:managegroups', $context); $grouping->descriptionformat = external_validate_format($grouping->descriptionformat); // Finally create the grouping. $grouping->id = groups_create_grouping($grouping); $groupings[] = (array) $grouping; } $transaction->allow_commit(); return $groupings; }
print_error('erroreditgrouping', 'group', $returnurl); } } } } /// First create the form $editform = new grouping_form(); $editform->set_data($grouping); if ($editform->is_cancelled()) { redirect($returnurl); } elseif ($data = $editform->get_data()) { $success = true; if ($data->id) { groups_update_grouping($data); } else { groups_create_grouping($data); } redirect($returnurl); } $strgroupings = get_string('groupings', 'group'); $strparticipants = get_string('participants'); if ($id) { $strheading = get_string('editgroupingsettings', 'group'); } else { $strheading = get_string('creategrouping', 'group'); } $navlinks = array(array('name' => $strparticipants, 'link' => $CFG->wwwroot . '/user/index.php?id=' . $courseid, 'type' => 'misc'), array('name' => $strgroupings, 'link' => $CFG->wwwroot . '/group/groupings.php?id=' . $courseid, 'type' => 'misc'), array('name' => $strheading, 'link' => '', 'type' => 'misc')); $navigation = build_navigation($navlinks); /// Print header print_header_simple($strgroupings, ': ' . $strgroupings, $navigation, '', '', true, '', navmenu($course)); print_heading($strheading);
/** * Create a test grouping for the specified course * * $record should be either an array or a stdClass containing infomation about the grouping to create. * At the very least it needs to contain courseid. * Default values are added for name, description, and descriptionformat if they are not present. * * This function calls {@see groups_create_grouping()} to create the grouping within the database. * * @param array|stdClass $record * @return stdClass grouping record */ public function create_grouping($record) { global $DB, $CFG; require_once $CFG->dirroot . '/group/lib.php'; $this->groupingcount++; $i = $this->groupingcount; $record = (array) $record; if (empty($record['courseid'])) { throw new coding_exception('courseid must be present in phpunit_util::create_grouping() $record'); } if (!isset($record['name'])) { $record['name'] = 'grouping-' . $i; } if (!isset($record['description'])) { $record['description'] = "Test Grouping {$i}\n{$this->loremipsum}"; } if (!isset($record['descriptionformat'])) { $record['descriptionformat'] = FORMAT_MOODLE; } $id = groups_create_grouping((object) $record); return $DB->get_record('groupings', array('id' => $id)); }
/** * Create an enrolment * * @param object $record One record of import data * @param string $filename The import file name, used for logging * @return boolean true on success, otherwise false */ function enrolment_create($record, $filename) { global $CFG, $DB; require_once $CFG->dirroot . '/lib/enrollib.php'; //set initial logging state with respect to enrolments (give non-specific message for now) $this->fslogger->set_enrolment_state(false, false); //field length checking $lengthcheck = $this->check_enrolment_field_lengths($record, $filename); if (!$lengthcheck) { return false; } //data checking if (!($roleid = $DB->get_field('role', 'id', array('shortname' => $record->role)))) { $identifier = $this->mappings['role']; $this->fslogger->log_failure("{$identifier} value of \"{$record->role}\" does not refer " . "to a valid role.", 0, $filename, $this->linenumber, $record, 'enrolment'); return false; } // Check for valid enrolment time if (isset($record->enrolmenttime)) { $value = $this->parse_date($record->enrolmenttime); if ($value === false) { $identifier = $this->mappings['enrolmenttime']; $this->fslogger->log_failure("{$identifier} value of \"{$record->enrolmenttime}\" is not a valid date in " . "MM/DD/YYYY, DD-MM-YYYY, YYYY.MM.DD, or MMM/DD/YYYY format.", 0, $filename, $this->linenumber, $record, "enrolment"); return false; } } // Check for valid complete time if (isset($record->completetime)) { $value = $this->parse_date($record->completetime); if ($value === false) { $identifier = $this->mappings['completetime']; $this->fslogger->log_failure("{$identifier} value of \"{$record->completetime}\" is not a valid date in " . "MM/DD/YYYY, DD-MM-YYYY, YYYY.MM.DD, or MMM/DD/YYYY format.", 0, $filename, $this->linenumber, $record, "enrolment"); return false; } } //find existing user record if (!($userid = $this->get_userid_from_record($record, $filename))) { return false; } //track context info $contextinfo = $this->get_contextinfo_from_record($record, $filename); if ($contextinfo == false) { return false; } list($contextlevel, $context) = $contextinfo; //make sure the role is assignable at the course context level if (!$DB->record_exists('role_context_levels', array('roleid' => $roleid, 'contextlevel' => $contextlevel))) { $this->fslogger->log_failure("The role with shortname \"{$record->role}\" is not assignable " . "on the {$record->context} context level.", 0, $filename, $this->linenumber, $record, "enrolment"); return false; } //note: this seems redundant but will be useful for error messages later $params = array('roleid' => $roleid, 'contextid' => $context->id, 'userid' => $userid, 'component' => '', 'itemid' => 0); $role_assignment_exists = $DB->record_exists('role_assignments', $params); //track whether an enrolment exists $enrolment_exists = false; if ($contextlevel == CONTEXT_COURSE) { $enrolment_exists = is_enrolled($context, $userid); } //after this point, general error messages should contain role assignment info //they should also contain enrolment info if the context is a course $track_enrolments = $record->context == 'course'; $this->fslogger->set_enrolment_state(true, $track_enrolments); //track the group and grouping specified $groupid = 0; $groupingid = 0; //duplicate group / grouping name checks and name validity checking if ($record->context == 'course' && isset($record->group)) { $count = $DB->count_records('groups', array('name' => $record->group, 'courseid' => $context->instanceid)); $creategroups = get_config('dhimport_version1', 'creategroupsandgroupings'); if ($count > 1) { //ambiguous $identifier = $this->mappings['group']; $this->fslogger->log_failure("{$identifier} value of \"{$record->group}\" refers to multiple " . "groups in course with shortname \"{$record->instance}\".", 0, $filename, $this->linenumber, $record, 'enrolment'); return false; } else { if ($count == 0 && empty($creategroups)) { //does not exist and not creating $identifier = $this->mappings['group']; $this->fslogger->log_failure("{$identifier} value of \"{$record->group}\" does not refer to " . "a valid group in course with shortname \"{$record->instance}\".", 0, $filename, $this->linenumber, $record, "enrolment"); return false; } else { //exact group exists $groupid = groups_get_group_by_name($context->instanceid, $record->group); } } if (isset($record->grouping)) { $count = $DB->count_records('groupings', array('name' => $record->grouping, 'courseid' => $context->instanceid)); if ($count > 1) { //ambiguous $identifier = $this->mappings['grouping']; $this->fslogger->log_failure("{$identifier} value of \"{$record->grouping}\" refers to multiple " . "groupings in course with shortname \"{$record->instance}\".", 0, $filename, $this->linenumber, $record, "enrolment"); return false; } else { if ($count == 0 && empty($creategroups)) { //does not exist and not creating $identifier = $this->mappings['grouping']; $this->fslogger->log_failure("{$identifier} value of \"{$record->grouping}\" does not refer to " . "a valid grouping in course with shortname \"{$record->instance}\".", 0, $filename, $this->linenumber, $record, "enrolment"); return false; } else { //exact grouping exists $groupingid = groups_get_grouping_by_name($context->instanceid, $record->grouping); } } } } //string to describe the user $user_descriptor = $this->get_user_descriptor($record); //string to describe the context instance $context_descriptor = $this->get_context_descriptor($record); //going to collect all messages for this action $logmessages = array(); if ($record->context == 'course') { // Set enrolment start and end time if specified, otherwise set enrolment time to 'now' to allow immediate access. $timestart = empty($record->enrolmenttime) ? time() : $this->parse_date($record->enrolmenttime); $timeend = empty($record->completetime) ? 0 : $this->parse_date($record->completetime); if ($role_assignment_exists && !$enrolment_exists) { // Role assignment already exists, so just enrol the user. enrol_try_internal_enrol($context->instanceid, $userid, null, $timestart, $timeend); } else { if (!$enrolment_exists) { // Role assignment does not exist, so enrol and assign role. enrol_try_internal_enrol($context->instanceid, $userid, $roleid, $timestart, $timeend); //collect success message for logging at end of action $logmessages[] = "User with {$user_descriptor} successfully assigned role with shortname " . "\"{$record->role}\" on {$context_descriptor}."; } else { if (!$role_assignment_exists) { //just assign the role role_assign($roleid, $userid, $context->id); //collect success message for logging at end of action $logmessages[] = "User with {$user_descriptor} successfully assigned role with " . "shortname \"{$record->role}\" on {$context_descriptor}."; } else { //duplicate enrolment attempt $this->fslogger->log_failure("User with {$user_descriptor} is already assigned role " . "with shortname \"{$record->role}\" on {$context_descriptor}. " . "User with {$user_descriptor} is already enrolled in course with " . "shortname \"{$record->instance}\".", 0, $filename, $this->linenumber, $record, 'enrolment'); return false; } } } //collect success message for logging at end of action if (!$enrolment_exists) { $logmessages[] = "User with {$user_descriptor} enrolled in course with shortname \"{$record->instance}\"."; if (!empty($context->instanceid) && !empty($userid)) { $this->newenrolmentemail($userid, $context->instanceid); } } } else { if ($role_assignment_exists) { //role assignment already exists, so this action serves no purpose $this->fslogger->log_failure("User with {$user_descriptor} is already assigned role " . "with shortname \"{$record->role}\" on {$context_descriptor}.", 0, $filename, $this->linenumber, $record, 'enrolment'); return false; } role_assign($roleid, $userid, $context->id); //collect success message for logging at end of action $logmessages[] = "User with {$user_descriptor} successfully assigned role with shortname \"{$record->role}\" on {$context_descriptor}."; } if ($record->context == 'course' && isset($record->group)) { //process specified group require_once $CFG->dirroot . '/lib/grouplib.php'; require_once $CFG->dirroot . '/group/lib.php'; if ($groupid == 0) { //need to create the group $data = new stdClass(); $data->courseid = $context->instanceid; $data->name = $record->group; $groupid = groups_create_group($data); //collect success message for logging at end of action $logmessages[] = "Group created with name \"{$record->group}\"."; } if (groups_is_member($groupid, $userid)) { //error handling $logmessages[] = "User with {$user_descriptor} is already assigned to group with name \"{$record->group}\"."; } else { //try to assign the user to the group if (!groups_add_member($groupid, $userid)) { //should never happen } //collect success message for logging at end of action $logmessages[] = "Assigned user with {$user_descriptor} to group with name \"{$record->group}\"."; } if (isset($record->grouping)) { //process the specified grouping if ($groupingid == 0) { //need to create the grouping $data = new stdClass(); $data->courseid = $context->instanceid; $data->name = $record->grouping; $groupingid = groups_create_grouping($data); //collect success message for logging at end of action $logmessages[] = "Created grouping with name \"{$record->grouping}\"."; } //assign the group to the grouping if ($DB->record_exists('groupings_groups', array('groupingid' => $groupingid, 'groupid' => $groupid))) { //error handling $logmessages[] = "Group with name \"{$record->group}\" is already assigned to grouping with name \"{$record->grouping}\"."; } else { if (!groups_assign_grouping($groupingid, $groupid)) { //should never happen } //collect success message for logging at end of action $logmessages[] = "Assigned group with name \"{$record->group}\" to grouping with name \"{$record->grouping}\"."; } } } //log success $this->fslogger->log_success(implode(' ', $logmessages), 0, $filename, $this->linenumber); if (!$this->fslogger->get_logfile_status()) { return false; } return true; }