+ public static function update_end_date($courseid) {
+ global $DB, $COURSE;
+
+ // Use one DB query to retrieve necessary fields in course, value for automaticenddate and number of the last
+ // section. This query will also validate that the course is indeed in 'weeks' format.
+ $sql = "SELECT c.id, c.format, c.startdate, c.enddate, fo.value AS automaticenddate, MAX(s.section) AS lastsection
+ FROM {course} c
+ LEFT JOIN {course_format_options} fo
+ ON fo.courseid = c.id
+ AND fo.format = c.format
+ AND fo.name = :optionname
+ AND fo.sectionid = 0
+ LEFT JOIN {course_sections} s
+ ON s.course = c.id
+ WHERE c.format = :format
+ AND c.id = :courseid
+ GROUP BY c.id, c.format, c.startdate, c.enddate, fo.value";
+ $course = $DB->get_record_sql($sql,
+ ['optionname' => 'automaticenddate', 'format' => 'weeks', 'courseid' => $courseid]);
+
+ if (!$course) {
+ // Looks like it is a course in a different format, nothing to do here.
+ return;
+ }