function validation($data, $files)
 {
     global $COURSE, $CFG;
     $errors = parent::validation($data, $files);
     $textlib = textlib_get_instance();
     $name = trim(stripslashes($data['name']));
     if ($data['id'] and $group = get_record('groups', 'id', $data['id'])) {
         if ($textlib->strtolower($group->name) != $textlib->strtolower($name)) {
             if (groups_get_group_by_name($COURSE->id, $name)) {
                 $errors['name'] = get_string('groupnameexists', 'group', $name);
             }
         }
         if (!empty($CFG->enrol_manual_usepasswordpolicy) and $data['enrolmentkey'] != '' and $group->enrolmentkey !== $data['enrolmentkey']) {
             // enforce password policy only if changing password
             $errmsg = '';
             if (!check_password_policy($data['enrolmentkey'], $errmsg)) {
                 $errors['enrolmentkey'] = $errmsg;
             }
         }
     } else {
         if (groups_get_group_by_name($COURSE->id, $name)) {
             $errors['name'] = get_string('groupnameexists', 'group', $name);
         }
     }
     return $errors;
 }
Exemple #2
0
 function validation($data, $files)
 {
     global $COURSE;
     $errors = parent::validation($data, $files);
     $name = trim(stripslashes($data['name']));
     if ($data['id'] and $group = get_record('groups', 'id', $data['id'])) {
         if ($group->name != $name) {
             if (groups_get_group_by_name($COURSE->id, $name)) {
                 $errors['name'] = get_string('groupnameexists', 'group', $name);
             }
         }
     } else {
         if (groups_get_group_by_name($COURSE->id, $name)) {
             $errors['name'] = get_string('groupnameexists', 'group', $name);
         }
     }
     return $errors;
 }
function blended_update_grouping($courseid, $teamname, $mem, $groupingid, $ya, $groupid = null)
{
    if ($groupid == null) {
        $group_id = groups_get_group_by_name($courseid, $teamname);
        if ($group_id != false) {
            blended_update_group($courseid, $teamname, $mem, $group_id, $ya);
        }
        if ($group_id == false) {
            $id_group = blended_add_new_group($courseid, $teamname, $mem, $groupingid, $ya);
            return $id_group;
        }
    } else {
        if ($groupid != false) {
            blended_update_group($courseid, $teamname, $mem, $groupid, $ya);
        }
        if ($groupid == false) {
            $id_group = blended_add_new_group($courseid, $teamname, $mem, $groupingid, $ya);
            return $id_group;
        }
    }
}
 function validation($data, $files)
 {
     global $COURSE;
     $errors = parent::validation($data, $files);
     $description = $data['description'];
     if (strlen($description) > self::DESCRIPTION_MAXLEN) {
         $errors['description'] = get_string('maxcharlenreached', 'mod_groupselect');
     }
     $password = $data['password'];
     if (strlen($password) > self::PASSWORD_MAXLEN) {
         $errors['password'] = get_string('maxcharlenreached', 'mod_groupselect');
     }
     $groupname = $data['groupname'];
     if (strlen($groupname) > self::GROUP_NAME_MAXLEN) {
         $errors['groupname'] = get_string('maxcharlenreached', 'mod_groupselect');
     }
     if (groups_get_group_by_name($COURSE->id, $groupname)) {
         $errors['groupname'] = get_string('groupnameexists', 'group', $groupname);
     }
     return $errors;
 }
 function validation($data)
 {
     global $COURSE;
     $errors = array();
     $name = stripslashes($data['name']);
     if ($data['id'] and $group = get_record('groups', 'id', $data['id'])) {
         if ($group->name != $name) {
             if (groups_get_group_by_name($COURSE->id, $name)) {
                 $errors['name'] = get_string('groupnameexists', 'group', $name);
             }
         }
     } else {
         if (groups_get_group_by_name($COURSE->id, $name)) {
             $errors['name'] = get_string('groupnameexists', 'group', $name);
         }
     }
     if (count($errors) > 0) {
         return $errors;
     } else {
         return true;
     }
 }
 /**
  * Validate that our constant expect end result is reached
  */
 private function validate_end_result()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/lib/grouplib.php';
     // Validate group creation.
     $groupid = groups_get_group_by_name(SITEID, 'testusersetname');
     $this->assertNotEquals(false, $groupid);
     // Validate user-group assignment.
     $userid = $DB->get_field('user', 'id', array('username' => 'testuserusername'));
     $this->assertTrue(groups_is_member($groupid, $userid));
     // Validate grouping creation.
     $groupingid = groups_get_grouping_by_name(SITEID, 'testusersetname');
     $this->assertNotEquals(false, $groupingid);
     // Validate group-grouping assignment.
     $this->assertTrue($DB->record_exists('groupings_groups', array('groupingid' => $groupingid, 'groupid' => $groupid)));
 }
Exemple #7
0
         } else {
             $newgroup->courseid = $id;
         }
     }
     //if courseid is set
     if (isset($newgroup->courseid)) {
         $newgroup->courseid = (int) $newgroup->courseid;
         $newgroup->timecreated = time();
         $linenum++;
         $groupname = $newgroup->name;
         $newgrpcoursecontext = get_context_instance(CONTEXT_COURSE, $newgroup->courseid);
         ///Users cannot upload groups in courses they cannot update.
         if (!has_capability('moodle/course:managegroups', $newgrpcoursecontext)) {
             echo $OUTPUT->notification(get_string('nopermissionforcreation', 'group', $groupname));
         } else {
             if ($groupid = groups_get_group_by_name($newgroup->courseid, $groupname) || !($newgroup->id = groups_create_group($newgroup))) {
                 //Record not added - probably because group is already registered
                 //In this case, output groupname from previous registration
                 if ($groupid) {
                     echo $OUTPUT->notification("{$groupname} :" . get_string('groupexistforcourse', 'error', $groupname));
                 } else {
                     echo $OUTPUT->notification(get_string('groupnotaddederror', 'error', $groupname));
                 }
             } else {
                 echo $OUTPUT->notification(get_string('groupaddedsuccesfully', 'group', $groupname));
             }
         }
     }
     //close courseid validity check
     unset($newgroup);
 }
Exemple #8
0
/**
 * @param string $name group name
 * @param int $courseid course
 * @return string or false 
 */
function mass_enroll_group_exists($name, $courseid) {
    return groups_get_group_by_name($courseid, $name);
}
 public function test_groups_get_group_by_name()
 {
     $this->resetAfterTest(true);
     $generator = $this->getDataGenerator();
     // Create a course category and course.
     $cat = $generator->create_category(array('parent' => 0));
     $course = $generator->create_course(array('category' => $cat->id));
     $name1 = 'Name 1';
     $name2 = 'Name 2';
     // Test with an empty and a null idnumber.
     $this->assertFalse(groups_get_group_by_name($course->id, ''));
     $this->assertFalse(groups_get_group_by_name($course->id, null));
     // Even when a group exists.
     $generator->create_group(array('courseid' => $course->id));
     $this->assertFalse(groups_get_group_by_name($course->id, ''));
     $this->assertFalse(groups_get_group_by_name($course->id, null));
     // Test with a valid name, but one that doesn't exist yet.
     $this->assertFalse(groups_get_group_by_name($course->id, $name1));
     $this->assertFalse(groups_get_group_by_name($course->id, $name2));
     // We should now have a valid group returned by the name search.
     $group1 = $generator->create_group(array('courseid' => $course->id, 'name' => $name1));
     $this->assertEquals($group1->id, groups_get_group_by_name($course->id, $name1));
     $this->assertFalse(groups_get_group_by_name($course->id, $name2));
     // We should now have a two valid groups returned by the name search.
     $group2 = $generator->create_group(array('courseid' => $course->id, 'name' => $name2));
     $this->assertEquals($group1->id, groups_get_group_by_name($course->id, $name1));
     $this->assertEquals($group2->id, groups_get_group_by_name($course->id, $name2));
     // Delete a group.
     $this->assertTrue(groups_delete_group($group1));
     $this->assertFalse(groups_get_group_by_name($course->id, $name1));
     $this->assertEquals($group2->id, groups_get_group_by_name($course->id, $name2));
     /*
      * Group idnumbers are unique within a course so test that we don't
      * retrieve groups for the first course.
      */
     // Create a second course.
     $course = $generator->create_course(array('category' => $cat->id));
     // An empty name should always return a false value.
     $this->assertFalse(groups_get_group_by_name($course->id, ''));
     $this->assertFalse(groups_get_group_by_name($course->id, null));
     // Our existing names shouldn't be returned here as we're in a different course.
     $this->assertFalse(groups_get_group_by_name($course->id, $name1));
     $this->assertFalse(groups_get_group_by_name($course->id, $name2));
     // We should be able to reuse the idnumbers again since this is a different course.
     $group1 = $generator->create_group(array('courseid' => $course->id, 'name' => $name1));
     $this->assertEquals($group1->id, groups_get_group_by_name($course->id, $name1));
     $group2 = $generator->create_group(array('courseid' => $course->id, 'name' => $name2));
     $this->assertEquals($group2->id, groups_get_group_by_name($course->id, $name2));
 }
Exemple #10
0
function options_from_csv($groupreg, $courseid, $csv)
{
    // Set new option_repeats as count(csv-lines)
    $option_repeats = count($csv);
    // Initialize settings
    $groupreg->option = array();
    $groupreg->limit = array();
    $groupreg->grouping = array();
    $groupreg->optionid = array();
    $groupreg->option_repeats = $option_repeats;
    foreach ($csv as $row) {
        // get group id
        $groupname = trim(filter_var($row['name']));
        // TODO attention: Duplicate group names will lead to unexpected behavior!
        $option = groups_get_group_by_name($courseid, $groupname);
        // maxanswer
        $limit = intval($row['maxanswers']);
        // grouping
        $grouping = isset($row['grouping']) ? filter_var($row['grouping']) : '';
        // default optionid = 0
        $optionid = 0;
        array_push($groupreg->option, $option);
        array_push($groupreg->limit, $limit);
        array_push($groupreg->grouping, $grouping);
        array_push($groupreg->optionid, $optionid);
    }
    return $groupreg;
}
         $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;
     }
     $newgroup = new object();
     $newgroup->courseid = $data->courseid;
     $newgroup->name = $group['name'];
     if (!($groupid = groups_create_group(addslashes_recursive($newgroup)))) {
         $error = 'Can not create group!';
         // should not happen
         $failed = true;
         break;
     }
     $createdgroups[] = $groupid;
     foreach ($group['members'] as $user) {
Exemple #12
0
/**
 * 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;
}
Exemple #13
0
                 $newgroup->courseid = $mycourse->id;
             } else {
                 //else use use current id
                 $newgroup->courseid = $id;
             }
         }
         //if courseid is set
         if (isset($newgroup->courseid)) {
             $linenum++;
             $groupname = $newgroup->name;
             $newgrpcoursecontext = get_context_instance(CONTEXT_COURSE, $newgroup->courseid);
             ///Users cannot upload groups in courses they cannot update.
             if (!has_capability('moodle/course:managegroups', $newgrpcoursecontext) or !is_enrolled($newgrpcoursecontext) and !has_capability('moodle/course:view', $newgrpcoursecontext)) {
                 echo $OUTPUT->notification(get_string('nopermissionforcreation', 'group', $groupname));
             } else {
                 if ($groupid = groups_get_group_by_name($newgroup->courseid, $groupname)) {
                     echo $OUTPUT->notification("{$groupname} :" . get_string('groupexistforcourse', 'error', $groupname));
                 } else {
                     if (groups_create_group($newgroup)) {
                         echo $OUTPUT->notification(get_string('groupaddedsuccesfully', 'group', $groupname), 'notifysuccess');
                     } else {
                         echo $OUTPUT->notification(get_string('groupnotaddederror', 'error', $groupname));
                     }
                 }
             }
         }
         unset($newgroup);
     }
 }
 echo $OUTPUT->single_button($returnurl, get_string('continue'), 'get');
 echo $OUTPUT->footer();
Exemple #14
0
         $userserrors++;
         continue;
     }
 }
 for ($i = 0; $i < 5; $i++) {
     if ($addcourse[$i] && !$course[$i]) {
         notify(get_string('unknowncourse', 'error', $addcourse[$i]));
     }
 }
 for ($i = 0; $i < 5; $i++) {
     $groupid[$i] = 0;
     if ($addgroup[$i]) {
         if (!$course[$i]) {
             notify(get_string('coursegroupunknown', 'error', $addgroup[$i]));
         } else {
             if ($gid = groups_get_group_by_name($course[$i]->id, $addgroup[$i])) {
                 $groupid[$i] = $gid;
             } else {
                 notify(get_string('groupunknown', 'error', $addgroup[$i]));
             }
         }
     }
 }
 for ($i = 0; $i < 5; $i++) {
     /// Enrol into courses if necessary
     if ($course[$i]) {
         if (isset($addrole[$i])) {
             $coursecontext = get_context_instance(CONTEXT_COURSE, $course[$i]->id);
             if (!user_can_assign($coursecontext, $addrole[$i])) {
                 notify('--> Can not assign role in course');
                 //TODO: localize
Exemple #15
0
/**
 * 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;
}
// action confirmed, perform it
if ($confirm) {
    if (empty($SESSION->bulk_courses)) {
        redirect($return);
    }
    // for each course, get the default role if needed and check the selected group
    foreach ($SESSION->bulk_courses as $course) {
        $context = get_context_instance(CONTEXT_COURSE, $course);
        $in = implode(',', $SESSION->bulk_users);
        $groupid = false;
        if ($roleassign == 0) {
            $defrole = get_default_course_role($context);
            $roleassign = $defrole->id;
        }
        if (!empty($groupname)) {
            $groupid = groups_get_group_by_name($course, stripslashes($groupname));
        }
        // for each user, enrol them to the course with the selected role,
        // and add to the selected group if available
        if ($rs = get_recordset_select('user', "id IN ({$in})")) {
            while ($user = rs_fetch_next_record($rs)) {
                role_assign($roleassign, $user->id, 0, $context->id, 0, 0, $hidden);
                if ($groupid !== false) {
                    groups_add_member($groupid, $user->id);
                }
            }
        }
        rs_close($rs);
    }
    // we're done, exit now
    admin_externalpage_print_header();
 /**
  * Create a moodle group for each of the users in $users
  *
  * @param stdClass[] $users array of users-objects for which to create the groups
  * @param string $namescheme scheme determining how to name the created groups
  * @param int $grouping -1 => create new grouping,
  *                       0 => no grouping,
  *                      >0 => assign groups to grouping with that id
  * @param string $groupingname optional name for created grouping
  * @param bool $previewonly optional only show preview of created groups
  * @return array ( 0 => error, 1 => message )
  */
 private function create_one_person_groups($users, $namescheme = "[idnumber]", $grouping = 0, $groupingname = null, $previewonly = false)
 {
     global $DB, $PAGE, $USER;
     require_capability('mod/grouptool:create_groups', $this->context);
     // Allocate members from the selected role to groups!
     $usercnt = count($users);
     // Prepare group data!
     $groups = array();
     $i = 0;
     $digits = ceil(log10(count($users)));
     foreach ($users as $user) {
         $groups[$i] = array();
         $groups[$i]['name'] = $this->groups_parse_name(trim($namescheme), $i, $user, $digits);
         $groups[$i]['member'] = $user;
         $i++;
     }
     if ($previewonly) {
         $error = false;
         $table = new html_table();
         $table->head = array(get_string('groupscount', 'group', $usercnt), get_string('groupmembers', 'group'));
         $table->size = array('30%', '70%');
         $table->align = array('left', 'left');
         $table->width = '90%';
         $table->data = array();
         $groupnames = array();
         foreach ($groups as $group) {
             $line = array();
             if (groups_get_group_by_name($this->course->id, $group['name']) || in_array($group['name'], $groupnames)) {
                 $error = true;
                 if (in_array($group['name'], $groupnames)) {
                     $line[] = '<span class="notifyproblem">' . get_string('nameschemenotunique', 'grouptool', $group['name']) . '</span>';
                 } else {
                     $line[] = '<span class="notifyproblem">' . get_string('groupnameexists', 'group', $group['name']) . '</span>';
                 }
             } else {
                 $groupnames[] = $group['name'];
                 $line[] = $group['name'];
             }
             $line[] = fullname($group['member']);
             $table->data[] = $line;
         }
         return array(0 => $error, 1 => html_writer::table($table));
     } else {
         $newgrouping = null;
         $createdgrouping = null;
         $createdgroups = array();
         $failed = false;
         // Prepare grouping!
         if (!empty($grouping)) {
             if ($grouping < 0) {
                 $grouping = new stdClass();
                 $grouping->courseid = $this->course->id;
                 $grouping->name = trim($groupingname);
                 $grouping->id = groups_create_grouping($grouping);
                 $createdgrouping = $grouping->id;
             } else {
                 $grouping = groups_get_grouping($grouping);
             }
         }
         // Trigger group_creation_started event.
         $groupingid = !empty($grouping) ? $grouping->id : 0;
         \mod_grouptool\event\group_creation_started::create_person($this->cm, $namescheme, $groupingid)->trigger();
         // Save the groups data!
         foreach ($groups as $key => $group) {
             if (groups_get_group_by_name($this->course->id, $group['name'])) {
                 $error = get_string('groupnameexists', 'group', $group['name']);
                 $failed = true;
                 break;
             }
             $newgroup = new stdClass();
             $newgroup->courseid = $this->course->id;
             $newgroup->name = $group['name'];
             $groupid = groups_create_group($newgroup);
             // Insert into agrp-table!
             $newagrp = new stdClass();
             $newagrp->groupid = $groupid;
             $newagrp->grouptoolid = $this->grouptool->id;
             $newagrp->sort_order = 999999;
             if ($this->grouptool->allow_reg == true) {
                 $newagrp->active = 1;
             } else {
                 $newagrp->active = 0;
             }
             if (!$DB->record_exists('grouptool_agrps', array('grouptoolid' => $this->grouptool->id, 'groupid' => $groupid))) {
                 $newagrp->id = $DB->insert_record('grouptool_agrps', $newagrp, true);
             } else {
                 /* This is also the case if eventhandlers work properly
                  * because group gets allready created in eventhandler
                  */
                 $newagrp->id = $DB->get_field('grouptool_agrps', 'id', array('grouptoolid' => $this->grouptool->id, 'groupid' => $groupid));
                 if ($this->grouptool->allow_reg == true) {
                     $DB->set_field('grouptool_agrps', 'active', 1, array('id' => $newagrp->id));
                 }
             }
             $createdgroups[] = $groupid;
             groups_add_member($groupid, $group['member']->id);
             $usrreg = new stdClass();
             $usrreg->userid = $group['member']->id;
             $usrreg->agrpid = $newagrp->id;
             $usrreg->timestamp = time();
             $usrreg->modified_by = $USER->id;
             $attr = array('userid' => $group['member']->id, 'agrpid' => $newagrp->id);
             if (!$DB->record_exists('grouptool_registered', $attr)) {
                 $DB->insert_record('grouptool_registered', $usrreg);
             } else {
                 $DB->set_field('grouptool_registered', 'modified_by', $USER->id, $attr);
             }
             if ($grouping) {
                 groups_assign_grouping($grouping->id, $groupid);
             }
         }
         if ($failed) {
             foreach ($createdgroups as $groupid) {
                 groups_delete_group($groupid);
             }
             if ($createdgrouping) {
                 groups_delete_grouping($createdgrouping);
             }
             return array(0 => $failed, 1 => get_string('group_creation_failed', 'grouptool') . html_writer::empty_tag('br') . $error);
         } else {
             // Trigger agrps updated via groupcreation event.
             $groupingid = !empty($grouping) ? $grouping->id : 0;
             \mod_grouptool\event\agrps_updated::create_groupcreation($this->cm, $namescheme, count($groups), $groupingid)->trigger();
             return array(0 => $failed, 1 => get_string('groups_created', 'grouptool'));
         }
     }
 }
Exemple #18
0
 /**
  * Form validation
  *
  * @param array $data
  * @param array $files
  * @return array $errors An array of errors
  */
 function validation($data, $files)
 {
     global $COURSE, $DB, $CFG;
     $errors = parent::validation($data, $files);
     $name = trim($data['name']);
     if (isset($data['idnumber'])) {
         $idnumber = trim($data['idnumber']);
     } else {
         $idnumber = '';
     }
     if ($data['id'] and $group = $DB->get_record('groups', array('id' => $data['id']))) {
         if (core_text::strtolower($group->name) != core_text::strtolower($name)) {
             if (groups_get_group_by_name($COURSE->id, $name)) {
                 $errors['name'] = get_string('groupnameexists', 'group', $name);
             }
         }
         if (!empty($idnumber) && $group->idnumber != $idnumber) {
             if (groups_get_group_by_idnumber($COURSE->id, $idnumber)) {
                 $errors['idnumber'] = get_string('idnumbertaken');
             }
         }
         if ($data['enrolmentkey'] != '') {
             $errmsg = '';
             if (!empty($CFG->groupenrolmentkeypolicy) && $group->enrolmentkey !== $data['enrolmentkey'] && !check_password_policy($data['enrolmentkey'], $errmsg)) {
                 // Enforce password policy when the password is changed.
                 $errors['enrolmentkey'] = $errmsg;
             } else {
                 // Prevent twice the same enrolment key in course groups.
                 $sql = "SELECT id FROM {groups} WHERE id <> :groupid AND courseid = :courseid AND enrolmentkey = :key";
                 $params = array('groupid' => $data['id'], 'courseid' => $COURSE->id, 'key' => $data['enrolmentkey']);
                 if ($DB->record_exists_sql($sql, $params)) {
                     $errors['enrolmentkey'] = get_string('enrolmentkeyalreadyinuse', 'group');
                 }
             }
         }
     } else {
         if (groups_get_group_by_name($COURSE->id, $name)) {
             $errors['name'] = get_string('groupnameexists', 'group', $name);
         } else {
             if (!empty($idnumber) && groups_get_group_by_idnumber($COURSE->id, $idnumber)) {
                 $errors['idnumber'] = get_string('idnumbertaken');
             } else {
                 if ($data['enrolmentkey'] != '') {
                     $errmsg = '';
                     if (!empty($CFG->groupenrolmentkeypolicy) && !check_password_policy($data['enrolmentkey'], $errmsg)) {
                         // Enforce password policy.
                         $errors['enrolmentkey'] = $errmsg;
                     } else {
                         if ($DB->record_exists('groups', array('courseid' => $COURSE->id, 'enrolmentkey' => $data['enrolmentkey']))) {
                             // Prevent the same enrolment key from being used multiple times in course groups.
                             $errors['enrolmentkey'] = get_string('enrolmentkeyalreadyinuse', 'group');
                         }
                     }
                 }
             }
         }
     }
     return $errors;
 }
Exemple #19
0
$course = null;
$group = null;
$groupname = null;
$groupscreated = 0;
$enrolments = 0;
foreach ($syncrows as $sync) {
    if ($courseshortname !== $sync->shortname) {
        $courseshortname = $sync->shortname;
        if (!($course = $DB->get_record('course', array('shortname' => $sync->shortname)))) {
            echo "Error! No existe curso {$sync->shortname} \n";
            continue;
        }
    }
    if ($groupname !== $sync->groupname) {
        $groupname = $sync->groupname;
        if ($groupid = groups_get_group_by_name($course->id, $sync->groupname)) {
            if (!($group = groups_get_group($groupid))) {
                echo "Error! Grupo id {$groupid} no existe!\n";
                continue;
            }
        } else {
            $group = new stdClass();
            $group->courseid = $course->id;
            $group->name = $sync->groupname;
            $group->timecreated = time();
            $group->timemodified = time();
            $group->id = groups_create_group($group);
            if (!$group->id) {
                $group = false;
            } else {
                $groupscreated++;
     echo json_encode($result);
     die;
 }
 switch ($action) {
     case 'delete':
         // Delete Group...
         $groupid = required_param('groupid', PARAM_INT);
         require_capability('mod/grouptool:administrate_groups', $context);
         groups_delete_group($groupid);
         break;
     case 'rename':
         // Rename to...
         $groupid = required_param('groupid', PARAM_INT);
         require_capability('mod/grouptool:administrate_groups', $context);
         $name = required_param('name', PARAM_TEXT);
         $group = groups_get_group_by_name($course->id, $name);
         $group = $DB->get_record('groups', array('id' => $group));
         if (!empty($group) && $group->id != $groupid) {
             $result->error = get_string('groupnameexists', 'group', $name);
         } else {
             $group = new stdClass();
             $group->id = $groupid;
             $group->name = $name;
             $group->courseid = (int) $course->id;
             groups_update_group($group);
             if ($name != $DB->get_field('groups', 'name', array('id' => $groupid))) {
                 // Error happened...
                 $result->error = get_string('couldnt_rename_group', 'grouptool', $name);
             } else {
                 $result->message = get_string('renamed_group', 'grouptool', $name);
             }
 /**
  * Validation for rename form
  * If there are errors return array of errors ("fieldname"=>"error message"),
  * otherwise true if ok.
  *
  * @param array $data array of ("fieldname"=>value) of submitted data
  * @param array $files array of uploaded files "element_name"=>tmp_file_path
  * @return array of "element_name"=>"error_description" if there are errors,
  *               or an empty array if everything is OK.
  */
 public function validation($data, $files)
 {
     global $CFG, $DB;
     $errors = parent::validation($data, $files);
     if (empty($data['name'])) {
         $errors['name'] = get_string('choose_group', 'grouptool');
     } else {
         $group = groups_get_group_by_name($this->course->id, $data['name']);
         $group = $DB->get_record('groups', array('id' => $group));
         if (!empty($group) && $group->id != $data['rename']) {
             $errors['name'] = get_string('groupnameexists', 'group', $data['name']);
         }
     }
     return $errors;
 }
                 // student
             // student
             default:
                 $ok = enrol_student($user->id, $course->id);
                 break;
         }
     }
     if ($ok) {
         // OK
         echo $strindent . get_string('enrolledincourse', '', $addcourse) . '<br />';
     } else {
         notify(get_string('erroronline', 'error', $linenum) . ': ' . get_string('enrolledincoursenot', '', $addcourse));
     }
     // find group to add to
     if ($addgroup = @$user->{'group' . $ncourses}) {
         if ($gid =& groups_get_group_by_name($course->id, $addgroup)) {
             $coursecontext =& get_context_instance(CONTEXT_COURSE, $course->id);
             if (count(get_user_roles($coursecontext, $user->id))) {
                 if (groups_add_member($gid, $user->id)) {
                     echo $strindent . get_string('addedtogroup', '', $addgroup) . '<br />';
                 } else {
                     notify(get_string('erroronline', 'error', $linenum) . ': ' . get_string('addedtogroupnot', '', $addgroup));
                 }
             } else {
                 notify(get_string('erroronline', 'error', $linenum) . ': ' . get_string('addedtogroupnotenrolled', '', $addgroup));
             }
         } else {
             notify(get_string('erroronline', 'error', $linenum) . ': ' . get_string('groupunknown', 'error', $addgroup));
         }
     }
 }
Exemple #23
0
    /**
     * Performs validation of the form information
     *
     * @param array $data
     * @param array $files
     * @return array $errors An array of $errors
     */
    function validation($data, $files) {
        global $CFG, $COURSE;
        $errors = parent::validation($data, $files);

        if ($data['allocateby'] != 'no') {
            $source = array();
            if ($data['cohortid']) {
                $source['cohortid'] = $data['cohortid'];
            }
            if ($data['groupingid']) {
                $source['groupingid'] = $data['groupingid'];
            }
            if ($data['groupid']) {
                $source['groupid'] = $data['groupid'];
            }
            if (!$users = groups_get_potential_members($data['courseid'], $data['roleid'], $source)) {
                $errors['roleid'] = get_string('nousersinrole', 'group');
            }

           /// Check the number entered is sane
            if ($data['groupby'] == 'groups') {
                $usercnt = count($users);

                if ($data['number'] > $usercnt || $data['number'] < 1) {
                    $errors['number'] = get_string('toomanygroups', 'group', $usercnt);
                }
            }
        }

        //try to detect group name duplicates
        $name = groups_parse_name(trim($data['namingscheme']), 0);
        if (groups_get_group_by_name($COURSE->id, $name)) {
            $errors['namingscheme'] = get_string('groupnameexists', 'group', $name);
        }

        // check grouping name duplicates
        if ( isset($data['grouping']) && $data['grouping'] == '-1') {
            $name = trim($data['groupingname']);
            if (empty($name)) {
                $errors['groupingname'] = get_string('required');
            } else if (groups_get_grouping_by_name($COURSE->id, $name)) {
                $errors['groupingname'] = get_string('groupingnameexists', 'group', $name);
            }
        }

       /// Check the naming scheme
        if ($data['groupby'] == 'groups' and $data['number'] == 1) {
            // we can use the name as is because there will be only one group max
        } else {
            $matchcnt = preg_match_all('/[#@]{1,1}/', $data['namingscheme'], $matches);
            if ($matchcnt != 1) {
                $errors['namingscheme'] = get_string('badnamingscheme', 'group');
            }
        }

        return $errors;
    }
 function validation($data, $files)
 {
     global $CFG, $COURSE;
     $errors = parent::validation($data, $files);
     if ($data['allocateby'] != 'no') {
         if (!($users = groups_get_potential_members($data['courseid'], $data['roleid']))) {
             $errors['roleid'] = get_string('nousersinrole', 'group');
         }
         /// Check the number entered is sane
         if ($data['groupby'] == 'groups') {
             $usercnt = count($users);
             if ($data['number'] > $usercnt || $data['number'] < 1) {
                 $errors['number'] = get_string('toomanygroups', 'group', $usercnt);
             }
         }
     }
     //try to detect group name duplicates
     $name = groups_parse_name(stripslashes(trim($data['namingscheme'])), 0);
     if (groups_get_group_by_name($COURSE->id, $name)) {
         $errors['namingscheme'] = get_string('groupnameexists', 'group', $name);
     }
     // check grouping name duplicates
     if (isset($data['grouping']) && $data['grouping'] == '-1') {
         $name = trim(stripslashes($data['groupingname']));
         if (empty($name)) {
             $errors['groupingname'] = get_string('required');
         } else {
             if (groups_get_grouping_by_name($COURSE->id, $name)) {
                 $errors['groupingname'] = get_string('groupingnameexists', 'group', $name);
             }
         }
     }
     /// Check the naming scheme
     $matchcnt = preg_match_all('/[#@]{1,1}/', $data['namingscheme'], $matches);
     if ($matchcnt != 1) {
         $errors['namingscheme'] = get_string('badnamingscheme', 'group');
     }
     return $errors;
 }
 //get all of the students in this class
 $students = $dbc->get_course_users($course_id, $group_id);
 $course = $dbc->get_course_by_id($course_id);
 $groups = groups_get_all_groups($course->id);
 if (!empty($groups)) {
     $groupmode = groups_get_course_groupmode($course);
     // Groups are being used
     $isseparategroups = $course->groupmode == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $context);
 } else {
     $group_id = 0;
 }
 $groupexists = groups_get_group($group_id);
 if (empty($groupexists)) {
     $group_id = 0;
 } else {
     $groupincourse = groups_get_group_by_name($course_id, $groupexists->name);
     if (empty($groupincourse)) {
         $group_id = 0;
     }
 }
 $pagetitle = $course->shortname;
 if (stripos($CFG->release, "2.") !== false) {
     $ucourses = enrol_get_users_courses($USER->id, false, NULL, 'shortname ASC');
 } else {
     $ucourses = $dbc->get_user_courses($USER->id);
 }
 $user_courses = array();
 foreach ($ucourses as $uc) {
     $coursecontext = get_context_instance(CONTEXT_COURSE, $uc->id);
     //if the user has the capability to view the course then add it to the array
     if (has_capability('block/ilp:viewotherilp', $coursecontext, $USER->id, false)) {
Exemple #26
0
 /**
  * Form validation
  *
  * @param array $data
  * @param array $files
  * @return array $errors An array of errors
  */
 function validation($data, $files)
 {
     global $COURSE, $DB, $CFG;
     $errors = parent::validation($data, $files);
     $name = trim($data['name']);
     if (isset($data['idnumber'])) {
         $idnumber = trim($data['idnumber']);
     } else {
         $idnumber = '';
     }
     if ($data['id'] and $group = $DB->get_record('groups', array('id' => $data['id']))) {
         if (textlib::strtolower($group->name) != textlib::strtolower($name)) {
             if (groups_get_group_by_name($COURSE->id, $name)) {
                 $errors['name'] = get_string('groupnameexists', 'group', $name);
             }
         }
         if (!empty($idnumber) && $group->idnumber != $idnumber) {
             if (groups_get_group_by_idnumber($COURSE->id, $idnumber)) {
                 $errors['idnumber'] = get_string('idnumbertaken');
             }
         }
         if (!empty($CFG->groupenrolmentkeypolicy) and $data['enrolmentkey'] != '' and $group->enrolmentkey !== $data['enrolmentkey']) {
             // enforce password policy only if changing password
             $errmsg = '';
             if (!check_password_policy($data['enrolmentkey'], $errmsg)) {
                 $errors['enrolmentkey'] = $errmsg;
             }
         }
     } else {
         if (groups_get_group_by_name($COURSE->id, $name)) {
             $errors['name'] = get_string('groupnameexists', 'group', $name);
         } else {
             if (!empty($idnumber) && groups_get_group_by_idnumber($COURSE->id, $idnumber)) {
                 $errors['idnumber'] = get_string('idnumbertaken');
             }
         }
     }
     return $errors;
 }
Exemple #27
0
 /**
  * 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;
 }