cron MDL-25370 Added support for course report cron
[moodle.git] / lib / cronlib.php
CommitLineData
28bd3d9a
PS
1<?php
2
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.
14//
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/>.
17
18/**
19 * Cron functions.
20 *
21 * @package core
22 * @subpackage admin
23 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27function cron_run() {
28 global $DB, $CFG, $OUTPUT;
29
9957af68
PS
30 if (CLI_MAINTENANCE) {
31 echo "CLI maintenance mode active, cron execution suspended.\n";
32 exit(1);
33 }
34
4c56c7bf
PS
35 if (moodle_needs_upgrading()) {
36 echo "Moodle upgrade pending, cron execution suspended.\n";
37 exit(1);
38 }
39
28bd3d9a
PS
40 require_once($CFG->libdir.'/adminlib.php');
41 require_once($CFG->libdir.'/gradelib.php');
42
43 if (!empty($CFG->showcronsql)) {
44 $DB->set_debug(true);
45 }
46 if (!empty($CFG->showcrondebugging)) {
47 $CFG->debug = DEBUG_DEVELOPER;
48 $CFG->debugdisplay = true;
49 }
50
51 set_time_limit(0);
52 $starttime = microtime();
53
41209c1e 54/// increase memory limit
346c5887 55 raise_memory_limit(MEMORY_EXTRA);
28bd3d9a
PS
56
57/// emulate normal session
58 cron_setup_user();
59
60/// Start output log
61
62 $timenow = time();
63
64 mtrace("Server Time: ".date('r',$timenow)."\n\n");
65
66
67/// Session gc
68
69 mtrace("Cleaning up stale sessions");
70 session_gc();
71
72/// Run all cron jobs for each module
73
74 mtrace("Starting activity modules");
75 get_mailer('buffer');
76 if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
77 foreach ($mods as $mod) {
78 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
79 if (file_exists($libfile)) {
80 include_once($libfile);
81 $cron_function = $mod->name."_cron";
82 if (function_exists($cron_function)) {
83 mtrace("Processing module function $cron_function ...", '');
84 $pre_dbqueries = null;
85 $pre_dbqueries = $DB->perf_get_queries();
86 $pre_time = microtime(1);
87 if ($cron_function()) {
f685e830 88 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id));
28bd3d9a
PS
89 }
90 if (isset($pre_dbqueries)) {
91 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
92 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
93 }
94 /// Reset possible changes by modules to time_limit. MDL-11597
95 @set_time_limit(0);
96 mtrace("done.");
97 }
98 }
99 }
100 }
101 get_mailer('close');
102 mtrace("Finished activity modules");
103
104 mtrace("Starting blocks");
105 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
106 // we will need the base class.
107 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
108 foreach ($blocks as $block) {
109 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
110 if (file_exists($blockfile)) {
111 require_once($blockfile);
112 $classname = 'block_'.$block->name;
113 $blockobj = new $classname;
114 if (method_exists($blockobj,'cron')) {
115 mtrace("Processing cron function for ".$block->name.'....','');
116 if ($blockobj->cron()) {
f685e830 117 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id));
28bd3d9a
PS
118 }
119 /// Reset possible changes by blocks to time_limit. MDL-11597
120 @set_time_limit(0);
121 mtrace('done.');
122 }
123 }
124
125 }
126 }
127 mtrace('Finished blocks');
128
bce59524
DM
129 //now do plagiarism checks
130 require_once($CFG->libdir.'/plagiarismlib.php');
131 plagiarism_cron();
132
28bd3d9a
PS
133 mtrace("Starting quiz reports");
134 if ($reports = $DB->get_records_select('quiz_report', "cron > 0 AND ((? - lastcron) > cron)", array($timenow))) {
135 foreach ($reports as $report) {
136 $cronfile = "$CFG->dirroot/mod/quiz/report/$report->name/cron.php";
137 if (file_exists($cronfile)) {
138 include_once($cronfile);
139 $cron_function = 'quiz_report_'.$report->name."_cron";
140 if (function_exists($cron_function)) {
141 mtrace("Processing quiz report cron function $cron_function ...", '');
142 $pre_dbqueries = null;
143 $pre_dbqueries = $DB->perf_get_queries();
144 $pre_time = microtime(1);
145 if ($cron_function()) {
f685e830 146 $DB->set_field('quiz_report', "lastcron", $timenow, array("id"=>$report->id));
28bd3d9a
PS
147 }
148 if (isset($pre_dbqueries)) {
149 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
150 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
151 }
152 mtrace("done.");
153 }
154 }
155 }
156 }
157 mtrace("Finished quiz reports");
158
28bd3d9a
PS
159 mtrace('Starting main gradebook job ...');
160 grade_cron();
161 mtrace('done.');
162
163
164 mtrace('Starting processing the event queue...');
165 events_cron();
166 mtrace('done.');
167
168
169 if ($CFG->enablecompletion) {
170 // Completion cron
171 mtrace('Starting the completion cron...');
172 require_once($CFG->libdir . '/completion/cron.php');
173 completion_cron();
174 mtrace('done');
175 }
176
177
178 if ($CFG->enableportfolios) {
179 // Portfolio cron
180 mtrace('Starting the portfolio cron...');
181 require_once($CFG->libdir . '/portfoliolib.php');
182 portfolio_cron();
183 mtrace('done');
184 }
185
186/// Run all core cron jobs, but not every time since they aren't too important.
187/// These don't have a timer to reduce load, so we'll use a random number
188/// to randomly choose the percentage of times we should run these jobs.
189
190 srand ((double) microtime() * 10000000);
191 $random100 = rand(0,100);
192
193 if ($random100 < 20) { // Approximately 20% of the time.
194 mtrace("Running clean-up tasks...");
195
196 /// Delete users who haven't confirmed within required period
197
198 if (!empty($CFG->deleteunconfirmed)) {
199 $cuttime = $timenow - ($CFG->deleteunconfirmed * 3600);
200 $rs = $DB->get_recordset_sql ("SELECT id, firstname, lastname
201 FROM {user}
202 WHERE confirmed = 0 AND firstaccess > 0
203 AND firstaccess < ?", array($cuttime));
204 foreach ($rs as $user) {
205 if ($DB->delete_records('user', array('id'=>$user->id))) {
206 mtrace("Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
207 }
208 }
209 $rs->close();
210 }
211 flush();
212
213
214 /// Delete users who haven't completed profile within required period
215
216 if (!empty($CFG->deleteincompleteusers)) {
217 $cuttime = $timenow - ($CFG->deleteincompleteusers * 3600);
218 $rs = $DB->get_recordset_sql ("SELECT id, username
219 FROM {user}
220 WHERE confirmed = 1 AND lastaccess > 0
221 AND lastaccess < ? AND deleted = 0
222 AND (lastname = '' OR firstname = '' OR email = '')",
223 array($cuttime));
224 foreach ($rs as $user) {
225 if (delete_user($user)) {
226 mtrace("Deleted not fully setup user $user->username ($user->id)");
227 }
228 }
229 $rs->close();
230 }
231 flush();
232
233
234 /// Delete old logs to save space (this might need a timer to slow it down...)
235
236 if (!empty($CFG->loglifetime)) { // value in days
237 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
238 if ($DB->delete_records_select("log", "time < ?", array($loglifetime))) {
239 mtrace("Deleted old log records");
240 }
241 }
242 flush();
243
cbb9e9b8
EL
244 // Delete old backup_controllers and logs
245
246 if (!empty($CFG->loglifetime)) { // value in days
247 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
248 // Delete child records from backup_logs
249 $DB->execute("DELETE FROM {backup_logs}
250 WHERE EXISTS (
251 SELECT 'x'
252 FROM {backup_controllers} bc
253 WHERE bc.backupid = {backup_logs}.backupid
254 AND bc.timecreated < ?)", array($loglifetime));
255 // Delete records from backup_controllers
256 $DB->execute("DELETE FROM {backup_controllers}
257 WHERE timecreated < ?", array($loglifetime));
258 mtrace("Deleted old backup records");
259 }
260 flush();
261
262
28bd3d9a
PS
263
264 /// Delete old cached texts
265
266 if (!empty($CFG->cachetext)) { // Defined in config.php
267 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
268 if ($DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime))) {
269 mtrace("Deleted old cache_text records");
270 }
271 }
272 flush();
273
274 if (!empty($CFG->notifyloginfailures)) {
275 notify_login_failures();
276 mtrace('Notified login failured');
277 }
278 flush();
279
280 //
281 // generate new password emails for users
282 //
283 mtrace('checking for create_password');
284 if ($DB->count_records('user_preferences', array('name'=>'create_password', 'value'=>'1'))) {
285 mtrace('creating passwords for new users');
286 $newusers = $DB->get_records_sql("SELECT u.id as id, u.email, u.firstname,
287 u.lastname, u.username,
288 p.id as prefid
289 FROM {user} u
290 JOIN {user_preferences} p ON u.id=p.userid
291 WHERE p.name='create_password' AND p.value='1' AND u.email !='' ");
292
293 foreach ($newusers as $newuserid => $newuser) {
28bd3d9a
PS
294 // email user
295 if (setnew_password_and_mail($newuser)) {
296 // remove user pref
297 $DB->delete_records('user_preferences', array('id'=>$newuser->prefid));
298 } else {
299 trigger_error("Could not create and mail new user password!");
300 }
301 }
302 }
303
304 if (!empty($CFG->usetags)) {
305 require_once($CFG->dirroot.'/tag/lib.php');
306 tag_cron();
307 mtrace ('Executed tag cron');
308 }
309
310 // Accesslib stuff
311 cleanup_contexts();
312 mtrace ('Cleaned up contexts');
313 gc_cache_flags();
314 mtrace ('Cleaned cache flags');
315 // If you suspect that the context paths are somehow corrupt
316 // replace the line below with: build_context_path(true);
317 build_context_path();
318 mtrace ('Built context paths');
319
212badff 320 if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
7868480a 321 $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
212badff
AD
322 $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime'=>$notificationdeletetime));
323 mtrace('Cleaned up read notifications');
324 }
325
28bd3d9a
PS
326 mtrace("Finished clean-up tasks...");
327
328 } // End of occasional clean-up tasks
329
bac233d3
SH
330 // Run automated backups if required.
331 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
332 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
333 backup_cron_automated_helper::run_automated_backup();
28bd3d9a
PS
334
335/// Run the auth cron, if any
336/// before enrolments because it might add users that will be needed in enrol plugins
337 $auths = get_enabled_auth_plugins();
338
339 mtrace("Running auth crons if required...");
340 foreach ($auths as $auth) {
341 $authplugin = get_auth_plugin($auth);
342 if (method_exists($authplugin, 'cron')) {
343 mtrace("Running cron for auth/$auth...");
344 $authplugin->cron();
345 if (!empty($authplugin->log)) {
346 mtrace($authplugin->log);
347 }
348 }
349 unset($authplugin);
350 }
351
352 mtrace("Running enrol crons if required...");
353 $enrols = enrol_get_plugins(true);
354 foreach($enrols as $ename=>$enrol) {
355 // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
356 if (!$enrol->is_cron_required()) {
357 continue;
358 }
359 mtrace("Running cron for enrol_$ename...");
360 $enrol->cron();
361 $enrol->set_config('lastcron', time());
362 }
363
364 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
365 require_once($CFG->dirroot.'/lib/statslib.php');
366 // check we're not before our runtime
367 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
368
369 if (time() > $timetocheck) {
370 // process configured number of days as max (defaulting to 31)
371 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
372 if (stats_cron_daily($maxdays)) {
373 if (stats_cron_weekly()) {
374 if (stats_cron_monthly()) {
375 stats_clean_old();
376 }
377 }
378 }
379 @set_time_limit(0);
380 } else {
381 mtrace('Next stats run after:'. userdate($timetocheck));
382 }
383 }
384
385 // run gradebook import/export/report cron
386 if ($gradeimports = get_plugin_list('gradeimport')) {
387 foreach ($gradeimports as $gradeimport => $plugindir) {
388 if (file_exists($plugindir.'/lib.php')) {
389 require_once($plugindir.'/lib.php');
390 $cron_function = 'grade_import_'.$gradeimport.'_cron';
391 if (function_exists($cron_function)) {
392 mtrace("Processing gradebook import function $cron_function ...", '');
393 $cron_function();
394 }
395 }
396 }
397 }
398
399 if ($gradeexports = get_plugin_list('gradeexport')) {
400 foreach ($gradeexports as $gradeexport => $plugindir) {
401 if (file_exists($plugindir.'/lib.php')) {
402 require_once($plugindir.'/lib.php');
403 $cron_function = 'grade_export_'.$gradeexport.'_cron';
404 if (function_exists($cron_function)) {
405 mtrace("Processing gradebook export function $cron_function ...", '');
406 $cron_function();
407 }
408 }
409 }
410 }
411
412 if ($gradereports = get_plugin_list('gradereport')) {
413 foreach ($gradereports as $gradereport => $plugindir) {
414 if (file_exists($plugindir.'/lib.php')) {
415 require_once($plugindir.'/lib.php');
416 $cron_function = 'grade_report_'.$gradereport.'_cron';
417 if (function_exists($cron_function)) {
418 mtrace("Processing gradebook report function $cron_function ...", '');
419 $cron_function();
420 }
421 }
422 }
423 }
424
425 // Run external blog cron if needed
426 if ($CFG->useexternalblogs) {
427 require_once($CFG->dirroot . '/blog/lib.php');
428 mtrace("Fetching external blog entries...", '');
429 $sql = "timefetched < ? OR timefetched = 0";
430 $externalblogs = $DB->get_records_select('blog_external', $sql, array(mktime() - $CFG->externalblogcrontime));
431
432 foreach ($externalblogs as $eb) {
433 blog_sync_external_entries($eb);
434 }
435 }
436
437 // Run blog associations cleanup
438 if ($CFG->useblogassociations) {
439 require_once($CFG->dirroot . '/blog/lib.php');
440 // delete entries whose contextids no longer exists
441 mtrace("Deleting blog associations linked to non-existent contexts...", '');
442 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
443 }
444
445 //Run registration updated cron
446 mtrace(get_string('siteupdatesstart', 'hub'));
447 require_once($CFG->dirroot . '/admin/registration/lib.php');
448 $registrationmanager = new registration_manager();
449 $registrationmanager->cron();
450 mtrace(get_string('siteupdatesend', 'hub'));
451
452 // cleanup file trash
453 $fs = get_file_storage();
454 $fs->cron();
455
456 //cleanup old session linked tokens
457 //deletes the session linked tokens that are over a day old.
458 mtrace("Deleting session linked tokens more than one day old...", '');
459 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
460 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
461 mtrace('done.');
462
463 // run any customized cronjobs, if any
464 if ($locals = get_plugin_list('local')) {
465 mtrace('Processing customized cron scripts ...', '');
466 foreach ($locals as $local => $localdir) {
467 if (file_exists("$localdir/cron.php")) {
468 include("$localdir/cron.php");
469 }
470 }
471 mtrace('done.');
472 }
473
54638024 474 // NOTE: Other types of plugin could also be supported in this loop, which
475 // can handle generic cron function.
476 foreach (array('report', 'coursereport') as $plugintype) {
477 mtrace('Starting plugin type: ' . $plugintype);
478 // These reports do not have a database table that lists them. Instead
479 // a report has cron.php with function report_reportname_cron() if it
480 // wishes to be cronned. It is up to this function to handle e.g. if it
481 // only needs to actually do anything occasionally.
482 $reports = get_plugin_list_with_function(
483 $plugintype, 'cron', 'cron.php');
484 foreach($reports as $report => $cronfunction) {
485 mtrace('Processing cron function for ' . $report . '...', '');
486 $pre_dbqueries = null;
487 $pre_dbqueries = $DB->perf_get_queries();
488 $pre_time = microtime(true);
489 $cronfunction();
490 if (isset($pre_dbqueries)) {
491 mtrace("... used " .
492 ($DB->perf_get_queries() - $pre_dbqueries) .
493 " dbqueries");
494 mtrace("... used " . round(microtime(true) - $pre_time, 2) .
495 " seconds");
496 }
497 mtrace('done.');
498 }
499 mtrace('Finished plugin type: ' . $plugintype);
500 }
28bd3d9a
PS
501
502 mtrace("Cron script completed correctly");
503
504 $difftime = microtime_diff($starttime, microtime());
505 mtrace("Execution took ".$difftime." seconds");
506
cbb9e9b8 507}