Is there a way to programmatically enable an enrolment plugin?
Or is it as simple as adding a record to mdl_enrol with the necessary data for the plugin? For some reason I don't trust this way of going about it.
This is how it should be done:
function enable_enrol_plugin($plugin) {
if (!enrol_is_enabled($plugin)) {
set_config('enrol_plugins_enabled', get_config('core', 'enrol_plugins_enabled').','.$plugin);
core_plugin_manager::reset_caches();
context_system::instance()->mark_dirty();
}
}
Slightly improved
function enable_enrol_plugin($plugin) {
if (!enrol_is_enabled($plugin)) {
$updated = $plugin;
$current = get_config('core', 'enrol_plugins_enabled');
if (!empty($current)) {
$updated = $current.','.$plugin;
}
set_config('enrol_plugins_enabled', $updated);
core_plugin_manager::reset_caches();
context_system::instance()->mark_dirty();
}
}
Thanks for this.
Unfortunately my question wasn't clear enough though.
I'm actually looking to enable the plugin programmatically on the course level.
OK, here goes:
/**
* @param string $plugin
* @param object $course
* @return mixed|null
* @throws coding_exception
*/
function add_enrol_instance($plugin, $course) {
global $DB;
$inst = null;
$enrol = enrol_get_plugin($plugin);
if (!empty($enrol)) {
$inst = null;
$instances = enrol_get_instances($course->id, false);
foreach ($instances as $instance) {
if ($instance->enrol == $plugin) {
$inst = $instance;
break;
}
}
if ($inst === null) {
$instid = $enrol->add_default_instance($course);
if ($instid === null) {
$instid = $enrol->add_instance($course);
}
$inst = $DB->get_record('enrol', array('id' => $instid));
}
}
return $inst;
}