- // Grab records for current user/course
- foreach ($rs as $record) {
- $completion = new completion_completion();
- $completion->userid = $record->userid;
- $completion->course = $record->course;
- $completion->timeenrolled = $record->timestarted;
-
- if ($record->completionid) {
- $completion->id = $record->completionid;
+ /**
+ * An explaination of the following loop
+ *
+ * We are essentially doing a group by in the code here (as I can't find
+ * a decent way of doing it in the sql).
+ *
+ * Since there can be multiple enrolment plugins for each course, we can have
+ * multiple rows for each particpant in the query result. This isn't really
+ * a problem until you combine it with the fact that the enrolment plugins
+ * can save the enrol start time in either timestart or timeenrolled.
+ *
+ * The purpose of this loop is to find the earliest enrolment start time for
+ * each participant in each course.
+ */
+ $prev = null;
+ while ($rs->valid() || $prev) {
+
+ $current = $rs->current();
+
+ if (!isset($current->course)) {
+ $current = false;
+ }
+ else {
+ // Not all enrol plugins fill out timestart correctly, so use whichever
+ // is non-zero
+ $current->timeenrolled = max($current->timestart, $current->timeenrolled);