/** * Triggered via the user_loggedin event, when a user logs in. * * @param stdClass $event */ public static function user_loggedin($event) { global $DB; $eventdata = $event->get_data(); if (!enrol_is_enabled('auto')) { return; } if (is_siteadmin($eventdata['userid'])) { // Don't enrol site admins return; } // Get all courses that have an auto enrol plugin, set to auto enrol on login, where the user isn't enrolled yet $sql = "SELECT e.courseid\n FROM {enrol} e\n LEFT JOIN {user_enrolments} ue ON e.id = ue.enrolid AND ue.userid = ?\n WHERE e.enrol = 'auto'\n AND e.status = ?\n AND e.customint3 = ?\n AND ue.id IS NULL"; if (!($courses = $DB->get_records_sql($sql, array($eventdata['userid'], ENROL_INSTANCE_ENABLED, ENROL_AUTO_LOGIN)))) { return; } $autoplugin = enrol_get_plugin('auto'); foreach ($courses as $course) { if (!($instance = $autoplugin->get_instance_for_course($course->courseid))) { continue; } $autoplugin->enrol_user($instance, $eventdata['userid'], $instance->roleid); // Send welcome message. if ($instance->customint2) { $autoplugin = enrol_get_plugin('auto'); $autoplugin->email_welcome_message($instance, $DB->get_record('user', array('id' => $eventdata['userid']))); } } }
/** * Event processor - cohort member added * @param stdClass $ca * @return bool */ public function member_added($ca) { global $DB; if (!enrol_is_enabled('cohort')) { return true; } // does any enabled cohort instance want to sync with this cohort? $sql = "SELECT e.*, r.id as roleexists\n FROM {enrol} e\n LEFT JOIN {role} r ON (r.id = e.roleid)\n WHERE customint1 = :cohortid AND enrol = 'cohort'\n ORDER BY id ASC"; if (!($instances = $DB->get_records_sql($sql, array('cohortid' => $ca->cohortid)))) { return true; } $plugin = enrol_get_plugin('cohort'); foreach ($instances as $instance) { if ($instance->status != ENROL_INSTANCE_ENABLED) { // no roles for disabled instances $instance->roleid = 0; } else { if ($instance->roleid and !$instance->roleexists) { // invalid role - let's just enrol, they will have to create new sync and delete this one $instance->roleid = 0; } } unset($instance->roleexists); // no problem if already enrolled $plugin->enrol_user($instance, $ca->userid, $instance->roleid, 0, 0, ENROL_USER_ACTIVE); } return true; }
public function test_basics() { $this->assertFalse(enrol_is_enabled('paypal')); $plugin = enrol_get_plugin('paypal'); $this->assertInstanceOf('enrol_paypal_plugin', $plugin); $this->assertEquals(ENROL_EXT_REMOVED_SUSPENDNOROLES, get_config('enrol_paypal', 'expiredaction')); }
public function test_basics() { $this->assertTrue(enrol_is_enabled('self')); $plugin = enrol_get_plugin('self'); $this->assertInstanceOf('enrol_self_plugin', $plugin); $this->assertEquals(1, get_config('enrol_self', 'defaultenrol')); $this->assertEquals(ENROL_EXT_REMOVED_KEEP, get_config('enrol_self', 'expiredaction')); }
/** * Install function for this plugin * * @return boolean true Returns true to satisfy install procedure */ function xmldb_enrol_elis_install() { global $CFG; if (!enrol_is_enabled('elis')) { // force the elis plugin to be enabled set_config('enrol_plugins_enabled', $CFG->enrol_plugins_enabled . ',elis'); } return true; }
/** * Called after updating/inserting course. * * @param bool $inserted true if course just inserted * @param stdClass $course * @param stdClass $data form data * @return void */ public function course_updated($inserted, $course, $data) { global $CFG; if (!enrol_is_enabled('category')) { return; } // Sync category enrols. require_once "{$CFG->dirroot}/enrol/category/locallib.php"; enrol_category_sync_course($course); }
/** * Is it possible to delete enrol instance via standard UI? * * @param stdClass $instance * @return bool */ public function instance_deleteable($instance) { if (!enrol_is_enabled('database')) { return true; } if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) { return true; } //TODO: connect to external system and make sure no users are to be enrolled in this course return false; }
/** * 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; }
/** * Sync all jwc course links. * @param int $courseid one course, empty mean all * @return void */ function enrol_jwc_sync($courseid = NULL) { global $CFG, $DB; // unfortunately this may take a long time @set_time_limit(0); //if this fails during upgrade we can continue from cron, no big deal $jwc = new jwc_helper(); $jwc_enrol = enrol_get_plugin('jwc'); if (enrol_is_enabled('jwc')) { $params = array(); $onecourse = ""; if ($courseid) { $params['courseid'] = $courseid; $onecourse = "AND courseid = :courseid"; } $select = "enrol = :jwc AND status = :status {$onecourse}"; $params['jwc'] = 'jwc'; $params['status'] = ENROL_INSTANCE_ENABLED; $instances = $DB->get_records_select('enrol', $select, $params); foreach ($instances as $instance) { // 课程必须有cas认证的教师 $teachers = enrol_jwc_get_cas_teachers($instance->courseid); if (empty($teachers)) { $DB->set_field('enrol', 'customchar2', '此课程没有使用HITID的教师', array('id' => $instance->id)); continue; } // 从教务处获取所有选修该课程的学生 $return_msg = ''; $students = $jwc->get_students($instance->customchar1, $teachers, $jwc_enrol->get_config('semester'), $return_msg); $DB->set_field('enrol', 'customchar2', $return_msg, array('id' => $instance->id)); if (!$students) { // 出错 continue; // skip this instance. 就算出错,也别清理选课,以免意外。管理员更改学期名时再清理所有选课 } // 开始同步 // 选课 foreach ($students as $userid) { $jwc_enrol->enrol_user($instance, $userid, $instance->roleid); } // 取消教务处删除的选课 if (empty($students)) { $where = "enrolid = {$instance->id}"; } else { $where = "enrolid = {$instance->id} AND userid NOT IN (" . implode(',', $students) . ')'; } $ues = $DB->get_records_select('user_enrolments', $where); foreach ($ues as $ue) { $jwc_enrol->unenrol_user($instance, $ue->userid); } } } }
/** * 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 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')); }
/** * Performs the synchronisation of members. */ public function execute() { if (!is_enabled_auth('lti')) { mtrace('Skipping task - ' . get_string('pluginnotenabled', 'auth', get_string('pluginname', 'auth_lti'))); return; } // Check if the enrolment plugin is disabled - isn't really necessary as the task should not run if // the plugin is disabled, but there is no harm in making sure core hasn't done something wrong. if (!enrol_is_enabled('lti')) { mtrace('Skipping task - ' . get_string('enrolisdisabled', 'enrol_lti')); return; } $this->dataconnector = new data_connector(); // Get all the enabled tools. $tools = helper::get_lti_tools(array('status' => ENROL_INSTANCE_ENABLED, 'membersync' => 1)); foreach ($tools as $tool) { mtrace("Starting - Member sync for published tool '{$tool->id}' for course '{$tool->courseid}'."); // Variables to keep track of information to display later. $usercount = 0; $enrolcount = 0; $unenrolcount = 0; // Fetch consumer records mapped to this tool. $consumers = $this->dataconnector->get_consumers_mapped_to_tool($tool->id); // Perform processing for each consumer. foreach ($consumers as $consumer) { mtrace("Requesting membership service for the tool consumer '{$consumer->getRecordId()}'"); // Get members through this tool consumer. $members = $this->fetch_members_from_consumer($consumer); // Check if we were able to fetch the members. if ($members === false) { mtrace("Skipping - Membership service request failed.\n"); continue; } // Fetched members count. $membercount = count($members); mtrace("{$membercount} members received.\n"); // Process member information. list($usercount, $enrolcount) = $this->sync_member_information($tool, $consumer, $members); } // Now we check if we have to unenrol users who were not listed. if ($this->should_sync_unenrol($tool->membersyncmode)) { $unenrolcount = $this->sync_unenrol($tool); } mtrace("Completed - Synced members for tool '{$tool->id}' in the course '{$tool->courseid}'. " . "Processed {$usercount} users; enrolled {$enrolcount} members; unenrolled {$unenrolcount} members.\n"); } // Sync the user profile photos. mtrace("Started - Syncing user profile images."); $countsyncedimages = $this->sync_profile_images(); mtrace("Completed - Synced {$countsyncedimages} profile images."); }
/** * Is it possible to delete enrol instance via standard UI? * * @param stdClass $instance * @return bool */ public function can_delete_instance($instance) { $context = context_course::instance($instance->courseid); if (!has_capability('enrol/database:config', $context)) { return false; } if (!enrol_is_enabled('database')) { return true; } if (!$this->get_config('dbtype') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) { return true; } //TODO: connect to external system and make sure no users are to be enrolled in this course return false; }
/** * Returns link to manual enrol UI if exists. * Does the access control tests automatically. * * @param object $instance * @return moodle_url */ public function get_manual_enrol_link($instance) { $name = $this->get_name(); if ($instance->enrol !== $name) { throw new coding_exception('invalid enrol instance!'); } if (!enrol_is_enabled($name)) { return NULL; } $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST); if (!has_capability('enrol/manual:manage', $context) or !has_capability('enrol/manual:enrol', $context) or !has_capability('enrol/manual:unenrol', $context)) { return NULL; } return new moodle_url('/enrol/manual/manage.php', array('enrolid' => $instance->id, 'id' => $instance->courseid)); }
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 member_added($ca) { global $DB; if (!enrol_is_enabled('cohort')) { return true; } // does anything want to sync with this parent? //TODO: add join to role table to make sure that roleid actually exists if (!($enrols = $DB->get_records('enrol', array('customint1' => $ca->cohortid, 'enrol' => 'cohort'), 'id ASC'))) { return true; } $plugin = enrol_get_plugin('cohort'); foreach ($enrols as $enrol) { // no problem if already enrolled $plugin->enrol_user($enrol, $ca->userid, $enrol->roleid); } return true; }
/** * Test utility methods used in syn test, fail here means something * in core accesslib was changed, but it is possible that only this test * is affected, nto the plugin itself... */ public function test_utils() { global $DB; $this->resetAfterTest(); $syscontext = context_system::instance(); $this->assertFalse(enrol_is_enabled('category')); $this->enable_plugin(); $this->assertTrue(enrol_is_enabled('category')); $roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext); $this->assertEmpty($roles); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->assertNotEmpty($studentrole); $this->enable_role_sync($studentrole->id); $roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext); $this->assertEquals(1, count($roles)); $this->assertEquals($studentrole, reset($roles)); $this->disable_role_sync($studentrole->id); $roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext); $this->assertEmpty($roles); }
/** * Triggered when user role is unassigned. * * @param \core\event\role_unassigned $event */ public static function role_unassigned(\core\event\role_unassigned $event) { global $DB; if (!enrol_is_enabled('category')) { return; } $ra = new stdClass(); $ra->userid = $event->relateduserid; $ra->contextid = $event->contextid; // only category level roles are interesting $parentcontext = context::instance_by_id($ra->contextid); if ($parentcontext->contextlevel != CONTEXT_COURSECAT) { return; } // Now this is going to be a bit slow, take all enrolments in child courses and verify each separately. $syscontext = context_system::instance(); if (!($roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext))) { return; } $plugin = enrol_get_plugin('category'); $sql = "SELECT e.*\n FROM {course} c\n JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :courselevel AND ctx.path LIKE :match)\n JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'category')\n JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)"; $params = array('courselevel' => CONTEXT_COURSE, 'match' => $parentcontext->path . '/%', 'userid' => $ra->userid); $rs = $DB->get_recordset_sql($sql, $params); list($roleids, $params) = $DB->get_in_or_equal(array_keys($roles), SQL_PARAMS_NAMED, 'r'); $params['userid'] = $ra->userid; foreach ($rs as $instance) { $coursecontext = context_course::instance($instance->courseid); $contextids = $coursecontext->get_parent_context_ids(); array_pop($contextids); // Remove system context, we are interested in categories only. list($contextids, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'c'); $params = array_merge($params, $contextparams); $sql = "SELECT ra.id\n FROM {role_assignments} ra\n WHERE ra.userid = :userid AND ra.contextid {$contextids} AND ra.roleid {$roleids}"; if (!$DB->record_exists_sql($sql, $params)) { // User does not have any interesting role in any parent context, let's unenrol. $plugin->unenrol_user($instance, $ra->userid); } } $rs->close(); }
/** * Event processor - cohort member added. * @param \core\event\cohort_member_added $event * @return bool */ public static function member_added(\core\event\cohort_member_added $event) { global $DB, $CFG; require_once "{$CFG->dirroot}/group/lib.php"; if (!enrol_is_enabled('cohort')) { return true; } // Does any enabled cohort instance want to sync with this cohort? $sql = "SELECT e.*, r.id as roleexists\n FROM {enrol} e\n LEFT JOIN {role} r ON (r.id = e.roleid)\n WHERE e.customint1 = :cohortid AND e.enrol = 'cohort' AND e.status = :enrolstatus\n ORDER BY e.id ASC"; $params['cohortid'] = $event->objectid; $params['enrolstatus'] = ENROL_INSTANCE_ENABLED; if (!($instances = $DB->get_records_sql($sql, $params))) { return true; } $plugin = enrol_get_plugin('cohort'); foreach ($instances as $instance) { if ($instance->status != ENROL_INSTANCE_ENABLED) { // No roles for disabled instances. $instance->roleid = 0; } else { if ($instance->roleid and !$instance->roleexists) { // Invalid role - let's just enrol, they will have to create new sync and delete this one. $instance->roleid = 0; } } unset($instance->roleexists); // No problem if already enrolled. $plugin->enrol_user($instance, $event->relateduserid, $instance->roleid, 0, 0, ENROL_USER_ACTIVE); // Sync groups. if ($instance->customint2) { if (!groups_is_member($instance->customint2, $event->relateduserid)) { if ($group = $DB->get_record('groups', array('id' => $instance->customint2, 'courseid' => $instance->courseid))) { groups_add_member($group->id, $event->relateduserid, 'enrol_cohort', $instance->id); } } } } return true; }
require_login($course); require_capability('moodle/course:enrolreview', $context); require_sesskey(); echo $OUTPUT->header(); // send headers $manager = new course_enrolment_manager($PAGE, $course); $outcome = new stdClass(); $outcome->success = true; $outcome->response = new stdClass(); $outcome->error = ''; $searchanywhere = get_user_preferences('userselector_searchanywhere', false); switch ($action) { case 'unenrol': $ue = $DB->get_record('user_enrolments', array('id' => required_param('ue', PARAM_INT)), '*', MUST_EXIST); list($instance, $plugin) = $manager->get_user_enrolment_components($ue); if (!$instance || !$plugin || !enrol_is_enabled($instance->enrol) || !$plugin->allow_unenrol_user($instance, $ue) || !has_capability("enrol/{$instance->enrol}:unenrol", $manager->get_context()) || !$manager->unenrol_user($ue)) { throw new enrol_ajax_exception('unenrolnotpermitted'); } break; case 'unassign': $role = required_param('role', PARAM_INT); $user = required_param('user', PARAM_INT); if (!has_capability('moodle/role:assign', $manager->get_context()) || !$manager->unassign_role_from_user($user, $role)) { throw new enrol_ajax_exception('unassignnotpermitted'); } break; case 'assign': $user = $DB->get_record('user', array('id' => required_param('user', PARAM_INT)), '*', MUST_EXIST); $roleid = required_param('roleid', PARAM_INT); if (!array_key_exists($roleid, $manager->get_assignable_roles())) { throw new enrol_ajax_exception('invalidrole');
/** * Sync all meta course links. * * @param progress_trace $trace * @param int $courseid one course, empty mean all * @return int 0 means ok, 1 means error, 2 means plugin disabled */ public function sync(progress_trace $trace, $courseid = null) { global $DB; if (!enrol_is_enabled('self')) { $trace->finished(); return 2; } // Unfortunately this may take a long time, execution can be interrupted safely here. core_php_time_limit::raise(); raise_memory_limit(MEMORY_HUGE); $trace->output('Verifying self-enrolments...'); $params = array('now' => time(), 'useractive' => ENROL_USER_ACTIVE, 'courselevel' => CONTEXT_COURSE); $coursesql = ""; if ($courseid) { $coursesql = "AND e.courseid = :courseid"; $params['courseid'] = $courseid; } // Note: the logic of self enrolment guarantees that user logged in at least once (=== u.lastaccess set) // and that user accessed course at least once too (=== user_lastaccess record exists). // First deal with users that did not log in for a really long time - they do not have user_lastaccess records. $sql = "SELECT e.*, ue.userid\n FROM {user_enrolments} ue\n JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)\n JOIN {user} u ON u.id = ue.userid\n WHERE :now - u.lastaccess > e.customint2\n {$coursesql}"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $instance) { $userid = $instance->userid; unset($instance->userid); $this->unenrol_user($instance, $userid); $days = $instance->customint2 / 60 * 60 * 24; $trace->output("unenrolling user {$userid} from course {$instance->courseid} as they have did not log in for at least {$days} days", 1); } $rs->close(); // Now unenrol from course user did not visit for a long time. $sql = "SELECT e.*, ue.userid\n FROM {user_enrolments} ue\n JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)\n JOIN {user_lastaccess} ul ON (ul.userid = ue.userid AND ul.courseid = e.courseid)\n WHERE :now - ul.timeaccess > e.customint2\n {$coursesql}"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $instance) { $userid = $instance->userid; unset($instance->userid); $this->unenrol_user($instance, $userid); $days = $instance->customint2 / 60 * 60 * 24; $trace->output("unenrolling user {$userid} from course {$instance->courseid} as they have did not access course for at least {$days} days", 1); } $rs->close(); $trace->output('...user self-enrolment updates finished.'); $trace->finished(); $this->process_expirations($trace, $courseid); return 0; }
$renames = 0; $renameerrors = 0; $usersskipped = 0; $weakpasswords = 0; // caches $ccache = array(); // course cache - do not fetch all courses here, we will not probably use them all anyway! $cohorts = array(); $rolecache = uu_allowed_roles_cache(); // roles lookup cache $manualcache = array(); // cache of used manual enrol plugins in each course $supportedauths = uu_supported_auths(); // officially supported plugins that are enabled // we use only manual enrol plugin here, if it is disabled no enrol is done if (enrol_is_enabled('manual')) { $manual = enrol_get_plugin('manual'); } else { $manual = NULL; } // clear bulk selection if ($bulk) { $SESSION->bulk_users = array(); } // init csv import helper $cir->init(); $linenum = 1; //column header is first line // init upload progress tracker $upt = new uu_progress_tracker(); $upt->start();
$toolid = null; $token = null; $filearguments = get_file_argument(); $arguments = explode('/', trim($filearguments, '/')); if (count($arguments) >= 2) { // Can put cartridge.xml at the end, or anything really. list($toolid, $token) = $arguments; } $toolid = optional_param('id', $toolid, PARAM_INT); $token = optional_param('token', $token, PARAM_ALPHANUM); // Only show the cartridge if the token parameter is correct. // If we do not compare with a shared secret, someone could very easily // guess an id for the enrolment. if (!\enrol_lti\helper::verify_tool_token($toolid, $token)) { throw new \moodle_exception('incorrecttoken', 'enrol_lti'); } $tool = \enrol_lti\helper::get_lti_tool($toolid); if (!is_enabled_auth('lti')) { print_error('pluginnotenabled', 'auth', '', get_string('pluginname', 'auth_lti')); } else { if (!enrol_is_enabled('lti')) { print_error('enrolisdisabled', 'enrol_lti'); } else { if ($tool->status != ENROL_INSTANCE_ENABLED) { print_error('enrolisdisabled', 'enrol_lti'); } else { header('Content-Type: text/xml; charset=utf-8'); echo \enrol_lti\helper::create_cartridge($toolid); } } }
require '../config.php'; require_once "{$CFG->dirroot}/enrol/locallib.php"; require_once "{$CFG->dirroot}/enrol/renderer.php"; $ueid = required_param('ue', PARAM_INT); // user enrolment id $confirm = optional_param('confirm', false, PARAM_BOOL); $filter = optional_param('ifilter', 0, PARAM_INT); $ue = $DB->get_record('user_enrolments', array('id' => $ueid), '*', MUST_EXIST); $user = $DB->get_record('user', array('id' => $ue->userid), '*', MUST_EXIST); $instance = $DB->get_record('enrol', array('id' => $ue->enrolid), '*', MUST_EXIST); $course = $DB->get_record('course', array('id' => $instance->courseid), '*', MUST_EXIST); $context = context_course::instance($course->id); // set up PAGE url first! $PAGE->set_url('/enrol/unenroluser.php', array('ue' => $ueid, 'ifilter' => $filter)); require_login($course); if (!enrol_is_enabled($instance->enrol)) { print_error('erroreditenrolment', 'enrol'); } $plugin = enrol_get_plugin($instance->enrol); if (!$plugin->allow_unenrol_user($instance, $ue) or !has_capability("enrol/{$instance->enrol}:unenrol", $context)) { print_error('erroreditenrolment', 'enrol'); } $manager = new course_enrolment_manager($PAGE, $course, $filter); $table = new course_enrolment_users_table($manager, $PAGE); $returnurl = new moodle_url('/enrol/users.php', array('id' => $course->id) + $manager->get_url_params() + $table->get_url_params()); $usersurl = new moodle_url('/enrol/users.php', array('id' => $course->id)); $PAGE->set_pagelayout('admin'); navigation_node::override_active_url($usersurl); // If the unenrolment has been confirmed and the sesskey is valid unenrol the user. if ($confirm && confirm_sesskey()) { $plugin->unenrol_user($instance, $ue->userid);
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); }
/** * Sync all meta course links. * * @param progress_trace $trace * @param int $courseid one course, empty mean all * @return int 0 means ok, 1 means error, 2 means plugin disabled */ public function sync(progress_trace $trace, $courseid = null) { global $DB; if (!enrol_is_enabled('manual')) { $trace->finished(); return 2; } // Unfortunately this may take a long time, execution can be interrupted safely here. @set_time_limit(0); raise_memory_limit(MEMORY_HUGE); $trace->output('Verifying manual enrolment expiration...'); $params = array('now' => time(), 'useractive' => ENROL_USER_ACTIVE, 'courselevel' => CONTEXT_COURSE); $coursesql = ""; if ($courseid) { $coursesql = "AND e.courseid = :courseid"; $params['courseid'] = $courseid; } // Deal with expired accounts. $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP); if ($action == ENROL_EXT_REMOVED_UNENROL) { $instances = array(); $sql = "SELECT ue.*, e.courseid, c.id AS contextid\n FROM {user_enrolments} ue\n JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'manual')\n JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)\n WHERE ue.timeend > 0 AND ue.timeend < :now\n {$coursesql}"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $ue) { if (empty($instances[$ue->enrolid])) { $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid)); } $instance = $instances[$ue->enrolid]; // Always remove all manually assigned roles here, this may break enrol_self roles but we do not want hardcoded hacks here. role_unassign_all(array('userid' => $ue->userid, 'contextid' => $ue->contextid, 'component' => '', 'itemid' => 0), true); $this->unenrol_user($instance, $ue->userid); $trace->output("unenrolling expired user {$ue->userid} from course {$instance->courseid}", 1); } $rs->close(); unset($instances); } else { if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) { $instances = array(); $sql = "SELECT ue.*, e.courseid, c.id AS contextid\n FROM {user_enrolments} ue\n JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'manual')\n JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)\n WHERE ue.timeend > 0 AND ue.timeend < :now\n AND ue.status = :useractive\n {$coursesql}"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $ue) { if (empty($instances[$ue->enrolid])) { $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid)); } $instance = $instances[$ue->enrolid]; // Always remove all manually assigned roles here, this may break enrol_self roles but we do not want hardcoded hacks here. role_unassign_all(array('userid' => $ue->userid, 'contextid' => $ue->contextid, 'component' => '', 'itemid' => 0), true); $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED); $trace->output("suspending expired user {$ue->userid} in course {$instance->courseid}", 1); } $rs->close(); unset($instances); } else { // ENROL_EXT_REMOVED_KEEP means no changes. } } $trace->output('...manual enrolment updates finished.'); $trace->finished(); return 0; }
/** * Remove all role assignments in the specified course for the specified account * id for the user whose id information is passed in the line data. * * @access public * @static * @param stdClass $course Course in which to remove the role assignment * @param string $ident_field The field (column) name in Moodle user rec against which to query using the imported data * @param stored_file $import_file File in local repository from which to get enrollment and group data * @return string String message with results * * @uses $DB */ public static function unenroll_file(stdClass $course, $ident_field, stored_file $import_file) { global $DB; // Default return value $result = ''; // Need one of these in the loop $course_context = context_course::instance($course->id); // Choose the regex pattern based on the $ident_field switch ($ident_field) { case 'email': $regex_pattern = '/^"?\\s*([a-z0-9][\\w.%-]*@[a-z0-9][a-z0-9.-]{0,61}[a-z0-9]\\.[a-z]{2,6})\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui'; break; case 'idnumber': $regex_pattern = '/^"?\\s*(\\d{1,32})\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui'; break; default: $regex_pattern = '/^"?\\s*([a-z0-9][\\w@.-]*)\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui'; break; } $user_rec = null; // Open and fetch the file contents $fh = $import_file->get_content_file_handle(); $line_num = 0; while (false !== ($line = fgets($fh))) { $line_num++; // Clean these up for each iteration unset($user_rec); if (!($line = trim($line))) { continue; } // Parse the line, from which we may get one or two // matches since the group name is an optional item // on a line by line basis if (!preg_match($regex_pattern, $line, $matches)) { $result .= sprintf(get_string('ERR_PATTERN_MATCH', self::PLUGIN_NAME), $line_num, $line); continue; } $ident_value = $matches[1]; // User must already exist, we import enrollments // into courses, not users into the system. Exclude // records marked as deleted. Because idnumber is // not enforced unique, possible multiple records // returned when using that identifying field, so // use ->get_records method to make that detection // and inform user $user_rec_array = $DB->get_records('user', array($ident_field => addslashes($ident_value), 'deleted' => 0)); // Should have one and only one record, otherwise // report it and move on to the next $user_rec_count = count($user_rec_array); if ($user_rec_count == 0) { // No record found $result .= sprintf(get_string('ERR_USERID_INVALID', self::PLUGIN_NAME), $line_num, $ident_value); continue; } elseif ($user_rec_count > 1) { // Too many records $result .= sprintf(get_string('ERR_USER_MULTIPLE_RECS', self::PLUGIN_NAME), $line_num, $ident_value); continue; } $user_rec = array_shift($user_rec_array); // Fetch all the role assignments this user might have for this course's context. $sql = 'SELECT ue.id, ue.status, ue.enrolid FROM {user_enrolments} ue JOIN {enrol} e ON e.id = ue.enrolid AND e.courseid=:courseid WHERE ue.userid=:userid'; $params = array("courseid" => $course->id, "userid" => $user_rec->id); $user_enrollments = $DB->get_records_sql($sql, $params); if ($user_enrollments) { foreach ($user_enrollments as $ue) { $instance = $DB->get_record('enrol', array('id' => $ue->enrolid), '*', MUST_EXIST); if ($instance->enrol == "meta") { $result .= sprintf(get_string('ERR_UNENROLL_META', self::PLUGIN_NAME), $line_num, $ident_value); } else { try { if (!enrol_is_enabled($instance->enrol)) { print_error('erroreditenrolment', 'enrol'); } $plugin = enrol_get_plugin($instance->enrol); if (!$plugin->allow_unenrol_user($instance, $ue) || !has_capability("enrol/{$instance->enrol}:unenrol", $course_context)) { print_error('erroreditenrolment', 'enrol'); } $plugin->unenrol_user($instance, $user_rec->id); } catch (Exception $exc) { $result .= sprintf(get_string('ERR_UNENROLL_FAILED', self::PLUGIN_NAME), $line_num, $ident_value); $result .= $exc->getMessage(); continue; } } } } } // while fgets fclose($fh); return empty($result) ? get_string('INF_UNENROLL_SUCCESS', self::PLUGIN_NAME) : $result; }
/** * Is course creator going to have capability in a new course? * * This is intended to be used in enrolment plugins before or during course creation, * do not use after the course is fully created. * * @category access * * @param string $capability the name of the capability to check. * @param context $context course or category context where is course going to be created * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user. * @return boolean true if the user will have this capability. * * @throws coding_exception if different type of context submitted */ function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) { global $CFG; if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) { throw new coding_exception('Only course or course category context expected'); } if (has_capability($capability, $context, $user)) { // User already has the capability, it could be only removed if CAP_PROHIBIT // was involved here, but we ignore that. return true; } if (!has_capability('moodle/course:create', $context, $user)) { return false; } if (!enrol_is_enabled('manual')) { return false; } if (empty($CFG->creatornewroleid)) { return false; } if ($context->contextlevel == CONTEXT_COURSE) { if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) { return false; } } else { if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) { return false; } } // Most likely they will be enrolled after the course creation is finished, // does the new role have the required capability? list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability); return isset($neededroles[$CFG->creatornewroleid]); }
/** * Create enrolment instances. * * This has to be called after creation of roles * and before adding of role assignments. * * @param mixed $data * @return void */ public function process_enrol($data) { global $DB; $data = (object)$data; $oldid = $data->id; // We'll need this later $restoretype = plugin_supports('enrol', $data->enrol, ENROL_RESTORE_TYPE, null); if ($restoretype !== ENROL_RESTORE_EXACT and $restoretype !== ENROL_RESTORE_NOUSERS) { // TODO: add complex restore support via custom class debugging("Skipping '{$data->enrol}' enrolment plugin. Will be implemented before 2.0 release", DEBUG_DEVELOPER); $this->set_mapping('enrol', $oldid, 0); return; } // Perform various checks to decide what to do with the enrol plugin if (!array_key_exists($data->enrol, enrol_get_plugins(false))) { // TODO: decide if we want to switch to manual enrol - we need UI for this debugging("Enrol plugin data can not be restored because it is not installed"); $this->set_mapping('enrol', $oldid, 0); return; } if (!enrol_is_enabled($data->enrol)) { // TODO: decide if we want to switch to manual enrol - we need UI for this debugging("Enrol plugin data can not be restored because it is not enabled"); $this->set_mapping('enrol', $oldid, 0); return; } // map standard fields - plugin has to process custom fields from own restore class $data->roleid = $this->get_mappingid('role', $data->roleid); //TODO: should we move the enrol start and end date here? // always add instance, if the course does not support multiple instances it just returns NULL $enrol = enrol_get_plugin($data->enrol); $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!! if ($newitemid = $enrol->add_instance($courserec, (array)$data)) { // ok } else { if ($instances = $DB->get_records('enrol', array('courseid'=>$courserec->id, 'enrol'=>$data->enrol))) { // most probably plugin that supports only one instance $newitemid = key($instances); } else { debugging('Can not create new enrol instance or reuse existing'); $newitemid = 0; } } if ($restoretype === ENROL_RESTORE_NOUSERS) { // plugin requests to prevent restore of any users $newitemid = 0; } $this->set_mapping('enrol', $oldid, $newitemid); }
/** * Constructs the table * * @param course_enrolment_manager $manager */ public function __construct(course_enrolment_manager $manager) { $this->manager = $manager; $this->page = optional_param(self::PAGEVAR, 0, PARAM_INT); $this->perpage = optional_param(self::PERPAGEVAR, self::DEFAULTPERPAGE, PARAM_INT); $this->sort = optional_param(self::SORTVAR, self::DEFAULTSORT, PARAM_ALPHANUM); $this->sortdirection = optional_param(self::SORTDIRECTIONVAR, self::DEFAULTSORTDIRECTION, PARAM_ALPHA); $this->attributes = array('class' => 'userenrolment'); if (!in_array($this->sort, self::$sortablefields)) { $this->sort = self::DEFAULTSORT; } if ($this->page < 0) { $this->page = 0; } if ($this->sortdirection !== 'ASC' && $this->sortdirection !== 'DESC') { $this->sortdirection = self::DEFAULTSORTDIRECTION; } $this->id = html_writer::random_id(); // Collect the bulk operations for the currently filtered plugin if there is one. $plugin = $manager->get_filtered_enrolment_plugin(); if ($plugin and enrol_is_enabled($plugin->get_name())) { $this->bulkoperations = $plugin->get_bulk_operations($manager); } }