moodle-local_replication/unenroll.php

76 lines
2.1 KiB
PHP
Raw Permalink Normal View History

<?php
define('CLI_SCRIPT', true);
require(__DIR__ . '/../../config.php');
require_once($CFG->libdir . '/clilib.php');
require_once($CFG->libdir . '/enrollib.php');
require_once($CFG->libdir . '/completionlib.php');
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
$usage = "Usage:
unenroll.php --username=<username> --shortname=<shortname>
Options:
--username The username of the user to unenroll.
--shortname The shortname of the course to unenroll the user from.
";
list($options, $unrecognized) = cli_get_params(
[
'username' => null,
'shortname' => null,
'help' => false,
],
['h' => 'help']
);
if ($options['help'] || !$options['username'] || !$options['shortname']) {
echo $usage;
exit(0);
}
$username = $options['username'];
$shortname = $options['shortname'];
try {
$user = $DB->get_record('user', array('username' => $username), '*', MUST_EXIST);
} catch (Exception $ex) {
cli_error('User ' . $username . ' does not exist.');
}
try {
$course = $DB->get_record('course', array('shortname' => $shortname), '*', MUST_EXIST);
} catch (Exception $ex) {
cli_error('Course ' . $shortname . ' does not exist.');
}
$context = context_course::instance($course->id);
$courseid = $course->id;
$userid = $user->id;
$context = context_course::instance($courseid);
$enrolinstances = enrol_get_instances($courseid, true);
$enrolplugin = enrol_get_plugin('manual');
$manualinstance = null;
foreach ($enrolinstances as $instance) {
if ($instance->enrol == 'manual') {
$manualinstance = $instance;
break;
}
}
if ($manualinstance === null) {
cli_error('No manual enrollment instance found for the course.');
}
$enrolplugin->unenrol_user($manualinstance, $userid);
$DB->delete_records('course_completions', ['userid' => $userid, 'course' => $courseid]);
$DB->delete_records('course_completion_crit_compl', ['userid' => $userid, 'course' => $courseid]);
backup_plan_builder::delete_course_userdata($userid, $courseid);
cli_writeln("User '{$username}' has been unenrolled from course '{$shortname}' and their completion data has been removed.");