The below function will replace the current function in enrol.php in the enrol\database folder.
This solution will not remove manually enrolled courses from the database enrolment method.
The function also includes an example how to manually map a course globally, useful for courses that are not held on your MIS system, i.e. A Generic Induction Course.
I am new to Moodle and php, but don't be surprised to see some more posts during the next few months.
We have this function working on Moodle 1.5.2 at Swansea College.
function get_student_courses(&$user) {
global $CFG;
parent::get_student_courses($user);
if (strpos($CFG->prefix, $CFG->dbname) === false) {
$oldprefix = $CFG->prefix;
$CFG->prefix = "$CFG->dbname.$CFG->prefix";
}
// Try to connect to the external database
$enroldb = &ADONewConnection($CFG->enrol_dbtype);
if ($enroldb->PConnect($CFG->enrol_dbhost,$CFG->enrol_dbuser,$CFG->enrol_dbpass,$CFG->enrol_dbname)) {
$courselist = array(); /// Initialise new array
$newstudent = array();
/// Get the authoritative list of enrolments from the database
$useridnumber = $user->{$CFG->enrol_localuserfield};
if ($rs = $enroldb->Execute("SELECT $CFG->enrol_remotecoursefield
FROM $CFG->enrol_dbtable
WHERE $CFG->enrol_remoteuserfield = '$useridnumber' ")) {
if ($rs->RecordCount() > 0) {
while (!$rs->EOF) {
$courselist[] = $rs->fields[0];
$rs->MoveNext();
}
foreach ($courselist as $coursefield) {
if ($course = get_record('course', $CFG->enrol_localcoursefield, $coursefield)) {
$newstudent[$course->id] = true; /// Add it to new list
if (isset($user->student[$course->id])) { /// We have it already
unset($user->student[$course->id]); /// Remove from old list
} else {
enrol_student($user->id, $course->id); /// Enrol the student
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
// Code snippet added in by C.Simpson 12th August 2005
// Snippet refreshes current courses attached to students
// This gets around the issue of manually enrolled courses being removed on logging in
/////////////////////////////////////////////////////////////////////////////////////////////
// Add your global manual enrolments here
// newstudent[courseid] = true;
// enrol_student($user->id,courseid);
// *** Just alter the courseid for each entry
// Code snippet added by C.Simpson 15th August 2005
//Modified code to re-enrol students on courses
if (!empty($user->student)) { /// We have courses left that we do not want to unenrol from
foreach ($user->student as $courseid => $value) {
$newstudent[$courseid] = true;
enrol_student($user->id,$courseid);
}
}
$user->student = $newstudent; /// Overwrite the array with the new one
}
$enroldb->Close();
}
if (!empty($oldprefix)) {
$CFG->prefix = $oldprefix; // Restore it just in case
}
}