MDL-50287 completion: Separated slow task out from cron
[moodle.git] / completion / cron.php
CommitLineData
2be4d090 1<?php
2be4d090
MD
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
2be4d090
MD
17/**
18 * Cron job for reviewing and aggregating course completion criteria
19 *
836375ec
SH
20 * @package core_completion
21 * @category completion
2be4d090 22 * @copyright 2009 Catalyst IT Ltd
836375ec
SH
23 * @author Aaron Barnes <aaronb@catalyst.net.nz>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2be4d090 25 */
2be4d090 26
836375ec 27defined('MOODLE_INTERNAL') || die();
f55ff38a 28require_once($CFG->libdir.'/completionlib.php');
2be4d090
MD
29
30/**
51e488ea 31 * Legacy - here for plugin use only, not used in scheduled tasks.
2be4d090
MD
32 * Update user's course completion statuses
33 *
836375ec 34 * First update all criteria completions, then aggregate all criteria completions
51e488ea 35 * and update overall course completions.
2be4d090
MD
36 */
37function completion_cron() {
2be4d090
MD
38 completion_cron_mark_started();
39
40 completion_cron_criteria();
41
42 completion_cron_completions();
43}
51e488ea
JW
44/**
45 * Update user's course completion statuses
46 *
47 * First update all criteria completions, then aggregate all criteria completions
48 * and update overall course completions
49 */
50function completion_regular_cron() {
51 // Two Functions which check criteria and learner completions regularly for accurate data.
52 completion_cron_criteria();
53 completion_cron_completions();
54}
55/**
56 * Marks users as started if the config option is set.
57 *
58 * One function which takes a long time 60+ minutes to enrol users onto completion started.
59 */
60function completion_daily_cron() {
61 completion_cron_mark_started();
62}
2be4d090
MD
63/**
64 * Mark users as started if the config option is set
65 *
836375ec 66 * @return void
2be4d090
MD
67 */
68function completion_cron_mark_started() {
926f5143 69 global $CFG, $DB;
2be4d090
MD
70
71 if (debugging()) {
72 mtrace('Marking users as started');
73 }
74
926f5143
DP
75 if (!empty($CFG->gradebookroles)) {
76 $roles = ' AND ra.roleid IN ('.$CFG->gradebookroles.')';
77 } else {
78 // This causes it to default to everyone (if there is no student role)
79 $roles = '';
80 }
81
89482538
AB
82 /**
83 * A quick explaination of this horrible looking query
84 *
85 * It's purpose is to locate all the active participants
86 * of a course with course completion enabled.
87 *
88 * We also only want the users with no course_completions
89 * record as this functions job is to create the missing
90 * ones :)
91 *
92 * We want to record the user's enrolment start time for the
93 * course. This gets tricky because there can be multiple
94 * enrolment plugins active in a course, hence the possibility
95 * of multiple records for each couse/user in the results
96 */
2be4d090 97 $sql = "
89482538 98 SELECT
2be4d090 99 c.id AS course,
926f5143
DP
100 u.id AS userid,
101 crc.id AS completionid,
102 ue.timestart AS timeenrolled,
103 ue.timecreated
2be4d090 104 FROM
926f5143
DP
105 {user} u
106 INNER JOIN
89482538 107 {user_enrolments} ue
926f5143 108 ON ue.userid = u.id
2be4d090 109 INNER JOIN
89482538
AB
110 {enrol} e
111 ON e.id = ue.enrolid
2be4d090 112 INNER JOIN
89482538
AB
113 {course} c
114 ON c.id = e.courseid
926f5143
DP
115 INNER JOIN
116 {role_assignments} ra
117 ON ra.userid = u.id
2be4d090
MD
118 LEFT JOIN
119 {course_completions} crc
120 ON crc.course = c.id
926f5143 121 AND crc.userid = u.id
2be4d090 122 WHERE
89482538 123 c.enablecompletion = 1
926f5143
DP
124 AND crc.timeenrolled IS NULL
125 AND ue.status = 0
126 AND e.status = 0
127 AND u.deleted = 0
89482538
AB
128 AND ue.timestart < ?
129 AND (ue.timeend > ? OR ue.timeend = 0)
926f5143
DP
130 $roles
131 ORDER BY
132 course,
133 userid
2be4d090
MD
134 ";
135
89482538 136 $now = time();
926f5143
DP
137 $rs = $DB->get_recordset_sql($sql, array($now, $now, $now, $now));
138
139 // Check if result is empty
140 if (!$rs->valid()) {
141 $rs->close(); // Not going to iterate (but exit), close rs
142 return;
143 }
144
145 /**
146 * An explaination of the following loop
147 *
148 * We are essentially doing a group by in the code here (as I can't find
149 * a decent way of doing it in the sql).
150 *
151 * Since there can be multiple enrolment plugins for each course, we can have
152 * multiple rows for each particpant in the query result. This isn't really
153 * a problem until you combine it with the fact that the enrolment plugins
154 * can save the enrol start time in either timestart or timeenrolled.
155 *
156 * The purpose of this loop is to find the earliest enrolment start time for
157 * each participant in each course.
158 */
159 $prev = null;
160 while ($rs->valid() || $prev) {
161
162 $current = $rs->current();
163
164 if (!isset($current->course)) {
165 $current = false;
166 }
167 else {
168 // Not all enrol plugins fill out timestart correctly, so use whichever
169 // is non-zero
170 $current->timeenrolled = max($current->timecreated, $current->timeenrolled);
171 }
172
173 // If we are at the last record,
174 // or we aren't at the first and the record is for a diff user/course
175 if ($prev &&
176 (!$rs->valid() ||
177 ($current->course != $prev->course || $current->userid != $prev->userid))) {
178
179 $completion = new completion_completion();
180 $completion->userid = $prev->userid;
181 $completion->course = $prev->course;
182 $completion->timeenrolled = (string) $prev->timeenrolled;
183 $completion->timestarted = 0;
184 $completion->reaggregate = time();
185
186 if ($prev->completionid) {
187 $completion->id = $prev->completionid;
188 }
189
190 $completion->mark_enrolled();
191
192 if (debugging()) {
193 mtrace('Marked started user '.$prev->userid.' in course '.$prev->course);
194 }
195 }
196 // Else, if this record is for the same user/course
197 elseif ($prev && $current) {
198 // Use oldest timeenrolled
199 $current->timeenrolled = min($current->timeenrolled, $prev->timeenrolled);
200 }
201
202 // Move current record to previous
203 $prev = $current;
204
205 // Move to next record
206 $rs->next();
207 }
208
209 $rs->close();
2be4d090
MD
210}
211
212/**
213 * Run installed criteria's data aggregation methods
214 *
215 * Loop through each installed criteria and run the
216 * cron() method if it exists
217 *
836375ec 218 * @return void
2be4d090
MD
219 */
220function completion_cron_criteria() {
221
222 // Process each criteria type
223 global $CFG, $COMPLETION_CRITERIA_TYPES;
224
225 foreach ($COMPLETION_CRITERIA_TYPES as $type) {
226
227 $object = 'completion_criteria_'.$type;
60829d80 228 require_once $CFG->dirroot.'/completion/criteria/'.$object.'.php';
2be4d090
MD
229
230 $class = new $object();
231
232 // Run the criteria type's cron method, if it has one
233 if (method_exists($class, 'cron')) {
234
235 if (debugging()) {
236 mtrace('Running '.$object.'->cron()');
237 }
238 $class->cron();
239 }
240 }
241}
242
243/**
244 * Aggregate each user's criteria completions
2be4d090
MD
245 */
246function completion_cron_completions() {
247 global $DB;
248
249 if (debugging()) {
250 mtrace('Aggregating completions');
251 }
252
253 // Save time started
254 $timestarted = time();
255
256 // Grab all criteria and their associated criteria completions
257 $sql = '
258 SELECT DISTINCT
259 c.id AS course,
260 cr.id AS criteriaid,
24a3b341 261 crc.userid AS userid,
2be4d090
MD
262 cr.criteriatype AS criteriatype,
263 cc.timecompleted AS timecompleted
264 FROM
265 {course_completion_criteria} cr
266 INNER JOIN
267 {course} c
268 ON cr.course = c.id
269 INNER JOIN
89482538
AB
270 {course_completions} crc
271 ON crc.course = c.id
2be4d090
MD
272 LEFT JOIN
273 {course_completion_crit_compl} cc
274 ON cc.criteriaid = cr.id
89482538 275 AND crc.userid = cc.userid
2be4d090 276 WHERE
89482538 277 c.enablecompletion = 1
2be4d090
MD
278 AND crc.timecompleted IS NULL
279 AND crc.reaggregate > 0
24a3b341 280 AND crc.reaggregate < :timestarted
2be4d090
MD
281 ORDER BY
282 course,
283 userid
284 ';
285
419178d7
EL
286 $rs = $DB->get_recordset_sql($sql, array('timestarted' => $timestarted));
287
2be4d090 288 // Check if result is empty
419178d7
EL
289 if (!$rs->valid()) {
290 $rs->close(); // Not going to iterate (but exit), close rs
2be4d090
MD
291 return;
292 }
293
294 $current_user = null;
295 $current_course = null;
296 $completions = array();
297
298 while (1) {
299
300 // Grab records for current user/course
301 foreach ($rs as $record) {
302 // If we are still grabbing the same users completions
303 if ($record->userid === $current_user && $record->course === $current_course) {
304 $completions[$record->criteriaid] = $record;
305 } else {
306 break;
307 }
308 }
309
310 // Aggregate
311 if (!empty($completions)) {
312
313 if (debugging()) {
314 mtrace('Aggregating completions for user '.$current_user.' in course '.$current_course);
315 }
316
317 // Get course info object
318 $info = new completion_info((object)array('id' => $current_course));
319
320 // Setup aggregation
321 $overall = $info->get_aggregation_method();
322 $activity = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ACTIVITY);
323 $prerequisite = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_COURSE);
324 $role = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ROLE);
325
326 $overall_status = null;
327 $activity_status = null;
328 $prerequisite_status = null;
329 $role_status = null;
330
331 // Get latest timecompleted
332 $timecompleted = null;
333
334 // Check each of the criteria
335 foreach ($completions as $params) {
336 $timecompleted = max($timecompleted, $params->timecompleted);
337
dbfcf440 338 $completion = new completion_criteria_completion((array)$params, false);
2be4d090
MD
339
340 // Handle aggregation special cases
341 if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) {
342 completion_cron_aggregate($activity, $completion->is_complete(), $activity_status);
343 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) {
344 completion_cron_aggregate($prerequisite, $completion->is_complete(), $prerequisite_status);
345 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ROLE) {
346 completion_cron_aggregate($role, $completion->is_complete(), $role_status);
347 } else {
348 completion_cron_aggregate($overall, $completion->is_complete(), $overall_status);
349 }
350 }
351
352 // Include role criteria aggregation in overall aggregation
353 if ($role_status !== null) {
354 completion_cron_aggregate($overall, $role_status, $overall_status);
355 }
356
357 // Include activity criteria aggregation in overall aggregation
358 if ($activity_status !== null) {
359 completion_cron_aggregate($overall, $activity_status, $overall_status);
360 }
361
362 // Include prerequisite criteria aggregation in overall aggregation
363 if ($prerequisite_status !== null) {
364 completion_cron_aggregate($overall, $prerequisite_status, $overall_status);
365 }
366
367 // If aggregation status is true, mark course complete for user
368 if ($overall_status) {
369 if (debugging()) {
370 mtrace('Marking complete');
371 }
372
373 $ccompletion = new completion_completion(array('course' => $params->course, 'userid' => $params->userid));
374 $ccompletion->mark_complete($timecompleted);
375 }
376 }
377
378 // If this is the end of the recordset, break the loop
379 if (!$rs->valid()) {
380 $rs->close();
381 break;
382 }
383
384 // New/next user, update user details, reset completions
385 $current_user = $record->userid;
386 $current_course = $record->course;
387 $completions = array();
388 $completions[$record->criteriaid] = $record;
389 }
390
391 // Mark all users as aggregated
392 $sql = "
393 UPDATE
394 {course_completions}
395 SET
396 reaggregate = 0
397 WHERE
7ba1c665
AB
398 reaggregate < :timestarted
399 AND reaggregate > 0
2be4d090
MD
400 ";
401
7ba1c665 402 $DB->execute($sql, array('timestarted' => $timestarted));
2be4d090
MD
403}
404
405/**
406 * Aggregate criteria status's as per configured aggregation method
407 *
408 * @param int $method COMPLETION_AGGREGATION_* constant
409 * @param bool $data Criteria completion status
410 * @param bool|null $state Aggregation state
2be4d090
MD
411 */
412function completion_cron_aggregate($method, $data, &$state) {
413 if ($method == COMPLETION_AGGREGATION_ALL) {
414 if ($data && $state !== false) {
415 $state = true;
416 } else {
417 $state = false;
418 }
419 } elseif ($method == COMPLETION_AGGREGATION_ANY) {
420 if ($data) {
421 $state = true;
422 } else if (!$data && $state === null) {
423 $state = false;
424 }
425 }
426}