MDL-30945 add support for unenrolling of individual users + code cleanup
[moodle.git] / lib / completion / cron.php
blob281a9d76d25a6ff382945a9e481dc8316df13685
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 /**
20 * Cron job for reviewing and aggregating course completion criteria
22 * @package moodlecore
23 * @copyright 2009 Catalyst IT Ltd
24 * @author Aaron Barnes <aaronb@catalyst.net.nz>
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 require_once $CFG->libdir.'/completionlib.php';
30 /**
31 * Update user's course completion statuses
33 * First update all criteria completions, then
34 * aggregate all criteria completions and update
35 * overall course completions
37 * @return void
39 function completion_cron() {
41 completion_cron_mark_started();
43 completion_cron_criteria();
45 completion_cron_completions();
48 /**
49 * Mark users as started if the config option is set
51 * @return void
53 function completion_cron_mark_started() {
54 global $CFG, $DB;
56 if (debugging()) {
57 mtrace('Marking users as started');
60 if (!empty($CFG->gradebookroles)) {
61 $roles = ' AND ra.roleid IN ('.$CFG->gradebookroles.')';
62 } else {
63 // This causes it to default to everyone (if there is no student role)
64 $roles = '';
67 /**
68 * A quick explaination of this horrible looking query
70 * It's purpose is to locate all the active participants
71 * of a course with course completion enabled.
73 * We also only want the users with no course_completions
74 * record as this functions job is to create the missing
75 * ones :)
77 * We want to record the user's enrolment start time for the
78 * course. This gets tricky because there can be multiple
79 * enrolment plugins active in a course, hence the possibility
80 * of multiple records for each couse/user in the results
82 $sql = "
83 SELECT
84 c.id AS course,
85 u.id AS userid,
86 crc.id AS completionid,
87 ue.timestart AS timeenrolled,
88 ue.timecreated
89 FROM
90 {user} u
91 INNER JOIN
92 {user_enrolments} ue
93 ON ue.userid = u.id
94 INNER JOIN
95 {enrol} e
96 ON e.id = ue.enrolid
97 INNER JOIN
98 {course} c
99 ON c.id = e.courseid
100 INNER JOIN
101 {role_assignments} ra
102 ON ra.userid = u.id
103 LEFT JOIN
104 {course_completions} crc
105 ON crc.course = c.id
106 AND crc.userid = u.id
107 WHERE
108 c.enablecompletion = 1
109 AND crc.timeenrolled IS NULL
110 AND ue.status = 0
111 AND e.status = 0
112 AND u.deleted = 0
113 AND ue.timestart < ?
114 AND (ue.timeend > ? OR ue.timeend = 0)
115 $roles
116 ORDER BY
117 course,
118 userid
121 $now = time();
122 $rs = $DB->get_recordset_sql($sql, array($now, $now, $now, $now));
124 // Check if result is empty
125 if (!$rs->valid()) {
126 $rs->close(); // Not going to iterate (but exit), close rs
127 return;
131 * An explaination of the following loop
133 * We are essentially doing a group by in the code here (as I can't find
134 * a decent way of doing it in the sql).
136 * Since there can be multiple enrolment plugins for each course, we can have
137 * multiple rows for each particpant in the query result. This isn't really
138 * a problem until you combine it with the fact that the enrolment plugins
139 * can save the enrol start time in either timestart or timeenrolled.
141 * The purpose of this loop is to find the earliest enrolment start time for
142 * each participant in each course.
144 $prev = null;
145 while ($rs->valid() || $prev) {
147 $current = $rs->current();
149 if (!isset($current->course)) {
150 $current = false;
152 else {
153 // Not all enrol plugins fill out timestart correctly, so use whichever
154 // is non-zero
155 $current->timeenrolled = max($current->timecreated, $current->timeenrolled);
158 // If we are at the last record,
159 // or we aren't at the first and the record is for a diff user/course
160 if ($prev &&
161 (!$rs->valid() ||
162 ($current->course != $prev->course || $current->userid != $prev->userid))) {
164 $completion = new completion_completion();
165 $completion->userid = $prev->userid;
166 $completion->course = $prev->course;
167 $completion->timeenrolled = (string) $prev->timeenrolled;
168 $completion->timestarted = 0;
169 $completion->reaggregate = time();
171 if ($prev->completionid) {
172 $completion->id = $prev->completionid;
175 $completion->mark_enrolled();
177 if (debugging()) {
178 mtrace('Marked started user '.$prev->userid.' in course '.$prev->course);
181 // Else, if this record is for the same user/course
182 elseif ($prev && $current) {
183 // Use oldest timeenrolled
184 $current->timeenrolled = min($current->timeenrolled, $prev->timeenrolled);
187 // Move current record to previous
188 $prev = $current;
190 // Move to next record
191 $rs->next();
194 $rs->close();
198 * Run installed criteria's data aggregation methods
200 * Loop through each installed criteria and run the
201 * cron() method if it exists
203 * @return void
205 function completion_cron_criteria() {
207 // Process each criteria type
208 global $CFG, $COMPLETION_CRITERIA_TYPES;
210 foreach ($COMPLETION_CRITERIA_TYPES as $type) {
212 $object = 'completion_criteria_'.$type;
213 require_once $CFG->libdir.'/completion/'.$object.'.php';
215 $class = new $object();
217 // Run the criteria type's cron method, if it has one
218 if (method_exists($class, 'cron')) {
220 if (debugging()) {
221 mtrace('Running '.$object.'->cron()');
223 $class->cron();
229 * Aggregate each user's criteria completions
231 * @return void
233 function completion_cron_completions() {
234 global $DB;
236 if (debugging()) {
237 mtrace('Aggregating completions');
240 // Save time started
241 $timestarted = time();
243 // Grab all criteria and their associated criteria completions
244 $sql = '
245 SELECT DISTINCT
246 c.id AS course,
247 cr.id AS criteriaid,
248 crc.userid AS userid,
249 cr.criteriatype AS criteriatype,
250 cc.timecompleted AS timecompleted
251 FROM
252 {course_completion_criteria} cr
253 INNER JOIN
254 {course} c
255 ON cr.course = c.id
256 INNER JOIN
257 {course_completions} crc
258 ON crc.course = c.id
259 LEFT JOIN
260 {course_completion_crit_compl} cc
261 ON cc.criteriaid = cr.id
262 AND crc.userid = cc.userid
263 WHERE
264 c.enablecompletion = 1
265 AND crc.timecompleted IS NULL
266 AND crc.reaggregate > 0
267 AND crc.reaggregate < :timestarted
268 ORDER BY
269 course,
270 userid
273 $rs = $DB->get_recordset_sql($sql, array('timestarted' => $timestarted));
275 // Check if result is empty
276 if (!$rs->valid()) {
277 $rs->close(); // Not going to iterate (but exit), close rs
278 return;
281 $current_user = null;
282 $current_course = null;
283 $completions = array();
285 while (1) {
287 // Grab records for current user/course
288 foreach ($rs as $record) {
289 // If we are still grabbing the same users completions
290 if ($record->userid === $current_user && $record->course === $current_course) {
291 $completions[$record->criteriaid] = $record;
292 } else {
293 break;
297 // Aggregate
298 if (!empty($completions)) {
300 if (debugging()) {
301 mtrace('Aggregating completions for user '.$current_user.' in course '.$current_course);
304 // Get course info object
305 $info = new completion_info((object)array('id' => $current_course));
307 // Setup aggregation
308 $overall = $info->get_aggregation_method();
309 $activity = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ACTIVITY);
310 $prerequisite = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_COURSE);
311 $role = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ROLE);
313 $overall_status = null;
314 $activity_status = null;
315 $prerequisite_status = null;
316 $role_status = null;
318 // Get latest timecompleted
319 $timecompleted = null;
321 // Check each of the criteria
322 foreach ($completions as $params) {
323 $timecompleted = max($timecompleted, $params->timecompleted);
325 $completion = new completion_criteria_completion($params, false);
327 // Handle aggregation special cases
328 if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) {
329 completion_cron_aggregate($activity, $completion->is_complete(), $activity_status);
330 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) {
331 completion_cron_aggregate($prerequisite, $completion->is_complete(), $prerequisite_status);
332 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ROLE) {
333 completion_cron_aggregate($role, $completion->is_complete(), $role_status);
334 } else {
335 completion_cron_aggregate($overall, $completion->is_complete(), $overall_status);
339 // Include role criteria aggregation in overall aggregation
340 if ($role_status !== null) {
341 completion_cron_aggregate($overall, $role_status, $overall_status);
344 // Include activity criteria aggregation in overall aggregation
345 if ($activity_status !== null) {
346 completion_cron_aggregate($overall, $activity_status, $overall_status);
349 // Include prerequisite criteria aggregation in overall aggregation
350 if ($prerequisite_status !== null) {
351 completion_cron_aggregate($overall, $prerequisite_status, $overall_status);
354 // If aggregation status is true, mark course complete for user
355 if ($overall_status) {
356 if (debugging()) {
357 mtrace('Marking complete');
360 $ccompletion = new completion_completion(array('course' => $params->course, 'userid' => $params->userid));
361 $ccompletion->mark_complete($timecompleted);
365 // If this is the end of the recordset, break the loop
366 if (!$rs->valid()) {
367 $rs->close();
368 break;
371 // New/next user, update user details, reset completions
372 $current_user = $record->userid;
373 $current_course = $record->course;
374 $completions = array();
375 $completions[$record->criteriaid] = $record;
378 // Mark all users as aggregated
379 $sql = "
380 UPDATE
381 {course_completions}
383 reaggregate = 0
384 WHERE
385 reaggregate < {$timestarted}
388 $DB->execute($sql);
392 * Aggregate criteria status's as per configured aggregation method
394 * @param int $method COMPLETION_AGGREGATION_* constant
395 * @param bool $data Criteria completion status
396 * @param bool|null $state Aggregation state
397 * @return void
399 function completion_cron_aggregate($method, $data, &$state) {
400 if ($method == COMPLETION_AGGREGATION_ALL) {
401 if ($data && $state !== false) {
402 $state = true;
403 } else {
404 $state = false;
406 } elseif ($method == COMPLETION_AGGREGATION_ANY) {
407 if ($data) {
408 $state = true;
409 } else if (!$data && $state === null) {
410 $state = false;