/** * Set up the database for tests * * This function is needed so that daily_log_provider has the before-test set up from setUp() */ public function setUpDB() { global $DB; if ($DB->record_exists('user', array('username' => 'user1'))) { return; } $datagen = self::getDataGenerator(); $user1 = $datagen->create_user(array('username'=>'user1')); $user2 = $datagen->create_user(array('username'=>'user2')); $course1 = $datagen->create_course(array('shortname'=>'course1')); $success = enrol_try_internal_enrol($course1->id, $user1->id, 5); if (! $success) { trigger_error('User enrollment failed', E_USER_ERROR); } $context = context_system::instance(); role_assign(self::STID, $user2->id, $context->id); $this->generate_replacement_list(); }
$ids = explode(',', $course); foreach ($ids as $course) { $courserow = new stdClass(); // find course based upon idnumber if (intval(trim($course)) == $course) { $courserow = $DB->get_record('course', array('id' => intval($course))); } elseif (!$courserow && $DB->record_exists('course', array('shortname' => $course))) { // find course based upon shortname $courserow = $DB->get_record('course', array('shortname' => $course)); } if (empty($courserow)) { continue; } // enrol student to course if (get_config('auth/wp2moodle', 'redirectnoenrol') == 'no') { if (!enrol_try_internal_enrol($courserow->id, $user->id, $studentrow->id)) { continue; } } // if the plugin auto-opens the course, then find the course this group is for and set it as the opener link if (get_config('auth/wp2moodle', 'autoopen') == 'yes') { $SESSION->wantsurl = new moodle_url('/course/view.php', array('id' => $courserow->id)); } } } // all that's left to do is to authenticate this user and set up their active session $authplugin = get_auth_plugin('wp2moodle'); // me! if ($authplugin->user_login($user->username, $user->password)) { $user->loggedin = true; $user->site = $CFG->wwwroot;
/** * Create a new Module on the Moodle installation based * upon the ID of the record in the course request system. * */ function block_cmanager_create_new_course_by_record_id($mid, $sendMail) { global $CFG, $DB; require_once "{$CFG->libdir}/formslib.php"; require_once '../../../course/lib.php'; require_once $CFG->libdir . '/completionlib.php'; //** Create an object to hold our new course information $new_course = new block_cmanager_new_course(); $new_course->format = get_config('moodlecourse', 'format'); //Get the default timestamp for new courses $timestamp_startdate = $DB->get_field('block_cmanager_config', 'value', array('varname' => 'startdate'), IGNORE_MULTIPLE); $new_course->startdate = $timestamp_startdate; $new_course->newsitems = get_config('moodlecourse', 'newsitems'); $new_course->showgrades = get_config('moodlecourse', 'showgrades'); $new_course->showreports = get_config('moodlecourse', 'showreports'); $new_course->maxbytes = get_config('moodlecourse', 'maxbytes'); //Formatting $new_course->numsections = get_config('moodlecourse', 'numsections'); $new_course->hiddensections = get_config('moodlecourse', 'hiddensections'); // Groups $new_course->groupmode = get_config('moodlecourse', 'groupmode'); $new_course->groupmodeforce = get_config('moodlecourse', 'groupmodeforce'); //completion $new_course->enablecompletion = get_config('moodlecourse', 'enablecompletion'); // Visible $new_course->visible = get_config('moodlecourse', 'visible'); $new_course->lang = get_config('moodlecourse', 'lang'); //is course mode enabled (page 1 optional dropdown) $mode = $DB->get_field('block_cmanager_config', 'value', array('varname' => 'page1_field3status')); // what naming mode is operating $naming = $DB->get_field('block_cmanager_config', 'value', array('varname' => 'naming'), IGNORE_MULTIPLE); //what short naming format is operating $snaming = $DB->get_field('block_cmanager_config', 'value', array('varname' => 'snaming'), IGNORE_MULTIPLE); //get the record for the request $rec = $DB->get_record('block_cmanager_records', array('id' => $mid)); // Build up a course record based on the request. if (empty($rec->cate)) { $new_course->category = $CFG->defaultrequestcategory; } else { $new_course->category = $rec->cate; } // Fields we are carrying across if ($mode == "enabled" && $snaming == 2) { $newShortName = $rec->modcode . ' - ' . $rec->modmode; } else { $newShortName = $rec->modcode; } $new_course->shortname = $newShortName; $p_key = $rec->modkey; //course naming if ($naming == 1) { $new_course->fullname = $rec->modname; } else { if ($naming == 2) { $new_course->fullname = $rec->modcode . ' - ' . $rec->modname; } else { if ($naming == 3) { $new_course->fullname = $rec->modname . ' (' . $rec->modcode . ')'; // Fullname, shortname } else { if ($naming == 4) { $new_course->fullname = $rec->modcode . ' - ' . $rec->modname . ' (' . date("Y") . ')'; // Shortname, fullname (year) } else { if ($naming == 5) { $new_course->fullname = $rec->modname . ' (' . date("Y") . ')'; } } } } } // Enrollment key // if the key thats been set, otherwise auto gen a key if (isset($rec->modkey)) { $modkey = $rec->modkey; } else { $modkey = rand(999, 5000); } $categoryid = $new_course->category; $category = $DB->get_record('course_categories', array('id' => $categoryid)); $catcontext = context_coursecat::instance($category->id); $contextobject = $catcontext; $editoroptions = array('maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $CFG->maxbytes, 'trusttext' => false, 'noclean' => true, 'content' => $contextobject); // Create the course $course = create_course($new_course, $editoroptions); // Forward to the course editing page to allow the admin to make // any changes to the course $nid = $course->id; if ($nid == null) { return $nid; } // Update the record to say that it is now complete $updatedRecord = new stdClass(); $updatedRecord->id = $rec->id; $updatedRecord->status = 'COMPLETE'; $DB->update_record('block_cmanager_records', $updatedRecord); // Try enroll the creator if (!empty($CFG->creatornewroleid)) { // deal with course creators - enrol them internally with default role enrol_try_internal_enrol($nid, $rec->createdbyid, $CFG->creatornewroleid); } // Check to see if auto create enrollment keys // is enabled. If this option is set, add an // enrollment key. $autoKey = $DB->get_field_select('block_cmanager_config', 'value', "varname = 'autoKey'"); if ($autoKey == 0 || $autoKey == 1) { // Add enrollnent key $enrollmentRecord = new stdClass(); $enrollmentRecord->enrol = 'self'; $enrollmentRecord->status = 0; $enrollmentRecord->courseid = $nid; $enrollmentRecord->sortorder = 3; $enrollmentRecord->name = ''; $enrollmentRecord->enrolperiod = 0; $enrollmentRecord->enrolenddate = 0; $enrollmentRecord->expirynotify = 0; $enrollmentRecord->expirythreshold = 0; $enrollmentRecord->notifyall = 0; $enrollmentRecord->password = $modkey; $enrollmentRecord->cost = NULL; $enrollmentRecord->currency = NULL; $enrollmentRecord->roleid = 5; $enrollmentRecord->customint1 = 0; $enrollmentRecord->customint2 = 0; $enrollmentRecord->customint3 = 0; $enrollmentRecord->customint4 = 1; if ($CFG->version >= 2013051400) { $enrollmentRecord->customint5 = NULL; $enrollmentRecord->customint6 = 1; } $enrollmentRecord->customchar1 = NULL; $enrollmentRecord->customchar2 = NULL; $enrollmentRecord->customdec1 = NULL; $enrollmentRecord->customdec2 = NULL; $enrollmentRecord->customtext1 = ''; $enrollmentRecord->customtext2 = NULL; $enrollmentRecord->timecreated = time(); $enrollmentRecord->timemodified = time(); $DB->insert_record('enrol', $enrollmentRecord); } if ($sendMail == true) { block_cmanager_send_emails($nid, $new_course->shortname, $new_course->fullname, $modkey, $mid); } return $nid; }
} redirect($url); } else if ($data = $editform->get_data()) { // process data if submitted if (empty($course->id)) { // In creating the course $course = create_course($data, $editoroptions); // Get the context of the newly created course $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); if (!empty($CFG->creatornewroleid) and !is_viewing($context, NULL, 'moodle/role:assign') and !is_enrolled($context, NULL, 'moodle/role:assign')) { // deal with course creators - enrol them internally with default role enrol_try_internal_enrol($course->id, $USER->id, $CFG->creatornewroleid); } if (!is_enrolled($context)) { // Redirect to manual enrolment page if possible $instances = enrol_get_instances($course->id, true); foreach($instances as $instance) { if ($plugin = enrol_get_plugin($instance->enrol)) { if ($plugin->get_manual_enrol_link($instance)) { // we know that the ajax enrol UI will have an option to enrol redirect(new moodle_url('/enrol/users.php', array('id'=>$course->id))); } } } } } else {
if (count($users) > 0 and $form = data_submitted() and confirm_sesskey()) { if (count($users) > 0) { $assignableroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, $courseid)); if (array_key_exists($role->id, $assignableroles)) { // For each "userd" in the form... foreach ($form->userid as $userid => $value) { $user_has_role = $DB->record_exists('role_assignments', array('userid' => $userid, 'contextid' => $context->id, 'roleid' => $roleid)); // Assign or Unassign role /*if ( $assign_unassign == 1 && $user_has_role ) { role_unassign( $role->id, $userid, $context->id ); } else*/ if (!$user_has_role) { role_assign($role->id, $userid, $context->id); } if (!is_enrolled($context, $userid)) { enrol_try_internal_enrol($courseid, $userid); } } } } global $SESSION; $SESSION->user_filtering = array(); // Redirect to calling page redirect('pick.php?courseid=' . $courseid, get_string('changessaved')); } $PAGE->set_url('/blocks/pick_students/assign.php'); $PAGE->set_pagelayout('base'); $title = print_context_name($context) . ' - '; $strtitle = get_string('enrolledusers', 'enrol'); $PAGE->set_title($strtitle); $PAGE->set_heading($title . $strtitle);
/** * Validate that LO grades are locked when they are updated and grade * is sufficient when run for a specific user */ public function test_methodlockslearningobjectivegradesduringupdateforspecificuserid() { global $DB; $this->load_csv_data(); // Create enrolment. $this->make_course_enrollable(); enrol_try_internal_enrol(2, 100, 1); enrol_try_internal_enrol(2, 101, 1); // Create LO and Moodle grade. $itemid = $this->create_grade_item(); $this->create_grade_grade($itemid, 100, 75, 100, 1); $this->create_grade_grade($itemid, 101, 75, 100, 1); $this->create_course_completion('manualitem', 50); // Enrol in PM class. $studentgrade = new \student_grade(array('userid' => 103, 'classid' => 100, 'completionid' => 1, 'grade' => 75, 'locked' => 0, 'timegraded' => 1)); $studentgrade->save(); $studentgrade = new \student_grade(array('userid' => 104, 'classid' => 100, 'completionid' => 1, 'grade' => 75, 'locked' => 0, 'timegraded' => 1)); $studentgrade->save(); // Validate setup. $this->assert_num_student_grades(2); $count = $DB->count_records(\student_grade::TABLE, array('locked' => 1)); $this->assertEquals(0, $count); $this->assert_student_grade_exists(100, 103, 1, null, 0); // Update Moodle info. $DB->execute("UPDATE {grade_grades} SET finalgrade = 80, timemodified = 2"); // Run and validate. $sync = new \local_elisprogram\moodle\synchronize(); $sync->synchronize_moodle_class_grades(100); $this->assert_num_student_grades(2); $count = $DB->count_records(\student_grade::TABLE, array('locked' => 1)); $this->assertEquals(1, $count); $this->assert_student_grade_exists(100, 103, 1, null, 1); }
/** * 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; }
/** * Import user and signup to session * * @access public * @param object $course Record from the course table * @param object $facetoface Record from the facetoface table * @param object $session Session to signup user to * @param mixed $userid User to signup (normally int) * @param array $params Optional suppressemail, ignoreconflicts, bulkaddsource, discountcode, notificationtype * boolean $suppressemail Suppress notifications flag * boolean $ignoreconflicts Ignore booking conflicts flag * string $bulkaddsource Flag to indicate if $userid is actually another field * string $discountcode Optional A user may specify a discount code * integer $notificationtype Optional A user may choose the type of notifications they will receive * @return array */ function facetoface_user_import($course, $facetoface, $session, $userid, $params = array()) { global $DB, $CFG, $USER; $result = array(); $result['id'] = $userid; $suppressemail = (isset($params['suppressemail']) ? $params['suppressemail'] : false); $ignoreconflicts = (isset($params['ignoreconflicts']) ? $params['ignoreconflicts'] : false); $bulkaddsource = (isset($params['bulkaddsource']) ? $params['bulkaddsource'] : 'bulkaddsourceuserid'); $discountcode = (isset($params['discountcode']) ? $params['discountcode'] : ''); $notificationtype = (isset($params['notificationtype']) ? $params['notificationtype'] : MDL_F2F_BOTH); if (isset($params['approvalreqd'])) { // Overwrite default behaviour as bulkadd_* is requested $facetoface->approvalreqd = $params['approvalreqd']; $facetoface->ccmanager = (isset($params['ccmanager']) ? $params['ccmanager'] : 0); } // Check parameters. if ($bulkaddsource == 'bulkaddsourceuserid') { if (!is_int($userid) && !ctype_digit($userid)) { $result['name'] = ''; $result['result'] = get_string('error:userimportuseridnotanint', 'facetoface', $userid); return $result; } } // Get user. switch ($bulkaddsource) { case 'bulkaddsourceuserid': $user = $DB->get_record('user', array('id' => $userid)); break; case 'bulkaddsourceidnumber': $user = $DB->get_record('user', array('idnumber' => $userid)); break; case 'bulkaddsourceusername': $user = $DB->get_record('user', array('username' => $userid)); break; } if (!$user) { $result['name'] = ''; $a = array('fieldname' => get_string($bulkaddsource, 'facetoface'), 'value' => $userid); $result['result'] = get_string('userdoesnotexist', 'facetoface', $a); return $result; } $result['name'] = fullname($user); if (isguestuser($user)) { $a = array('fieldname' => get_string($bulkaddsource, 'facetoface'), 'value' => $userid); $result['result'] = get_string('cannotsignupguest', 'facetoface', $a); return $result; } // Make sure that the user is enroled in the course $context = context_course::instance($course->id); if (!is_enrolled($context, $user)) { $defaultlearnerrole = $DB->get_record('role', array('id' => $CFG->learnerroleid)); if (!enrol_try_internal_enrol($course->id, $user->id, $defaultlearnerrole->id, time())) { $result['result'] = get_string('error:enrolmentfailed', 'facetoface', fullname($user)); return $result; } } // Check if they are already signed up $minimumstatus = ($session->datetimeknown) ? MDL_F2F_STATUS_BOOKED : MDL_F2F_STATUS_REQUESTED; // If multiple sessions are allowed then just check against this session // Otherwise check against all sessions $multisessionid = ($facetoface->multiplesessions ? $session->id : null); if (facetoface_get_user_submissions($facetoface->id, $user->id, $minimumstatus, MDL_F2F_STATUS_FULLY_ATTENDED, $multisessionid)) { if ($user->id == $USER->id) { $result['result'] = get_string('error:addalreadysignedupattendeeaddself', 'facetoface'); } else { $result['result'] = get_string('error:addalreadysignedupattendee', 'facetoface'); } return $result; } if (!facetoface_session_has_capacity($session, $context)) { if ($session->allowoverbook) { $status = MDL_F2F_STATUS_WAITLISTED; } else { $result['result'] = get_string('full', 'facetoface'); return $result; } } // Check if we are waitlisting or booking if ($session->datetimeknown) { if (!isset($status)) { $status = MDL_F2F_STATUS_BOOKED; } // Check if there are any date conflicts if (!$ignoreconflicts) { $dates = facetoface_get_session_dates($session->id); if ($availability = facetoface_get_sessions_within($dates, $user->id)) { $result['result'] = facetoface_get_session_involvement($user, $availability); $result['conflict'] = true; return $result; } } } else { $status = MDL_F2F_STATUS_WAITLISTED; } // Finally attempt to enrol if (!facetoface_user_signup( $session, $facetoface, $course, $discountcode, $notificationtype, $status, $user->id, !$suppressemail)) { $result['result'] = get_string('error:addattendee', 'facetoface', fullname($user)); return $result; } $result['result'] = true; return $result; }
/** * Test the group event handlers */ public function test_group_event_handlers() { global $DB,$CFG; $this->resetAfterTest(); $this->setAdminUser(); // Setup course, user and groups $course = $this->getDataGenerator()->create_course(); $user1 = $this->getDataGenerator()->create_user(); $studentrole = $DB->get_record('role', array('shortname'=>'student')); $this->assertNotEmpty($studentrole); $this->assertTrue(enrol_try_internal_enrol($course->id, $user1->id, $studentrole->id)); $group1 = $this->getDataGenerator()->create_group(array('courseid'=>$course->id)); $group2 = $this->getDataGenerator()->create_group(array('courseid'=>$course->id)); $this->assertTrue(groups_add_member($group1, $user1)); $this->assertTrue(groups_add_member($group2, $user1)); $uniqueid = 0; $quiz_generator = $this->getDataGenerator()->get_plugin_generator('mod_quiz'); $quiz = $quiz_generator->create_instance(array('course'=>$course->id, 'timeclose'=>1200, 'timelimit'=>0)); // add a group1 override $DB->insert_record('quiz_overrides', array('quiz'=>$quiz->id, 'groupid'=>$group1->id, 'timeclose'=>1300, 'timelimit'=>null)); // add an attempt $attemptid = $DB->insert_record('quiz_attempts', array('quiz'=>$quiz->id, 'userid'=>$user1->id, 'state'=>'inprogress', 'timestart'=>100, 'timecheckstate'=>0, 'layout'=>'', 'uniqueid'=>$uniqueid++)); // update timecheckstate quiz_update_open_attempts(array('quizid'=>$quiz->id)); $this->assertEquals(1300, $DB->get_field('quiz_attempts', 'timecheckstate', array('id'=>$attemptid))); // remove from group $this->assertTrue(groups_remove_member($group1, $user1)); $this->assertEquals(1200, $DB->get_field('quiz_attempts', 'timecheckstate', array('id'=>$attemptid))); // add back to group $this->assertTrue(groups_add_member($group1, $user1)); $this->assertEquals(1300, $DB->get_field('quiz_attempts', 'timecheckstate', array('id'=>$attemptid))); // delete group groups_delete_group($group1); $this->assertEquals(1200, $DB->get_field('quiz_attempts', 'timecheckstate', array('id'=>$attemptid))); $this->assertEquals(0, $DB->count_records('quiz_overrides', array('quiz'=>$quiz->id))); // add a group2 override $DB->insert_record('quiz_overrides', array('quiz'=>$quiz->id, 'groupid'=>$group2->id, 'timeclose'=>1400, 'timelimit'=>null)); quiz_update_open_attempts(array('quizid'=>$quiz->id)); $this->assertEquals(1400, $DB->get_field('quiz_attempts', 'timecheckstate', array('id'=>$attemptid))); // delete user1 from all groups groups_delete_group_members($course->id, $user1->id); $this->assertEquals(1200, $DB->get_field('quiz_attempts', 'timecheckstate', array('id'=>$attemptid))); // add back to group2 $this->assertTrue(groups_add_member($group2, $user1)); $this->assertEquals(1400, $DB->get_field('quiz_attempts', 'timecheckstate', array('id'=>$attemptid))); // delete everyone from all groups groups_delete_group_members($course->id); $this->assertEquals(1200, $DB->get_field('quiz_attempts', 'timecheckstate', array('id'=>$attemptid))); }
/** * Validates that, for deletion of a course role that is not assigned, an error is logged * instead of deleting the user's enrolment if they have some other role assignment on * the coruse */ public function test_version1importlogsdeletionofenrolmentwhenrolesassignmentsexist() { global $CFG, $DB; require_once $CFG->dirroot . '/lib/enrollib.php'; // Set up dependencies. $userid = $this->create_test_user(); $unassignedroleid = $this->create_test_role('unassigned', 'unassigned', 'unassigned'); $assignedroleid = $this->create_test_role('assigned', 'assigned', 'assigned'); $courseid = $this->create_test_course(); set_config('siteguest', ''); $enrol = new stdClass(); $enrol->enrol = 'manual'; $enrol->courseid = $courseid; $enrol->status = ENROL_INSTANCE_ENABLED; $DB->insert_record('enrol', $enrol); // Set up a role assignment and an enrolment. enrol_try_internal_enrol($courseid, $userid, $assignedroleid); // Data. $data = array('action' => 'delete', 'username' => 'rlipusername', 'context' => 'course', 'instance' => 'rlipshortname', 'role' => 'unassigned'); $message = "[enrolment.csv line 2] User with username \"rlipusername\" could not be unassigned role with shortname"; $message .= " \"unassigned\" on course \"rlipshortname\". User with username \"rlipusername\" could not be unenrolled"; $message .= " from course with shortname \"rlipshortname\". User with username \"rlipusername\" is not assigned role"; $message .= " with shortname \"unassigned\" on course \"rlipshortname\". User with username \"rlipusername\" requires"; $message .= " their enrolment to be maintained because they have another role assignment in this course.\n"; $this->assert_data_produces_error($data, $message, 'enrolment'); }
/** * Validate that the import prevents assigning a user to the same group * twice */ public function test_version1importpreventsduplicateusergroupassignments() { global $CFG, $DB; require_once $CFG->dirroot . '/group/lib.php'; // Enrol the user in the course. enrol_try_internal_enrol(self::$courseid, self::$userid, self::$courseroleid, 0); // Set up the "pre-existing" group. $groupid = $this->create_test_group(self::$courseid); // Add the user to the group. groups_add_member($groupid, self::$userid); // Validate setup. $this->assertEquals($DB->count_records('groups_members'), 1); // Run the import. $data = $this->get_core_enrolment_data(); $data['group'] = 'rlipgroup'; $this->run_core_enrolment_import($data, false); // Compare data. $this->assertEquals($DB->count_records('groups_members'), 1); }
/** * Validate that the version 1 plugin deletes appropriate associations when * deleting a user */ public function test_version1importdeleteuserdeletesassociations() { global $CFG, $DB; set_config('siteadmins', 0); // New config settings needed for course format refactoring in 2.4. set_config('numsections', 15, 'moodlecourse'); set_config('hiddensections', 0, 'moodlecourse'); set_config('coursedisplay', 1, 'moodlecourse'); require_once $CFG->dirroot . '/cohort/lib.php'; require_once $CFG->dirroot . '/course/lib.php'; require_once $CFG->dirroot . '/group/lib.php'; require_once $CFG->dirroot . '/lib/enrollib.php'; require_once $CFG->dirroot . '/lib/gradelib.php'; // Create our test user, and determine their userid. $this->run_core_user_import(array()); $userid = (int) $DB->get_field('user', 'id', array('username' => 'rlipusername', 'mnethostid' => $CFG->mnet_localhost_id)); // Create cohort. $cohort = new stdClass(); $cohort->name = 'testcohort'; $cohort->contextid = context_system::instance()->id; $cohortid = cohort_add_cohort($cohort); // Add the user to the cohort. cohort_add_member($cohortid, $userid); // Create a course category - there is no API for doing this. $category = new stdClass(); $category->name = 'testcategory'; $category->id = $DB->insert_record('course_categories', $category); // Create a course. set_config('defaultenrol', 1, 'enrol_manual'); set_config('status', ENROL_INSTANCE_ENABLED, 'enrol_manual'); $course = new stdClass(); $course->category = $category->id; $course->fullname = 'testfullname'; $course = create_course($course); // Create a grade. $gradeitem = new grade_item(array('courseid' => $course->id, 'itemtype' => 'manual', 'itemname' => 'testitem'), false); $gradeitem->insert(); $gradegrade = new grade_grade(array('itemid' => $gradeitem->id, 'userid' => $userid), false); $gradegrade->insert(); // Send the user an unprocessed message. set_config('noemailever', true); // Set up a user tag. tag_set('user', $userid, array('testtag')); // Create a new course-level role. $roleid = create_role('testrole', 'testrole', 'testrole'); set_role_contextlevels($roleid, array(CONTEXT_COURSE)); // Enrol the user in the course with the new role. enrol_try_internal_enrol($course->id, $userid, $roleid); // Create a group. $group = new stdClass(); $group->name = 'testgroup'; $group->courseid = $course->id; $groupid = groups_create_group($group); // Add the user to the group. groups_add_member($groupid, $userid); set_user_preference('testname', 'testvalue', $userid); // Create profile field data - don't both with the API here because it's a bit unwieldy. $userinfodata = new stdClass(); $userinfodata->fieldid = 1; $userinfodata->data = 'bogus'; $userinfodata->userid = $userid; $DB->insert_record('user_info_data', $userinfodata); // There is no easily accessible API for doing this. $lastaccess = new stdClass(); $lastaccess->userid = $userid; $lastaccess->courseid = $course->id; $DB->insert_record('user_lastaccess', $lastaccess); $data = array('action' => 'delete', 'username' => 'rlipusername'); $this->run_core_user_import($data, false); // Assert data condition after delete. $this->assertEquals($DB->count_records('message_read', array('useridto' => $userid)), 0); $this->assertEquals($DB->count_records('grade_grades'), 0); $this->assertEquals($DB->count_records('tag_instance'), 0); $this->assertEquals($DB->count_records('cohort_members'), 0); $this->assertEquals($DB->count_records('user_enrolments'), 0); $this->assertEquals($DB->count_records('role_assignments'), 0); $this->assertEquals($DB->count_records('groups_members'), 0); $this->assertEquals($DB->count_records('user_preferences'), 0); $this->assertEquals($DB->count_records('user_info_data'), 0); $this->assertEquals($DB->count_records('user_lastaccess'), 0); }
if (!$demostudentuser) { // Test this by setting $demostudentuser to false. print get_string('errorfailedtocreateuser', 'block_demostudent', $demostudentusername); print get_string('returntocourse', 'block_demostudent', $url); exit; } } // Else DemoStudent user already exists for this instructor. $demostudentid = $demostudentuser->id; // Enrol DemoStudent in this course (as a demostudent). $demostudentroleid = get_roleid_by_roleshortname('demostudent'); if (!$demostudentroleid) { print get_string('warningmissingrole', 'block_demostudent'); } if (!is_enrolled($coursecontext, $demostudentuser)) { if (!enrol_try_internal_enrol($courseid, $demostudentid, $demostudentroleid)) { // Enrolment failed. Haven't seen this happen yet. trigger_error('DemoStudent user enrolment failed!<br>Parameters:<br>' . '<br> url=' . var_export($url, true) . '<br> viewrole=' . var_export($viewrole, true) . '<br> courseid=' . var_export($courseid, true) . '<br>Globals:' . '<br> userid=' . var_export($userid, true) . '<br> username='******'<br>Locals:' . '<br> demostudentid=' . var_export($demostudentid, true) . '<br> demostudentroleid=' . var_export($demostudentroleid, true) . '<br> coursecontext=' . var_export($coursecontext, true) . '<br> demostudentuser='******'s possible that the function failed, but that the user is nevertheless enrolled. // If the user is not enrolled, a later check will take care of things. } } // Aditionally, if we are switching from 'instructor' view (i.e., not in 'firstuse' mode), switch user. if ($viewrole == 'instructor') { if (is_siteadmin($demostudentid)) { // This should never happen. Haven't seen it happen yet. print_error('nologinas'); } if (!is_enrolled($coursecontext, $demostudentid)) { // This should never happen. Haven't seen it happen yet. print_error('usernotincourse');
/** * 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); }
$potentialuserselector = new facetoface_candidate_selector('addselect', array('sessionid' => $session->id)); $existinguserselector = new facetoface_existing_selector('removeselect', array('sessionid' => $session->id)); // Process incoming user assignments. if (optional_param('add', false, PARAM_BOOL) && confirm_sesskey()) { require_capability('mod/facetoface:addattendees', $context); $userstoassign = $potentialuserselector->get_selected_users(); if (!empty($userstoassign)) { foreach ($userstoassign as $adduser) { if (!($adduser = clean_param($adduser->id, PARAM_INT))) { continue; // Invalid userid. } // Make sure that the user is enroled in the course. if (!has_capability('moodle/course:view', $context, $adduser)) { $user = $DB->get_record('user', array('id' => $adduser)); if (!enrol_try_internal_enrol($course->id, $user->id, 5)) { $errors[] = get_string('error:enrolmentfailed', 'facetoface', fullname($user)); $errors[] = get_string('error:addattendee', 'facetoface', fullname($user)); continue; // Don't sign the user up. } } $usernamefields = get_all_user_name_fields(true); if (facetoface_get_user_submissions($facetoface->id, $adduser)) { $erruser = $DB->get_record('user', array('id' => $adduser), "id, {$usernamefields}"); $errors[] = get_string('error:addalreadysignedupattendee', 'facetoface', fullname($erruser)); } else { if (!facetoface_session_has_capacity($session, $context)) { $errors[] = get_string('full', 'facetoface'); break; // No point in trying to add other people.
if (!($group = $DB->get_record("groups", array("name" => $v[1], "courseid" => $id)))) { $newgroupdata = new stdClass(); $newgroupdata->name = $v[1]; $newgroupdata->courseid = $id; $newgroupdata->description = ''; $gid = groups_create_group($newgroupdata); if ($gid) { $group = $DB->get_record("groups", array("id" => $gid)); } $report['groupcreated'][$gid] = array($newgroupdata->name); } if (!$user) { $report['studentnotfound'][] = array($v[0], $group->name); } if ($user && $group) { enrol_try_internal_enrol($id, $user->id, 5, time()); groups_add_member($group->id, $user->id); $report['studentregistered'][] = array($user->username, $user->lastname, $user->firstname, $user->email, $group->name); } } } ///Excel report $course = $DB->get_record("course", array("id" => $id)); $name = "GroupReg_" . $course->shortname . "_" . date(get_string('timeformat', 'block_groupreg'), time()); if (!($data = $DB->get_record_sql("SELECT itemid FROM {files} WHERE component='block_groupreg' AND filearea='excel' AND contextid=? ORDER BY itemid DESC LIMIT 1", array($context->id)))) { $itemid = 1; } else { $itemid = $data->itemid + 1; } $fs = get_file_storage(); $fileinfo = array('contextid' => $context->id, 'component' => 'block_groupreg', 'filearea' => 'excel', 'itemid' => $itemid, 'filepath' => '/', 'filename' => $name . '.json');
/** * This function approves the request turning it into a course * * This function converts the course request into a course, at the same time * transferring any files used in the summary to the new course and then removing * the course request and the files associated with it. * * @return int The id of the course that was created from this request */ public function approve() { global $CFG, $DB, $USER; $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted' => 0), '*', MUST_EXIST); $category = get_course_category($CFG->defaultrequestcategory); $courseconfig = get_config('moodlecourse'); // Transfer appropriate settings $data = clone $this->properties; unset($data->id); unset($data->reason); unset($data->requester); // Set category $data->category = $category->id; $data->sortorder = $category->sortorder; // place as the first in category // Set misc settings $data->requested = 1; // Apply course default settings $data->format = $courseconfig->format; $data->numsections = $courseconfig->numsections; $data->hiddensections = $courseconfig->hiddensections; $data->newsitems = $courseconfig->newsitems; $data->showgrades = $courseconfig->showgrades; $data->showreports = $courseconfig->showreports; $data->maxbytes = $courseconfig->maxbytes; $data->groupmode = $courseconfig->groupmode; $data->groupmodeforce = $courseconfig->groupmodeforce; $data->visible = $courseconfig->visible; $data->visibleold = $data->visible; $data->lang = $courseconfig->lang; $course = create_course($data); $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); // add enrol instances if (!$DB->record_exists('enrol', array('courseid' => $course->id, 'enrol' => 'manual'))) { if ($manual = enrol_get_plugin('manual')) { $manual->add_default_instance($course); } } // enrol the requester as teacher if necessary if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) { enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid); } $this->delete(); $a = new stdClass(); $a->name = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))); $a->url = $CFG->wwwroot . '/course/view.php?id=' . $course->id; $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a)); return $course->id; }
/** * Claim a coupon * * @param string $code coupon submission code */ function claim_coupon_confirm($code) { global $CFG, $DB, $USER; // Because we're outside course context we've got to include groups library manually. require_once $CFG->dirroot . '/group/lib.php'; require_once $CFG->dirroot . '/cohort/lib.php'; $role = $DB->get_record('role', array('shortname' => 'student')); $coupon = $DB->get_record('block_coupon', array('submission_code' => $code)); $couponcourses = $DB->get_records('block_coupon_courses', array('couponid' => $coupon->id)); // We'll handle coupon_cohorts. if (empty($couponcourses)) { $couponcohorts = $DB->get_records('block_coupon_cohorts', array('couponid' => $coupon->id)); if (count($couponcohorts) == 0) { throw new exception('error:missing_cohort'); } // Add user to cohort. foreach ($couponcohorts as $couponcohort) { if (!$DB->get_record('cohort', array('id' => $couponcohort->cohortid))) { throw new exception('error:missing_cohort'); } cohort_add_member($couponcohort->cohortid, $USER->id); } // Now execute the cohort sync. $result = self::enrol_cohort_sync(); // If result = 0 it went ok. (lol!). if ($result === 1) { throw new exception('error:cohort_sync'); } else { if ($result === 2) { throw new exception('error:plugin_disabled'); } } // Otherwise we'll handle based on courses. } else { // Set enrolment period. $endenrolment = 0; if (!is_null($coupon->enrolperiod) && $coupon->enrolperiod > 0) { $endenrolment = strtotime("+ {$coupon->enrolperiod} days"); } foreach ($couponcourses as $couponcourse) { // Make sure we only enrol if its not enrolled yet. $context = \context_course::instance($couponcourse->courseid); if (is_null($context) || $context === false) { throw new exception('error:course-not-found'); } if (is_enrolled($context, $USER->id)) { continue; } // Now we can enrol. if (!enrol_try_internal_enrol($couponcourse->courseid, $USER->id, $role->id, time(), $endenrolment)) { throw new exception('error:unable_to_enrol'); } // Mark the context for cache refresh. $context->mark_dirty(); remove_temp_course_roles($context); } // And add user to groups. $coupongroups = $DB->get_records('block_coupon_groups', array('couponid' => $coupon->id)); if (!empty($coupongroups)) { foreach ($coupongroups as $coupongroup) { // Check if the group exists. if (!$DB->get_record('groups', array('id' => $coupongroup->groupid))) { throw new exception('error:missing_group'); } // Add user if its not a member yet. if (!groups_is_member($coupongroup->groupid, $USER->id)) { groups_add_member($coupongroup->groupid, $USER->id); } } } } // And finally update the coupon record. $coupon->userid = $USER->id; $coupon->timemodified = time(); $DB->update_record('block_coupon', $coupon); // Trigger event. $event = \block_coupon\event\coupon_used::create(array('objectid' => $coupon->id, 'relateduserid' => $USER->id, 'context' => \context_user::instance($USER->id))); $event->add_record_snapshot('block_coupon', $coupon); $event->trigger(); //return (empty($coupon->redirect_url)) ? $CFG->wwwroot . "/my" : $coupon->redirect_url; }
protected function define_execution() { global $CFG, $DB; if (!($userid = $this->task->get_userid())) { return; } if (empty($CFG->restorernewroleid)) { // Bad luck, no fallback role for restorers specified return; } $courseid = $this->get_courseid(); $context = context_course::instance($courseid); if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { // Current user may access the course (admin, category manager or restored teacher enrolment usually) return; } // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled role_assign($CFG->restorernewroleid, $userid, $context); if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { // Extra role is enough, yay! return; } // The last chance is to create manual enrol if it does not exist and and try to enrol the current user, // hopefully admin selected suitable $CFG->restorernewroleid ... if (!enrol_is_enabled('manual')) { return; } if (!($enrol = enrol_get_plugin('manual'))) { return; } if (!$DB->record_exists('enrol', array('enrol' => 'manual', 'courseid' => $courseid))) { $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); $fields = array('status' => ENROL_INSTANCE_ENABLED, 'enrolperiod' => $enrol->get_config('enrolperiod', 0), 'roleid' => $enrol->get_config('roleid', 0)); $enrol->add_instance($course, $fields); } enrol_try_internal_enrol($courseid, $userid); }
/** * Set up data that is needed for testing */ private function set_up_required_data($assignusertouserset = true, $assigncoursetoclass = true, $assigntracktoclass = true, $initclusterprofile = false, $initusersetfielddata = true) { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once $CFG->dirroot . '/course/lib.php'; require_once $CFG->dirroot . '/lib/enrollib.php'; require_once elis::lib('data/customfield.class.php'); require_once elispm::file('accesslib.php'); require_once elispm::lib('data/classmoodlecourse.class.php'); require_once elispm::lib('data/clusterassignment.class.php'); require_once elispm::lib('data/clustertrack.class.php'); require_once elispm::lib('data/course.class.php'); require_once elispm::lib('data/curriculum.class.php'); require_once elispm::lib('data/pmclass.class.php'); require_once elispm::lib('data/track.class.php'); require_once elispm::lib('data/user.class.php'); require_once elispm::lib('data/userset.class.php'); require_once elispm::lib('data/usertrack.class.php'); $fieldcategoryid = $DB->get_field(field_category::TABLE, 'id', array('name' => 'Associated Group')); $this->assertNotEquals(false, $fieldcategoryid); $fieldcategory = new field_category($fieldcategoryid); $fieldcategory->load(); // Set up the test user. $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA')); $user->save(); // Set up the test course description and class instance. $course = new course(array('name' => 'testcoursename', 'idnumber' => 'testcourseidnumber', 'syllabus' => '')); $course->save(); $pmclass = new pmclass(array('courseid' => $course->id, 'idnumber' => 'testclassidnumber')); $pmclass->save(); $category = new stdClass(); $category->name = 'testcategoryname'; $category->id = $DB->insert_record('course_categories', $category); // Set up the test Moodle course. set_config('enrol_plugins_enabled', 'manual'); set_config('defaultenrol', 1, 'enrol_manual'); set_config('status', ENROL_INSTANCE_ENABLED, 'enrol_manual'); $course = new stdClass(); $course->category = $category->id; $course->shortname = 'testcourseshortname'; $course->fullname = 'testcoursefullname'; $course = create_course($course); if ($assigncoursetoclass) { // Assign the Moodle course to a class instance. $classmoodlecourse = new classmoodlecourse(array('classid' => $pmclass->id, 'moodlecourseid' => $course->id)); $classmoodlecourse->save(); } // Set up the test program and track. $curriculum = new curriculum(array('idnumber' => 'testcurriculumidnumber')); $curriculum->save(); $track = new track(array('curid' => $curriculum->id, 'idnumber' => 'testtrackidnumber')); $track->save(); if ($assigntracktoclass) { // Assign the test track to the test class instance. $trackassignment = new trackassignment(array('trackid' => $track->id, 'classid' => $pmclass->id, 'autoenrol' => 1)); $trackassignment->save(); } // Set up the test userset. $userset = new userset(); $usersetdata = array('name' => 'testusersetname'); if ($initusersetfielddata) { $usersetdata['field_userset_group'] = 1; $usersetdata['field_userset_groupings'] = 1; } $userset->set_from_data((object) $usersetdata); $userset->save(); // Assign the test user to the test track. $usertrack = new usertrack(array('userid' => $user->id, 'trackid' => $track->id)); $usertrack->save(); $clustertrack = new clustertrack(array('clusterid' => $userset->id, 'trackid' => $track->id)); $clustertrack->save(); if ($assignusertouserset) { // Assign the test user to the test userset. $clusterassignment = new clusterassignment(array('userid' => $user->id, 'clusterid' => $userset->id, 'plugin' => 'manual')); $clusterassignment->save(); } if ($initclusterprofile) { // Set up a file we can use to auto-associate users to a userset. $field = new field(array('categoryid' => $fieldcategory->id, 'shortname' => 'autoassociate', 'name' => 'autoassociate', 'datatype' => 'bool')); $field->save(); // Ensure manual field owner exists for syncing. field_owner::ensure_field_owner_exists($field, 'manual'); $ownerid = $DB->get_field(field_owner::TABLE, 'id', array('fieldid' => $field->id, 'plugin' => 'manual')); $owner = new field_owner($ownerid); $owner->param_control = 'checkbox'; $owner->save(); field_owner::ensure_field_owner_exists($field, 'moodle_profile'); $DB->execute("UPDATE {" . field_owner::TABLE . "} SET exclude = ?", array(pm_moodle_profile::sync_to_moodle)); $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => CONTEXT_ELIS_USER)); $fieldcontextlevel->save(); // The associated Moodle user profile field. require_once $CFG->dirroot . '/user/profile/definelib.php'; require_once $CFG->dirroot . '/user/profile/field/checkbox/define.class.php'; $profiledefinecheckbox = new profile_define_checkbox(); $data = new stdClass(); $data->datatype = 'checkbox'; $data->categoryid = 99999; $data->shortname = 'autoassociate'; $data->name = 'autoassociate'; $profiledefinecheckbox->define_save($data); $mfield = $DB->get_record('user_info_field', array('shortname' => 'autoassociate')); // The "cluster-profile" association. $usersetprofile = new userset_profile(array('clusterid' => $userset->id, 'fieldid' => $mfield->id, 'value' => true)); $usersetprofile->save(); } // Enrol the user in the Moodle course. $mdluserid = $DB->get_field('user', 'id', array('username' => 'testuserusername')); $roleid = create_role('testrole', 'testrole', 'testrole'); enrol_try_internal_enrol($course->id, $mdluserid, $roleid); // Set up the necessary config data. set_config('userset_groups', 1, 'elisprogram_usetgroups'); set_config('siteguest', ''); // Validate setup. $this->assertEquals(0, $DB->count_records('groups')); }