2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
22 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 global $DB, $CFG, $OUTPUT;
32 if (CLI_MAINTENANCE) {
33 echo "CLI maintenance mode active, cron execution suspended.\n";
37 if (moodle_needs_upgrading()) {
38 echo "Moodle upgrade pending, cron execution suspended.\n";
42 require_once($CFG->libdir.'/adminlib.php');
43 require_once($CFG->libdir.'/gradelib.php');
45 if (!empty($CFG->showcronsql)) {
48 if (!empty($CFG->showcrondebugging)) {
49 $CFG->debug = DEBUG_DEVELOPER;
50 $CFG->debugdisplay = true;
54 $starttime = microtime();
56 // Increase memory limit
57 raise_memory_limit(MEMORY_EXTRA);
59 // Emulate normal session - we use admin accoutn by default
64 mtrace("Server Time: ".date('r',$timenow)."\n\n");
67 // Run cleanup core cron jobs, but not every time since they aren't too important.
68 // These don't have a timer to reduce load, so we'll use a random number
69 // to randomly choose the percentage of times we should run these jobs.
70 srand ((double) microtime() * 10000000);
71 $random100 = rand(0,100);
72 if ($random100 < 20) { // Approximately 20% of the time.
73 mtrace("Running clean-up tasks...");
75 // Delete users who haven't confirmed within required period
76 if (!empty($CFG->deleteunconfirmed)) {
77 $cuttime = $timenow - ($CFG->deleteunconfirmed * 3600);
78 $rs = $DB->get_recordset_sql ("SELECT *
80 WHERE confirmed = 0 AND firstaccess > 0
81 AND firstaccess < ?", array($cuttime));
82 foreach ($rs as $user) {
83 delete_user($user); // we MUST delete user properly first
84 $DB->delete_records('user', array('id'=>$user->id)); // this is a bloody hack, but it might work
85 mtrace(" Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
91 // Delete users who haven't completed profile within required period
92 if (!empty($CFG->deleteincompleteusers)) {
93 $cuttime = $timenow - ($CFG->deleteincompleteusers * 3600);
94 $rs = $DB->get_recordset_sql ("SELECT *
96 WHERE confirmed = 1 AND lastaccess > 0
97 AND lastaccess < ? AND deleted = 0
98 AND (lastname = '' OR firstname = '' OR email = '')",
100 foreach ($rs as $user) {
102 mtrace(" Deleted not fully setup user $user->username ($user->id)");
108 // Delete old logs to save space (this might need a timer to slow it down...)
109 if (!empty($CFG->loglifetime)) { // value in days
110 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
111 $DB->delete_records_select("log", "time < ?", array($loglifetime));
112 mtrace(" Deleted old log records");
116 // Delete old backup_controllers and logs
117 if (!empty($CFG->loglifetime)) { // value in days
118 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
119 // Delete child records from backup_logs
120 $DB->execute("DELETE FROM {backup_logs}
123 FROM {backup_controllers} bc
124 WHERE bc.backupid = {backup_logs}.backupid
125 AND bc.timecreated < ?)", array($loglifetime));
126 // Delete records from backup_controllers
127 $DB->execute("DELETE FROM {backup_controllers}
128 WHERE timecreated < ?", array($loglifetime));
129 mtrace(" Deleted old backup records");
133 // Delete old cached texts
134 if (!empty($CFG->cachetext)) { // Defined in config.php
135 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
136 $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
137 mtrace(" Deleted old cache_text records");
141 if (!empty($CFG->usetags)) {
142 require_once($CFG->dirroot.'/tag/lib.php');
144 mtrace(' Executed tag cron');
148 // Context maintenance stuff
149 context_helper::cleanup_instances();
150 mtrace(' Cleaned up context instances');
151 context_helper::build_all_paths(false);
152 // If you suspect that the context paths are somehow corrupt
153 // replace the line below with: context_helper::build_all_paths(true);
154 mtrace(' Built context paths');
157 // Remove expired cache flags
159 mtrace(' Cleaned cache flags');
163 if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
164 $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
165 $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime'=>$notificationdeletetime));
166 mtrace(' Cleaned up read notifications');
169 mtrace("...finished clean-up tasks");
171 } // End of occasional clean-up tasks
174 // Send login failures notification - brute force protection in moodle is weak,
175 // we should at least send notices early in each cron execution
176 if (!empty($CFG->notifyloginfailures)) {
177 notify_login_failures();
178 mtrace(' Notified login failured');
182 // Make sure all context instances are properly created - they may be required in auth, enrol, etc.
183 context_helper::create_instances();
184 mtrace(' Created missing context instances');
189 mtrace("Cleaned up stale user sessions");
192 // Run the auth cron, if any before enrolments
193 // because it might add users that will be needed in enrol plugins
194 $auths = get_enabled_auth_plugins();
195 mtrace("Running auth crons if required...");
196 foreach ($auths as $auth) {
197 $authplugin = get_auth_plugin($auth);
198 if (method_exists($authplugin, 'cron')) {
199 mtrace("Running cron for auth/$auth...");
201 if (!empty($authplugin->log)) {
202 mtrace($authplugin->log);
207 // Generate new password emails for users - ppl expect these generated asap
208 if ($DB->count_records('user_preferences', array('name'=>'create_password', 'value'=>'1'))) {
209 mtrace('Creating passwords for new users...');
210 $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email, u.firstname,
211 u.lastname, u.username,
214 JOIN {user_preferences} p ON u.id=p.userid
215 WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin'");
217 // note: we can not send emails to suspended accounts
218 foreach ($newusers as $newuser) {
219 if (setnew_password_and_mail($newuser)) {
220 unset_user_preference('create_password', $newuser);
221 set_user_preference('auth_forcepasswordchange', 1, $newuser);
223 trigger_error("Could not create and mail new user password!");
230 // It is very important to run enrol early
231 // because other plugins depend on correct enrolment info.
232 mtrace("Running enrol crons if required...");
233 $enrols = enrol_get_plugins(true);
234 foreach($enrols as $ename=>$enrol) {
235 // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
236 if (!$enrol->is_cron_required()) {
239 mtrace("Running cron for enrol_$ename...");
241 $enrol->set_config('lastcron', time());
245 // Run all cron jobs for each module
246 mtrace("Starting activity modules");
247 get_mailer('buffer');
248 if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
249 foreach ($mods as $mod) {
250 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
251 if (file_exists($libfile)) {
252 include_once($libfile);
253 $cron_function = $mod->name."_cron";
254 if (function_exists($cron_function)) {
255 mtrace("Processing module function $cron_function ...", '');
256 $pre_dbqueries = null;
257 $pre_dbqueries = $DB->perf_get_queries();
258 $pre_time = microtime(1);
259 if ($cron_function()) {
260 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id));
262 if (isset($pre_dbqueries)) {
263 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
264 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
266 // Reset possible changes by modules to time_limit. MDL-11597
274 mtrace("Finished activity modules");
277 mtrace("Starting blocks");
278 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
279 // We will need the base class.
280 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
281 foreach ($blocks as $block) {
282 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
283 if (file_exists($blockfile)) {
284 require_once($blockfile);
285 $classname = 'block_'.$block->name;
286 $blockobj = new $classname;
287 if (method_exists($blockobj,'cron')) {
288 mtrace("Processing cron function for ".$block->name.'....','');
289 if ($blockobj->cron()) {
290 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id));
292 // Reset possible changes by blocks to time_limit. MDL-11597
300 mtrace('Finished blocks');
303 //TODO: get rid of this bloody hardcoded quiz module stuff, this must be done from quiz_cron()!
304 mtrace("Starting quiz reports");
305 if ($reports = $DB->get_records_select('quiz_reports', "cron > 0 AND ((? - lastcron) > cron)", array($timenow))) {
306 foreach ($reports as $report) {
307 $cronfile = "$CFG->dirroot/mod/quiz/report/$report->name/cron.php";
308 if (file_exists($cronfile)) {
309 include_once($cronfile);
310 $cron_function = 'quiz_report_'.$report->name."_cron";
311 if (function_exists($cron_function)) {
312 mtrace("Processing quiz report cron function $cron_function ...", '');
313 $pre_dbqueries = null;
314 $pre_dbqueries = $DB->perf_get_queries();
315 $pre_time = microtime(1);
316 if ($cron_function()) {
317 $DB->set_field('quiz_reports', "lastcron", $timenow, array("id"=>$report->id));
319 if (isset($pre_dbqueries)) {
320 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
321 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
329 mtrace("Finished quiz reports");
332 mtrace('Starting admin reports');
333 cron_execute_plugin_type('report');
334 mtrace('Finished admin reports');
337 mtrace('Starting main gradebook job...');
342 mtrace('Starting processing the event queue...');
347 if ($CFG->enablecompletion) {
349 mtrace('Starting the completion cron...');
350 require_once($CFG->libdir . '/completion/cron.php');
356 if ($CFG->enableportfolios) {
358 mtrace('Starting the portfolio cron...');
359 require_once($CFG->libdir . '/portfoliolib.php');
365 //now do plagiarism checks
366 require_once($CFG->libdir.'/plagiarismlib.php');
370 mtrace('Starting course reports');
371 cron_execute_plugin_type('coursereport');
372 mtrace('Finished course reports');
375 // run gradebook import/export/report cron
376 mtrace('Starting gradebook plugins');
377 cron_execute_plugin_type('gradeimport');
378 cron_execute_plugin_type('gradeexport');
379 cron_execute_plugin_type('gradereport');
380 mtrace('Finished gradebook plugins');
383 // Run external blog cron if needed
384 if ($CFG->useexternalblogs) {
385 require_once($CFG->dirroot . '/blog/lib.php');
386 mtrace("Fetching external blog entries...", '');
387 $sql = "timefetched < ? OR timefetched = 0";
388 $externalblogs = $DB->get_records_select('blog_external', $sql, array(mktime() - $CFG->externalblogcrontime));
390 foreach ($externalblogs as $eb) {
391 blog_sync_external_entries($eb);
395 // Run blog associations cleanup
396 if ($CFG->useblogassociations) {
397 require_once($CFG->dirroot . '/blog/lib.php');
398 // delete entries whose contextids no longer exists
399 mtrace("Deleting blog associations linked to non-existent contexts...", '');
400 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
405 //Run registration updated cron
406 mtrace(get_string('siteupdatesstart', 'hub'));
407 require_once($CFG->dirroot . '/admin/registration/lib.php');
408 $registrationmanager = new registration_manager();
409 $registrationmanager->cron();
410 mtrace(get_string('siteupdatesend', 'hub'));
413 //cleanup old session linked tokens
414 //deletes the session linked tokens that are over a day old.
415 mtrace("Deleting session linked tokens more than one day old...", '');
416 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
417 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
422 cron_execute_plugin_type('message', 'message plugins');
423 cron_execute_plugin_type('filter', 'filters');
424 cron_execute_plugin_type('editor', 'editors');
425 cron_execute_plugin_type('format', 'course formats');
426 cron_execute_plugin_type('profilefield', 'profile fields');
427 cron_execute_plugin_type('webservice', 'webservices');
428 // TODO: Repository lib.php files are messed up (include many other files, etc), so it is
429 // currently not possible to implement repository plugin cron using this infrastructure
430 // cron_execute_plugin_type('repository', 'repository plugins');
431 cron_execute_plugin_type('qtype', 'question types');
432 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
433 cron_execute_plugin_type('theme', 'themes');
434 cron_execute_plugin_type('tool', 'admin tools');
437 // and finally run any local cronjobs, if any
438 if ($locals = get_plugin_list('local')) {
439 mtrace('Processing customized cron scripts ...', '');
440 // new cron functions in lib.php first
441 cron_execute_plugin_type('local');
442 // legacy cron files are executed directly
443 foreach ($locals as $local => $localdir) {
444 if (file_exists("$localdir/cron.php")) {
445 include("$localdir/cron.php");
452 // Run automated backups if required - these may take a long time to execute
453 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
454 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
455 backup_cron_automated_helper::run_automated_backup();
458 // Run stats as at the end because they are known to take very long time on large sites
459 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
460 require_once($CFG->dirroot.'/lib/statslib.php');
461 // check we're not before our runtime
462 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
464 if (time() > $timetocheck) {
465 // process configured number of days as max (defaulting to 31)
466 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
467 if (stats_cron_daily($maxdays)) {
468 if (stats_cron_weekly()) {
469 if (stats_cron_monthly()) {
476 mtrace('Next stats run after:'. userdate($timetocheck));
481 // cleanup file trash - not very important
482 $fs = get_file_storage();
486 mtrace("Cron script completed correctly");
488 $difftime = microtime_diff($starttime, microtime());
489 mtrace("Execution took ".$difftime." seconds");
493 * Executes cron functions for a specific type of plugin.
495 * @param string $plugintype Plugin type (e.g. 'report')
496 * @param string $description If specified, will display 'Starting (whatever)'
497 * and 'Finished (whatever)' lines, otherwise does not display
499 function cron_execute_plugin_type($plugintype, $description = null) {
502 // Get list from plugin => function for all plugins
503 $plugins = get_plugin_list_with_function($plugintype, 'cron');
505 // Modify list for backward compatibility (different files/names)
506 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
508 // Return if no plugins with cron function to process
514 mtrace('Starting '.$description);
517 foreach ($plugins as $component=>$cronfunction) {
518 $dir = get_component_directory($component);
520 // Get cron period if specified in version.php, otherwise assume every cron
522 if (file_exists("$dir/version.php")) {
523 $plugin = new stdClass();
524 include("$dir/version.php");
525 if (isset($plugin->cron)) {
526 $cronperiod = $plugin->cron;
530 // Using last cron and cron period, don't run if it already ran recently
531 $lastcron = get_config($component, 'lastcron');
532 if ($cronperiod && $lastcron) {
533 if ($lastcron + $cronperiod > time()) {
534 // do not execute cron yet
539 mtrace('Processing cron function for ' . $component . '...');
540 $pre_dbqueries = $DB->perf_get_queries();
541 $pre_time = microtime(true);
545 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
546 round(microtime(true) - $pre_time, 2) . " seconds)");
548 set_config('lastcron', time(), $component);
553 mtrace('Finished ' . $description);
558 * Used to add in old-style cron functions within plugins that have not been converted to the
559 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
560 * cron.php and some used a different name.)
562 * @param string $plugintype Plugin type e.g. 'report'
563 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
564 * 'report_frog_cron') for plugin cron functions that were already found using the new API
565 * @return array Revised version of $plugins that adds in any extra plugin functions found by
566 * looking in the older location
568 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
569 global $CFG; // mandatory in case it is referenced by include()d PHP script
571 if ($plugintype === 'report') {
572 // Admin reports only - not course report because course report was
573 // never implemented before, so doesn't need BC
574 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
575 $component = $plugintype . '_' . $pluginname;
576 if (isset($plugins[$component])) {
577 // We already have detected the function using the new API
580 if (!file_exists("$dir/cron.php")) {
581 // No old style cron file present
584 include_once("$dir/cron.php");
585 $cronfunction = $component . '_cron';
586 if (function_exists($cronfunction)) {
587 $plugins[$component] = $cronfunction;
589 debugging("Invalid legacy cron.php detected in $component, " .
590 "please use lib.php instead");
593 } else if (strpos($plugintype, 'grade') === 0) {
594 // Detect old style cron function names
595 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
596 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
597 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
598 $component = $plugintype.'_'.$pluginname;
599 if (isset($plugins[$component])) {
600 // We already have detected the function using the new API
603 if (!file_exists("$dir/lib.php")) {
606 include_once("$dir/lib.php");
607 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
608 $pluginname . '_cron';
609 if (function_exists($cronfunction)) {
610 $plugins[$component] = $cronfunction;
620 * Notify admin users or admin user of any failed logins (since last notification).
622 * Note that this function must be only executed from the cron script
623 * It uses the cache_flags system to store temporary records, deleting them
624 * by name before finishing
626 function notify_login_failures() {
627 global $CFG, $DB, $OUTPUT;
629 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
631 if (empty($CFG->lastnotifyfailure)) {
632 $CFG->lastnotifyfailure=0;
635 // we need to deal with the threshold stuff first.
636 if (empty($CFG->notifyloginthreshold)) {
637 $CFG->notifyloginthreshold = 10; // default to something sensible.
640 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
641 // and insert them into the cache_flags temp table
642 $sql = "SELECT ip, COUNT(*)
644 WHERE module = 'login' AND action = 'error'
647 HAVING COUNT(*) >= ?";
648 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
649 $rs = $DB->get_recordset_sql($sql, $params);
650 foreach ($rs as $iprec) {
651 if (!empty($iprec->ip)) {
652 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
657 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
658 // and insert them into the cache_flags temp table
659 $sql = "SELECT info, count(*)
661 WHERE module = 'login' AND action = 'error'
664 HAVING count(*) >= ?";
665 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
666 $rs = $DB->get_recordset_sql($sql, $params);
667 foreach ($rs as $inforec) {
668 if (!empty($inforec->info)) {
669 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
674 // Now, select all the login error logged records belonging to the ips and infos
675 // since lastnotifyfailure, that we have stored in the cache_flags table
676 $sql = "SELECT l.*, u.firstname, u.lastname
678 JOIN {cache_flags} cf ON l.ip = cf.name
679 LEFT JOIN {user} u ON l.userid = u.id
680 WHERE l.module = 'login' AND l.action = 'error'
682 AND cf.flagtype = 'login_failure_by_ip'
684 SELECT l.*, u.firstname, u.lastname
686 JOIN {cache_flags} cf ON l.info = cf.name
687 LEFT JOIN {user} u ON l.userid = u.id
688 WHERE l.module = 'login' AND l.action = 'error'
690 AND cf.flagtype = 'login_failure_by_info'
692 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
694 // Init some variables
697 // Iterate over the logs recordset
698 $rs = $DB->get_recordset_sql($sql, $params);
699 foreach ($rs as $log) {
700 $log->time = userdate($log->time);
701 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
706 // If we haven't run in the last hour and
707 // we have something useful to report and we
708 // are actually supposed to be reporting to somebody
709 if ((time() - HOURSECS) > $CFG->lastnotifyfailure && $count > 0 && is_array($recip) && count($recip) > 0) {
711 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
712 // Calculate the complete body of notification (start + messages + end)
713 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
714 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
716 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
718 // For each destination, send mail
719 mtrace('Emailing admins about '. $count .' failed login attempts');
720 foreach ($recip as $admin) {
721 //emailing the admins directly rather than putting these through the messaging system
722 email_to_user($admin,get_admin(), $subject, $body);
725 // Update lastnotifyfailure with current time
726 set_config('lastnotifyfailure', time());
729 // Finally, delete all the temp records we have created in cache_flags
730 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");