function definition() { global $CFG, $DB; $mform = $this->_form; list($instance, $plugin, $course) = $this->_customdata; $coursecontext = context_course::instance($course->id); $enrol = enrol_get_plugin('cohort'); $groups = array(0 => get_string('none')); foreach (groups_get_all_groups($course->id) as $group) { $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext)); } $mform->addElement('header', 'general', get_string('pluginname', 'enrol_cohort')); $mform->addElement('text', 'name', get_string('custominstancename', 'enrol')); $mform->setType('name', PARAM_TEXT); $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'), ENROL_INSTANCE_DISABLED => get_string('no')); $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options); if ($instance->id) { if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) { $cohorts = array($instance->customint1 => format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)))); } else { $cohorts = array($instance->customint1 => get_string('error')); } $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $cohorts); $mform->setConstant('customint1', $instance->customint1); $mform->hardFreeze('customint1', $instance->customint1); } else { $cohorts = array('' => get_string('choosedots')); $allcohorts = cohort_get_available_cohorts($coursecontext, 0, 0, 0); foreach ($allcohorts as $c) { $cohorts[$c->id] = format_string($c->name); } $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $cohorts); $mform->addRule('customint1', get_string('required'), 'required', null, 'client'); } $roles = get_assignable_roles($coursecontext); $roles[0] = get_string('none'); $roles = array_reverse($roles, true); // Descending default sortorder. $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles); $mform->setDefault('roleid', $enrol->get_config('roleid')); if ($instance->id and !isset($roles[$instance->roleid])) { if ($role = $DB->get_record('role', array('id' => $instance->roleid))) { $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS, true); $roles[$instance->roleid] = role_get_name($role, $coursecontext); } else { $roles[$instance->roleid] = get_string('error'); } } $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups); $mform->addElement('hidden', 'courseid', null); $mform->setType('courseid', PARAM_INT); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); if ($instance->id) { $this->add_action_buttons(true); } else { $this->add_action_buttons(true, get_string('addinstance', 'enrol')); } $this->set_data($instance); }
protected function setUp() { global $DB, $CFG; $this->resetAfterTest(true); unset_config('noemailever'); $CFG->enablecompletion = true; $user = $this->getDataGenerator()->create_user(); $fordb = new stdClass(); $fordb->id = null; $fordb->name = "Test badge"; $fordb->description = "Testing badges"; $fordb->timecreated = time(); $fordb->timemodified = time(); $fordb->usercreated = $user->id; $fordb->usermodified = $user->id; $fordb->issuername = "Test issuer"; $fordb->issuerurl = "http://issuer-url.domain.co.nz"; $fordb->issuercontact = "*****@*****.**"; $fordb->expiredate = null; $fordb->expireperiod = null; $fordb->type = BADGE_TYPE_SITE; $fordb->courseid = null; $fordb->messagesubject = "Test message subject"; $fordb->message = "Test message body"; $fordb->attachment = 1; $fordb->notification = 0; $fordb->status = BADGE_STATUS_INACTIVE; $this->badgeid = $DB->insert_record('badge', $fordb, true); // Create a course with activity and auto completion tracking. $this->course = $this->getDataGenerator()->create_course(array('enablecompletion' => true)); $this->user = $this->getDataGenerator()->create_user(); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->assertNotEmpty($studentrole); // Get manual enrolment plugin and enrol user. require_once($CFG->dirroot.'/enrol/manual/locallib.php'); $manplugin = enrol_get_plugin('manual'); $maninstance = $DB->get_record('enrol', array('courseid' => $this->course->id, 'enrol' => 'manual'), '*', MUST_EXIST); $manplugin->enrol_user($maninstance, $this->user->id, $studentrole->id); $this->assertEquals(1, $DB->count_records('user_enrolments')); $completionauto = array('completion' => COMPLETION_TRACKING_AUTOMATIC); $this->module = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id), $completionauto); // Build badge and criteria. $fordb->type = BADGE_TYPE_COURSE; $fordb->courseid = $this->course->id; $fordb->status = BADGE_STATUS_ACTIVE; $this->coursebadge = $DB->insert_record('badge', $fordb, true); $this->assertion = new stdClass(); $this->assertion->badge = '{"uid":"%s","recipient":{"identity":"%s","type":"email","hashed":true,"salt":"%s"},"badge":"%s","verify":{"type":"hosted","url":"%s"},"issuedOn":"%d","evidence":"%s"}'; $this->assertion->class = '{"name":"%s","description":"%s","image":"%s","criteria":"%s","issuer":"%s"}'; $this->assertion->issuer = '{"name":"%s","url":"%s","email":"%s"}'; }
/** * Return guest enrolment instance information. * * @param int $instanceid instance id of guest enrolment plugin. * @return array warnings and instance information. * @since Moodle 3.1 */ public static function get_instance_info($instanceid) { global $DB; $params = self::validate_parameters(self::get_instance_info_parameters(), array('instanceid' => $instanceid)); $warnings = array(); // Retrieve guest enrolment plugin. $enrolplugin = enrol_get_plugin('guest'); if (empty($enrolplugin)) { throw new moodle_exception('invaliddata', 'error'); } require_login(null, false, null, false, true); $enrolinstance = $DB->get_record('enrol', array('id' => $params['instanceid']), '*', MUST_EXIST); $course = $DB->get_record('course', array('id' => $enrolinstance->courseid), '*', MUST_EXIST); $context = context_course::instance($course->id); if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) { throw new moodle_exception('coursehidden'); } $instanceinfo = $enrolplugin->get_enrol_info($enrolinstance); // Specific instance information. $instanceinfo->passwordrequired = $instanceinfo->requiredparam->passwordrequired; unset($instanceinfo->requiredparam); $result = array(); $result['instanceinfo'] = $instanceinfo; $result['warnings'] = $warnings; return $result; }
/** * Return self-enrolment instance information. * * @param int $instanceid instance id of self enrolment plugin. * @return array instance information. * @throws moodle_exception */ public static function get_instance_info($instanceid) { global $DB, $CFG; require_once $CFG->libdir . '/enrollib.php'; $params = self::validate_parameters(self::get_instance_info_parameters(), array('instanceid' => $instanceid)); // Retrieve self enrolment plugin. $enrolplugin = enrol_get_plugin('self'); if (empty($enrolplugin)) { throw new moodle_exception('invaliddata', 'error'); } // Note that we can't use validate_context because the user is not enrolled in the course. require_login(null, false, null, false, true); $enrolinstance = $DB->get_record('enrol', array('id' => $params['instanceid']), '*', MUST_EXIST); $course = $DB->get_record('course', array('id' => $enrolinstance->courseid), '*', MUST_EXIST); $context = context_course::instance($course->id); if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) { throw new moodle_exception('coursehidden'); } $instanceinfo = (array) $enrolplugin->get_enrol_info($enrolinstance); if (isset($instanceinfo['requiredparam']->enrolpassword)) { $instanceinfo['enrolpassword'] = $instanceinfo['requiredparam']->enrolpassword; } unset($instanceinfo->requiredparam); return $instanceinfo; }
function definition() { global $CFG, $DB; $mform = $this->_form; $course = $this->_customdata; $coursecontext = context_course::instance($course->id); $enrol = enrol_get_plugin('cohort'); $cohorts = array('' => get_string('choosedots')); list($sqlparents, $params) = $DB->get_in_or_equal(get_parent_contexts($coursecontext)); $sql = "SELECT id, name, contextid\n FROM {cohort}\n WHERE contextid {$sqlparents}\n ORDER BY name ASC"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $c) { $context = get_context_instance_by_id($c->contextid); if (!has_capability('moodle/cohort:view', $context)) { continue; } $cohorts[$c->id] = format_string($c->name); } $rs->close(); $roles = get_assignable_roles($coursecontext); $roles[0] = get_string('none'); $roles = array_reverse($roles, true); // descending default sortorder $mform->addElement('header', 'general', get_string('pluginname', 'enrol_cohort')); $mform->addElement('select', 'cohortid', get_string('cohort', 'cohort'), $cohorts); $mform->addRule('cohortid', get_string('required'), 'required', null, 'client'); $mform->addElement('select', 'roleid', get_string('role'), $roles); $mform->addRule('roleid', get_string('required'), 'required', null, 'client'); $mform->setDefault('roleid', $enrol->get_config('roleid')); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); $this->add_action_buttons(true, get_string('addinstance', 'enrol')); $this->set_data(array('id' => $course->id)); }
/** * Test get_users_courses */ public function test_get_users_courses() { global $USER; $this->resetAfterTest(true); $course1 = self::getDataGenerator()->create_course(); $course2 = self::getDataGenerator()->create_course(); $courses = array($course1, $course2); // Enrol $USER in the courses. // We use the manual plugin. $enrol = enrol_get_plugin('manual'); $roleid = null; foreach ($courses as $course) { $context = context_course::instance($course->id); $roleid = $this->assignUserCapability('moodle/course:viewparticipants', $context->id, $roleid); $enrolinstances = enrol_get_instances($course->id, true); foreach ($enrolinstances as $courseenrolinstance) { if ($courseenrolinstance->enrol == "manual") { $instance = $courseenrolinstance; break; } } $enrol->enrol_user($instance, $USER->id, $roleid); } // Call the external function. $enrolledincourses = core_enrol_external::get_users_courses($USER->id); // We need to execute the return values cleaning process to simulate the web service server. $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses); // Check we retrieve the good total number of enrolled users. $this->assertEquals(2, count($enrolledincourses)); }
public function execute() { global $CFG, $DB; require_once $CFG->dirroot . '/cohort/lib.php'; require_once $CFG->dirroot . '/enrol/cohort/locallib.php'; foreach ($this->arguments as $argument) { $this->expandOptionsManually(array($argument)); $options = $this->expandedOptions; // Sanity Checks. // Check if cohorst exists. if (!($cohorts = $DB->get_records('cohort', array('name' => $argument)))) { echo "Cohort does not exist\n"; exit(0); } // Check if enough arguments. if (empty($options['courseid']) && empty($options['userid'])) { echo "Not enough arguments, provide userid or courseid\n"; } // Check if course exists. $course = ''; if (!empty($options['courseid'])) { if (!($course = $DB->get_record('course', array('id' => $options['courseid'])))) { echo "Course does not exist\n"; exit(0); } } // Check if user exists. if (!empty($options['userid'])) { if (!($user = $DB->get_record('user', array('id' => $options['userid'])))) { echo "User does not exist\n"; exit(0); } } // Add cohort to course if (!empty($course)) { foreach ($cohorts as $cohort) { // Check if cohort enrolment already exists if ($cohortenrolment = $DB->get_record('enrol', array('customint1' => $cohort->id, 'courseid' => $options['courseid']))) { echo " Notice: Cohort already enrolled into course\n"; } else { $enrol = enrol_get_plugin('cohort'); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $enrol->add_instance($course, array('name' => $argument . '_sync', 'status' => 0, 'customint1' => $cohort->id, 'roleid' => $studentrole->id, 'customint2' => '0')); echo "Cohort enrolled\n"; } $this->enrol_cohort_sync($course->id); } } if (!empty($user)) { foreach ($cohorts as $cohort) { cohort_add_member($cohort->id, $options['userid']); echo "User enrolled\n"; if (!empty($course)) { $this->enrol_cohort_sync($course->id); } } } } }
/** * Set up our main Moodle course to be enrollable */ protected function make_course_enrollable() { set_config('enrol_plugins_enabled', 'manual'); $enrol = enrol_get_plugin('manual'); $course = new \stdClass(); $course->id = 2; $enrol->add_instance($course); }
/** * @param mr_fixture_course $course The course to enroll the user into * @param mr_fixture_user $user The user to enroll * @param enrol_plugin $enroll The enrollment plugin to use, defaults to enrol_get_plugin('manual') * @param mr_fixture_role|null $role The role to use for the enrollment, optional * @param array|object $options Parameters to pass to the enrol_plugin->enrol_user() */ public function __construct(mr_fixture_course $course, mr_fixture_user $user, enrol_plugin $enroll = null, mr_fixture_role $role = null, $options = array()) { parent::__construct(); if (is_null($enroll)) { $enroll = enrol_get_plugin('manual'); } $this->set_course($course)->set_user($user)->set_enroll($enroll)->set_role($role)->set_options($options); }
/** * Enrolment of users. * * Function throw an exception at the first error encountered. * @param array $enrolments An array of user enrolment * @since Moodle 2.2 */ public static function enrol_users($enrolments) { global $DB, $CFG; require_once $CFG->libdir . '/enrollib.php'; $params = self::validate_parameters(self::enrol_users_parameters(), array('enrolments' => $enrolments)); $transaction = $DB->start_delegated_transaction(); // Rollback all enrolment if an error occurs // (except if the DB doesn't support it). // Retrieve the manual enrolment plugin. $enrol = enrol_get_plugin('manual'); if (empty($enrol)) { throw new moodle_exception('manualpluginnotinstalled', 'enrol_manual'); } foreach ($params['enrolments'] as $enrolment) { // Ensure the current user is allowed to run this function in the enrolment context. $context = context_course::instance($enrolment['courseid'], IGNORE_MISSING); self::validate_context($context); // Check that the user has the permission to manual enrol. require_capability('enrol/manual:enrol', $context); // Throw an exception if user is not able to assign the role. $roles = get_assignable_roles($context); if (!array_key_exists($enrolment['roleid'], $roles)) { $errorparams = new stdClass(); $errorparams->roleid = $enrolment['roleid']; $errorparams->courseid = $enrolment['courseid']; $errorparams->userid = $enrolment['userid']; throw new moodle_exception('wsusercannotassign', 'enrol_manual', '', $errorparams); } // Check manual enrolment plugin instance is enabled/exist. $instance = null; $enrolinstances = enrol_get_instances($enrolment['courseid'], true); foreach ($enrolinstances as $courseenrolinstance) { if ($courseenrolinstance->enrol == "manual") { $instance = $courseenrolinstance; break; } } if (empty($instance)) { $errorparams = new stdClass(); $errorparams->courseid = $enrolment['courseid']; throw new moodle_exception('wsnoinstance', 'enrol_manual', $errorparams); } // Check that the plugin accept enrolment (it should always the case, it's hard coded in the plugin). if (!$enrol->allow_enrol($instance)) { $errorparams = new stdClass(); $errorparams->roleid = $enrolment['roleid']; $errorparams->courseid = $enrolment['courseid']; $errorparams->userid = $enrolment['userid']; throw new moodle_exception('wscannotenrol', 'enrol_manual', '', $errorparams); } // Finally proceed the enrolment. $enrolment['timestart'] = isset($enrolment['timestart']) ? $enrolment['timestart'] : 0; $enrolment['timeend'] = isset($enrolment['timeend']) ? $enrolment['timeend'] : 0; $enrolment['status'] = isset($enrolment['suspend']) && !empty($enrolment['suspend']) ? ENROL_USER_SUSPENDED : ENROL_USER_ACTIVE; $enrol->enrol_user($instance, $enrolment['userid'], $enrolment['roleid'], $enrolment['timestart'], $enrolment['timeend'], $enrolment['status']); } $transaction->allow_commit(); }
/** * Test can_delete_instance */ public function test_can_delete_instance() { global $DB, $CFG; require_once $CFG->dirroot . '/enrol/uaims/lib.php'; $this->resetAfterTest(); // Create users to enrol. $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); // User to use in IMS enrol. $user3 = $this->getDataGenerator()->create_user(array('idnumber' => 'testuser3')); $xmldoc = <<<DOC <?xml version="1.0" encoding="utf-8"?> <enterprise xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <group recstatus="1"> <sourcedid> <source>AIS</source> <id>IDNUMBER</id> </sourcedid> <grouptype> <typevalue>Course</typevalue> </grouptype> <description> <short>IDNUMBER</short> <long>Long description</long> </description> <org /> <timeframe> <begin>1420441200</begin> <end>1431237600</end> </timeframe> <enrollcontrol /> <relationship> <sourcedid> <source>AIS</source> <id>UOFAB-TEST</id> </sourcedid> </relationship> <extension> <settings> <setting>visible</setting> <value>0</value> </settings> <settings> <setting>format</setting> <value>topics</value> </settings> </extension></group> <membership> <sourcedid> <source>AIS</source> <id>IDNUMBER</id> </sourcedid> <member> <idtype>1</idtype> <sourcedid> <source>AIS</source> <id>testuser3</id> </sourcedid> <role recstatus="1" roletype="05"> <status>1</status> </role> </member> </membership></enterprise> DOC; $category = new stdClass(); $category->name = "test"; $category->description = "UOFAB-TEST"; $category->idnumber = "UOFAB-TEST"; $category->timemodified = time(); $DB->insert_record('course_categories', $category); $enrol = new enrol_uaims_plugin(); // Make sure the course does not already exist. $course = $DB->get_record('course', array('idnumber' => "IDNUMBER"), $fields = '*', $strictness = IGNORE_MISSING); $this->assertEquals(false, $course); // Process the IMS Doc. $enrol->process_imsdoc($xmldoc); $course = $DB->get_record('course', array('idnumber' => "IDNUMBER"), $fields = '*', $strictness = MUST_EXIST); $manplugin = enrol_get_plugin('manual'); $uaimsplugin = enrol_get_plugin('uaims'); // Get the manager and teacher roles. $managerrole = $DB->get_record('role', array('shortname' => 'manager')); $this->assertNotEmpty($managerrole); $teacherrole = $DB->get_record('role', array('shortname' => 'teacher')); $this->assertNotEmpty($teacherrole); $maninstance1 = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'manual'), '*', MUST_EXIST); $uaimsinstance1 = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'uaims'), '*', MUST_EXIST); // Manually enrol users since the IMS plugin incorrectly assigns roles. CC does this as a separate process. $manplugin->enrol_user($maninstance1, $user1->id, $managerrole->id); $manplugin->enrol_user($maninstance1, $user2->id, $teacherrole->id); // Test that managers can delete the UAIM enrol method. $this->setUser($user1); $this->assertEquals(true, $uaimsplugin->can_delete_instance($uaimsinstance1)); // Test that teachers can NOT delete the UAIM enrol method. $this->setUser($user2); $this->assertEquals(false, $uaimsplugin->can_delete_instance($uaimsinstance1)); }
function enrol_into_course($courseid, $userid, $roleid = 5) { global $DB; $manualenrol = enrol_get_plugin('manual'); // get the enrolment plugin $enrolinstance = $DB->get_record('enrol', array('courseid' => $courseid, 'status' => ENROL_INSTANCE_ENABLED, 'enrol' => 'manual'), '*', MUST_EXIST); // retrieve enrolment instance associated with your course return $manualenrol->enrol_user($enrolinstance, $userid, $roleid); // enrol the user }
/** * Test get_instance_info */ public function test_get_instance_info() { global $DB; $this->resetAfterTest(true); // Check if guest enrolment plugin is enabled. $guestplugin = enrol_get_plugin('guest'); $this->assertNotEmpty($guestplugin); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $coursedata = new stdClass(); $coursedata->visible = 0; $course = self::getDataGenerator()->create_course($coursedata); $student = self::getDataGenerator()->create_user(); $this->getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id, 'manual'); // Add enrolment methods for course. $instance = $guestplugin->add_instance($course, array('status' => ENROL_INSTANCE_ENABLED, 'name' => 'Test instance', 'customint6' => 1, 'roleid' => $studentrole->id)); $this->setAdminUser(); $result = enrol_guest_external::get_instance_info($instance); $result = external_api::clean_returnvalue(enrol_guest_external::get_instance_info_returns(), $result); $this->assertEquals($instance, $result['instanceinfo']['id']); $this->assertEquals($course->id, $result['instanceinfo']['courseid']); $this->assertEquals('guest', $result['instanceinfo']['type']); $this->assertEquals('Test instance', $result['instanceinfo']['name']); $this->assertTrue($result['instanceinfo']['status']); $this->assertFalse($result['instanceinfo']['passwordrequired']); $DB->set_field('enrol', 'status', ENROL_INSTANCE_DISABLED, array('id' => $instance)); $result = enrol_guest_external::get_instance_info($instance); $result = external_api::clean_returnvalue(enrol_guest_external::get_instance_info_returns(), $result); $this->assertEquals($instance, $result['instanceinfo']['id']); $this->assertEquals($course->id, $result['instanceinfo']['courseid']); $this->assertEquals('guest', $result['instanceinfo']['type']); $this->assertEquals('Test instance', $result['instanceinfo']['name']); $this->assertFalse($result['instanceinfo']['status']); $this->assertFalse($result['instanceinfo']['passwordrequired']); $DB->set_field('enrol', 'status', ENROL_INSTANCE_ENABLED, array('id' => $instance)); // Try to retrieve information using a normal user for a hidden course. $user = self::getDataGenerator()->create_user(); $this->setUser($user); try { enrol_guest_external::get_instance_info($instance); } catch (moodle_exception $e) { $this->assertEquals('coursehidden', $e->errorcode); } // Student user. $DB->set_field('course', 'visible', 1, array('id' => $course->id)); $this->setUser($student); $result = enrol_guest_external::get_instance_info($instance); $result = external_api::clean_returnvalue(enrol_guest_external::get_instance_info_returns(), $result); $this->assertEquals($instance, $result['instanceinfo']['id']); $this->assertEquals($course->id, $result['instanceinfo']['courseid']); $this->assertEquals('guest', $result['instanceinfo']['type']); $this->assertEquals('Test instance', $result['instanceinfo']['name']); $this->assertTrue($result['instanceinfo']['status']); $this->assertFalse($result['instanceinfo']['passwordrequired']); }
function xmldb_enrol_metaplus_uninstall() { global $CFG, $DB; $meta = enrol_get_plugin('metaplus'); $rs = $DB->get_recordset('enrol', array('enrol' => 'metaplus')); foreach ($rs as $instance) { $meta->delete_instance($instance); } $rs->close(); role_unassign_all(array('component' => 'enrol_metaplus')); return true; }
/** * Do the job. * Throw exceptions on errors (the job will be retried). */ public function execute() { global $CFG; require_once $CFG->dirroot . '/enrol/flatfile/lib.php'; if (!enrol_is_enabled('flatfile')) { return; } // Instance of enrol_flatfile_plugin. $plugin = enrol_get_plugin('flatfile'); $result = $plugin->sync(new \null_progress_trace()); return $result; }
function xmldb_enrol_delayedcohort_uninstall() { global $CFG, $DB; $cohort = enrol_get_plugin('delayedcohort'); $rs = $DB->get_recordset('enrol', array('enrol' => 'delayedcohort')); foreach ($rs as $instance) { $cohort->delete_instance($instance); } $rs->close(); role_unassign_all(array('component' => 'enrol_delayedcohort')); return true; }
/** * Test get_instance_info */ public function test_get_instance_info() { global $DB; $this->resetAfterTest(true); // Check if self enrolment plugin is enabled. $selfplugin = enrol_get_plugin('self'); $this->assertNotEmpty($selfplugin); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->assertNotEmpty($studentrole); $coursedata = new stdClass(); $coursedata->visible = 0; $course = self::getDataGenerator()->create_course($coursedata); // Add enrolment methods for course. $instanceid1 = $selfplugin->add_instance($course, array('status' => ENROL_INSTANCE_ENABLED, 'name' => 'Test instance 1', 'customint6' => 1, 'roleid' => $studentrole->id)); $instanceid2 = $selfplugin->add_instance($course, array('status' => ENROL_INSTANCE_DISABLED, 'customint6' => 1, 'name' => 'Test instance 2', 'roleid' => $studentrole->id)); $instanceid3 = $selfplugin->add_instance($course, array('status' => ENROL_INSTANCE_ENABLED, 'roleid' => $studentrole->id, 'customint6' => 1, 'name' => 'Test instance 3', 'password' => 'test')); $enrolmentmethods = $DB->get_records('enrol', array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED)); $this->assertCount(3, $enrolmentmethods); $this->setAdminUser(); $instanceinfo1 = enrol_self_external::get_instance_info($instanceid1); $instanceinfo1 = external_api::clean_returnvalue(enrol_self_external::get_instance_info_returns(), $instanceinfo1); $this->assertEquals($instanceid1, $instanceinfo1['id']); $this->assertEquals($course->id, $instanceinfo1['courseid']); $this->assertEquals('self', $instanceinfo1['type']); $this->assertEquals('Test instance 1', $instanceinfo1['name']); $this->assertTrue($instanceinfo1['status']); $this->assertFalse(isset($instanceinfo1['enrolpassword'])); $instanceinfo2 = enrol_self_external::get_instance_info($instanceid2); $instanceinfo2 = external_api::clean_returnvalue(enrol_self_external::get_instance_info_returns(), $instanceinfo2); $this->assertEquals($instanceid2, $instanceinfo2['id']); $this->assertEquals($course->id, $instanceinfo2['courseid']); $this->assertEquals('self', $instanceinfo2['type']); $this->assertEquals('Test instance 2', $instanceinfo2['name']); $this->assertEquals(get_string('canntenrol', 'enrol_self'), $instanceinfo2['status']); $this->assertFalse(isset($instanceinfo2['enrolpassword'])); $instanceinfo3 = enrol_self_external::get_instance_info($instanceid3); $instanceinfo3 = external_api::clean_returnvalue(enrol_self_external::get_instance_info_returns(), $instanceinfo3); $this->assertEquals($instanceid3, $instanceinfo3['id']); $this->assertEquals($course->id, $instanceinfo3['courseid']); $this->assertEquals('self', $instanceinfo3['type']); $this->assertEquals('Test instance 3', $instanceinfo3['name']); $this->assertTrue($instanceinfo3['status']); $this->assertEquals(get_string('password', 'enrol_self'), $instanceinfo3['enrolpassword']); // Try to retrieve information using a normal user for a hidden course. $user = self::getDataGenerator()->create_user(); $this->setUser($user); try { enrol_self_external::get_instance_info($instanceid3); } catch (moodle_exception $e) { $this->assertEquals('coursehidden', $e->errorcode); } }
/** * Sets up the table. * * @param string $courseid The id of the course. */ public function __construct($courseid) { parent::__construct('enrol_lti_manage_table'); $this->define_columns(array('name', 'url', 'secret', 'edit')); $this->define_headers(array(get_string('name'), get_string('url'), get_string('secret', 'enrol_lti'), get_string('edit'))); $this->collapsible(false); $this->sortable(false); // Set the variables we need access to. $this->ltiplugin = enrol_get_plugin('lti'); $this->ltienabled = enrol_is_enabled('lti'); $this->canconfig = has_capability('moodle/course:enrolconfig', \context_course::instance($courseid)); $this->courseid = $courseid; }
public function deleted($cohort) { global $DB; // does anything want to sync with this parent? if (!($enrols = $DB->get_records('enrol', array('customint1' => $cohort->id, 'enrol' => 'cohort'), 'id ASC'))) { return true; } $plugin = enrol_get_plugin('cohort'); foreach ($enrols as $enrol) { $plugin->delete_instance($enrol); } return true; }
public function execute() { global $CFG, $DB; require_once $CFG->dirroot . '/course/lib.php'; foreach ($this->arguments as $argument) { $this->expandOptionsManually(array($argument)); $options = $this->expandedOptions; // get the details for the course $course = $DB->get_record('course', array('id' => $argument), '*', MUST_EXIST); // get the details of the self enrolment plugin $plugin = enrol_get_plugin('self'); if (!$plugin) { throw new \Exception('could not find self enrolment plugin'); } // get the enrolment plugin instances for the course $instances = enrol_get_instances($course->id, false); // loop through the instances to find the instance ID for the self-enrolment plugin $selfEnrolInstance = 0; foreach ($instances as $instance) { if ($instance->enrol === 'self') { $selfEnrolInstance = $instance; } } // if we didn't find an instance for the self enrolment plugin then we need to add // one to the course if (!$selfEnrolInstance) { // first try add an instance $plugin->add_default_instance($course); // then try retreive it $instances = enrol_get_instances($course->id, false); $selfEnrolInstance = 0; foreach ($instances as $instance) { if ($instance->enrol === 'self') { $selfEnrolInstance = $instance; } } // if we still didn't get an instance - give up if (!$selfEnrolInstance) { throw new \Exception('failed to create instance of self enrolment plugin'); } } // activate self enrolment if ($selfEnrolInstance->status != ENROL_INSTANCE_ENABLED) { $plugin->update_status($selfEnrolInstance, ENROL_INSTANCE_ENABLED); } // set the enrolment key (always do this so running without the -k option will blank a pre-existing key) $instance_fromDB = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'self', 'id' => $selfEnrolInstance->id), '*', MUST_EXIST); $instance_fromDB->password = $options['key']; $DB->update_record('enrol', $instance_fromDB); } }
public function test_message_get_providers_for_user_more() { global $DB; $this->resetAfterTest(); // Create a course. $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); // It would probably be better to use a quiz instance as it has capability controlled messages // however mod_quiz doesn't have a data generator. // Instead we're going to use backup notifications and give and take away the capability at various levels. $assign = $this->getDataGenerator()->create_module('assign', array('course' => $course->id)); $modulecontext = context_module::instance($assign->cmid); // Create and enrol a teacher. $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'), '*', MUST_EXIST); $teacher = $this->getDataGenerator()->create_user(); role_assign($teacherrole->id, $teacher->id, $coursecontext); $enrolplugin = enrol_get_plugin('manual'); $enrolplugin->add_instance($course); $enrolinstances = enrol_get_instances($course->id, false); foreach ($enrolinstances as $enrolinstance) { if ($enrolinstance->enrol === 'manual') { break; } } $enrolplugin->enrol_user($enrolinstance, $teacher->id); // Make the teacher the current user. $this->setUser($teacher); // Teacher shouldn't have the required capability so they shouldn't be able to see the backup message. $this->assertFalse(has_capability('moodle/site:config', $modulecontext)); $providers = message_get_providers_for_user($teacher->id); $this->assertFalse($this->message_type_present('moodle', 'backup', $providers)); // Give the user the required capability in an activity module. // They should now be able to see the backup message. assign_capability('moodle/site:config', CAP_ALLOW, $teacherrole->id, $modulecontext->id, true); accesslib_clear_all_caches_for_unit_testing(); $modulecontext = context_module::instance($assign->cmid); $this->assertTrue(has_capability('moodle/site:config', $modulecontext)); $providers = message_get_providers_for_user($teacher->id); $this->assertTrue($this->message_type_present('moodle', 'backup', $providers)); // Prohibit the capability for the user at the course level. // This overrules the CAP_ALLOW at the module level. // They should not be able to see the backup message. assign_capability('moodle/site:config', CAP_PROHIBIT, $teacherrole->id, $coursecontext->id, true); accesslib_clear_all_caches_for_unit_testing(); $modulecontext = context_module::instance($assign->cmid); $this->assertFalse(has_capability('moodle/site:config', $modulecontext)); $providers = message_get_providers_for_user($teacher->id); // Actually, handling PROHIBITs would be too expensive. We do not // care if users with PROHIBITs see a few more preferences than they should. // $this->assertFalse($this->message_type_present('moodle', 'backup', $providers)); }
/** * Returns success or failure * * @return bool success or failure */ public static function process_magento_request($order_number, $customer, $moodle_courses) { global $USER, $DB; if (get_config('magentoconnector', 'magentoconnectorenabled') == 0) { return false; } $params = self::validate_parameters(self::process_magento_request_parameters(), array('order_number' => $order_number, 'customer' => $customer, 'moodle_courses' => $moodle_courses)); $context = context_user::instance($USER->id); self::validate_context($context); if (!($user = $DB->get_record('user', array('email' => $customer['email'])))) { $user = new stdClass(); $user->firstname = $customer['firstname']; $user->lastname = $customer['lastname']; $user->email = $customer['email']; $user->city = $customer['city']; $user->country = $customer['country']; $user->confirmed = 1; $user->policyagreed = 1; $user->mnethostid = 1; $user->username = local_magentoconnector_generate_username($customer['firstname'], $customer['lastname']); $user->timecreated = time(); $password = generate_password(); $user->password = hash_internal_user_password($password); $userid = $DB->insert_record('user', $user); } else { $userid = $user->id; } $roleid = $DB->get_field('role', 'id', array('shortname' => LOCAL_MAGENTOCONNECTOR_STUDENT_SHORTNAME)); $enrol = enrol_get_plugin('magento'); foreach ($moodle_courses as $moodle_course) { if ($course = $DB->get_record('course', array('idnumber' => $moodle_course['course_id']))) { $enrolinstance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'magento'), '*', MUST_EXIST); $enrol->enrol_user($enrolinstance, $userid, $roleid); $record = new stdClass(); $record->userid = $userid; $record->ordernum = $order_number; $record->courseid = $course->id; $record->timestamp = time(); $DB->insert_record('local_magentoconnector_trans', $record); } else { // no such course ... ? } } if (isset($password)) { $enrolinstance->newusername = $user->username; $enrolinstance->newaccountpassword = $password; } $customer = $DB->get_record('user', array('id' => $userid)); $enrol->email_welcome_message($enrolinstance, $customer); return true; }
public function test_basics() { # disabled by default $this->assertFalse(enrol_is_enabled('auto')); # correct enrol instance $plugin = enrol_get_plugin('auto'); $this->assertInstanceOf('enrol_auto_plugin', $plugin); # default config checks $this->assertEquals('1', get_config('enrol_auto', 'defaultenrol')); $this->assertEquals('1', get_config('enrol_auto', 'status')); $this->assertEquals(ENROL_AUTO_COURSE_VIEWED, get_config('enrol_auto', 'enrolon')); $this->assertEquals('1', get_config('enrol_auto', 'sendcoursewelcomemessage')); $this->assertEquals('', get_config('enrol_auto', 'modviewmods')); }
function enrol_user($userid, $courseid) { global $DB; if (!enrol_is_enabled('manual')) { return false; } if (!($enrol = enrol_get_plugin('manual'))) { return false; } $params = array('enrol' => 'manual', 'courseid' => $courseid, 'status' => ENROL_INSTANCE_ENABLED); if (!($instances = $DB->get_records('enrol', $params, 'sortorder,id ASC'))) { return false; } $instance = reset($instances); $enrol->enrol_user($instance, $userid, $instance->roleid, time(), time() + 24 * 60 * 60 * 30); }
public function validation($data, $files) { global $DB, $CFG; $errors = parent::validation($data, $files); $instance = $this->instance; if ($instance->password !== '') { if ($data['guestpassword'] !== $instance->password) { $plugin = enrol_get_plugin('guest'); if ($plugin->get_config('showhint')) { $hint = textlib::substr($instance->password, 0, 1); $errors['guestpassword'] = get_string('passwordinvalidhint', 'enrol_guest', $hint); } else { $errors['guestpassword'] = get_string('passwordinvalid', 'enrol_guest'); } } } return $errors; }
function block_csv_enrol_enrol_users($courseid, $csvcontent) { global $DB, $CFG; require_once $CFG->libdir . '/enrollib.php'; //get enrolment instance (manual and student) $instances = enrol_get_instances($courseid, false); $enrolment = ""; foreach ($instances as $instance) { if ($instance->enrol === 'manual') { $enrolment = $instance; break; } } //get enrolment plugin $manual = enrol_get_plugin('manual'); $context = get_context_instance(CONTEXT_COURSE, $courseid); $stats = new StdClass(); $stats->success = $stats->failed = 0; //init counters $log = get_string('enrolling', 'block_csv_enrol') . "\r\n"; $lines = explode("\n", $csvcontent); foreach ($lines as $line) { if ($line == "") { continue; } $user = $DB->get_record('user', array('email' => trim($line))); if ($user && !$user->deleted) { if (is_enrolled($context, $user)) { $log .= get_string('enrollinguser', 'block_csv_enrol', fullname($user) . ' (' . $user->username . ')') . "\r\n"; } else { $log .= get_string('alreadyenrolled', 'block_csv_enrol', fullname($user) . ' (' . $user->username . ')') . "\r\n"; $manual->enrol_user($enrolment, $user->id, $enrolment->roleid, time()); } $stats->success++; } else { $log .= get_string('emailnotfound', 'block_csv_enrol', trim($line)) . "\r\n"; $stats->failed++; } } $log .= get_string('done', 'block_csv_enrol') . "\r\n"; $log = get_string('status', 'block_csv_enrol', $stats) . ' ' . get_string('enrolmentlog', 'block_csv_enrol') . "\r\n\r\n" . $log; return $log; }
/** * Create course with user and activities. */ protected function setup_data() { global $DB, $CFG; $this->resetAfterTest(); // Enable completion before creating modules, otherwise the completion data is not written in DB. $CFG->enablecompletion = true; // Create a course with activities. $this->course = $this->getDataGenerator()->create_course(array('enablecompletion' => true)); $this->user = $this->getDataGenerator()->create_user(); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->assertNotEmpty($studentrole); // Get manual enrolment plugin and enrol user. require_once $CFG->dirroot . '/enrol/manual/locallib.php'; $manplugin = enrol_get_plugin('manual'); $maninstance = $DB->get_record('enrol', array('courseid' => $this->course->id, 'enrol' => 'manual'), '*', MUST_EXIST); $manplugin->enrol_user($maninstance, $this->user->id, $studentrole->id); $this->assertEquals(1, $DB->count_records('user_enrolments')); $this->module1 = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id)); $this->module2 = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id)); }
/** * Enrol two users on one unique course each and one shared course * then merge them. */ public function test_mergeenrolments() { global $DB; // Setup two users to merge. $user_remove = $this->getDataGenerator()->create_user(); $user_keep = $this->getDataGenerator()->create_user(); // Create three courses. $course1 = $this->getDataGenerator()->create_course(); $course2 = $this->getDataGenerator()->create_course(); $course3 = $this->getDataGenerator()->create_course(); $maninstance1 = $DB->get_record('enrol', array('courseid' => $course1->id, 'enrol' => 'manual'), '*', MUST_EXIST); $maninstance2 = $DB->get_record('enrol', array('courseid' => $course2->id, 'enrol' => 'manual'), '*', MUST_EXIST); $maninstance3 = $DB->get_record('enrol', array('courseid' => $course3->id, 'enrol' => 'manual'), '*', MUST_EXIST); $manual = enrol_get_plugin('manual'); $studentrole = $DB->get_record('role', array('shortname' => 'student')); // Enrol $user_remove on course 1 + 2 and $user_keep on course 2 + 3. $manual->enrol_user($maninstance1, $user_remove->id, $studentrole->id); $manual->enrol_user($maninstance2, $user_remove->id, $studentrole->id); $manual->enrol_user($maninstance2, $user_keep->id, $studentrole->id); $manual->enrol_user($maninstance3, $user_keep->id, $studentrole->id); // Check initial state of enrolments for $user_remove. $courses = enrol_get_all_users_courses($user_remove->id); ksort($courses); $this->assertCount(2, $courses); $this->assertEquals(array($course1->id, $course2->id), array_keys($courses)); // Check initial state of enrolments for $user_keep. $courses = enrol_get_all_users_courses($user_keep->id); ksort($courses); $this->assertCount(2, $courses); $this->assertEquals(array($course2->id, $course3->id), array_keys($courses)); $mut = new MergeUserTool(); list($success, $log, $logid) = $mut->merge($user_keep->id, $user_remove->id); // Check $user_remove is suspended. $user_remove = $DB->get_record('user', array('id' => $user_remove->id)); $this->assertEquals(1, $user_remove->suspended); // Check $user_keep is now enrolled on all three courses. $courses = enrol_get_all_users_courses($user_keep->id); ksort($courses); $this->assertCount(3, $courses); $this->assertEquals(array($course1->id, $course2->id, $course3->id), array_keys($courses)); }
/** * Return boleto-enrolment instance information. * * @param int $instanceid instance id of boleto enrolment plugin. * @return array instance information. */ public static function get_instance_info($instanceid) { global $DB, $CFG; require_once $CFG->libdir . '/enrollib.php'; $params = boleto::validate_parameters(boleto::get_instance_info_parameters(), array('instanceid' => $instanceid)); // Retrieve boleto enrolment plugin. $enrolplugin = enrol_get_plugin('boleto'); if (empty($enrolplugin)) { throw new moodle_exception('invaliddata', 'error'); } $enrolinstance = $DB->get_record('enrol', array('id' => $params['instanceid']), '*', MUST_EXIST); $coursecontext = context_course::instance($enrolinstance->courseid); $categorycontext = $coursecontext->get_parent_context(); boleto::validate_context($categorycontext); $instanceinfo = (array) $enrolplugin->get_enrol_info($enrolinstance); if (isset($instanceinfo['requiredparam']->enrolpassword)) { $instanceinfo['enrolpassword'] = $instanceinfo['requiredparam']->enrolpassword; } unset($instanceinfo->requiredparam); return $instanceinfo; }
/** * * @param type $user * @param type $course * @param type $cohort * @param type $mode */ private function enroluserincourse($course, $cohort, $mode) { $enrol = enrol_get_plugin('cohort'); $instance = array(); $instance['name'] = 'name'; $instance['status'] = ENROL_INSTANCE_ENABLED; // Enable it. $instance['customint1'] = $cohort->id; // Used to store the cohort id. $teacherroleid = $enrol->get_config('roleid'); if ($mode == 'teacher') { $teacherroleid = G\getteacherroleid(); } $instance['roleid'] = $teacherroleid; $instance['customint2'] = 0; // Optional group id. $enrol->add_instance($course, $instance); $trace = new null_progress_trace(); enrol_cohort_sync($trace, $course->id); $trace->finished(); }