moodle-local_replication/unenroll.php
Kumi f9ed77bcde
feat(replication): enhance course and category management
Implement enhanced category and course replication, improving the handling of both by ensuring new and existing categories are processed correctly. Introduce CLI support for bulk category imports using a dedicated flag and provide helper functions like `generateRandomString` and `removePath` for file management. Add a new `trigger_all.php` script to trigger replication for all courses and an `unenroll.php` script for unenrolling users with cleanup of related data.

Includes error handling improvements and directory structure checks.
2024-09-09 14:55:36 +02:00

75 lines
2.1 KiB
PHP

<?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.");