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 mtrace('Starting admin reports');
304 cron_execute_plugin_type('report');
305 mtrace('Finished admin reports');
308 mtrace('Starting main gradebook job...');
313 mtrace('Starting processing the event queue...');
318 if ($CFG->enablecompletion) {
320 mtrace('Starting the completion cron...');
321 require_once($CFG->libdir . '/completion/cron.php');
327 if ($CFG->enableportfolios) {
329 mtrace('Starting the portfolio cron...');
330 require_once($CFG->libdir . '/portfoliolib.php');
336 //now do plagiarism checks
337 require_once($CFG->libdir.'/plagiarismlib.php');
341 mtrace('Starting course reports');
342 cron_execute_plugin_type('coursereport');
343 mtrace('Finished course reports');
346 // run gradebook import/export/report cron
347 mtrace('Starting gradebook plugins');
348 cron_execute_plugin_type('gradeimport');
349 cron_execute_plugin_type('gradeexport');
350 cron_execute_plugin_type('gradereport');
351 mtrace('Finished gradebook plugins');
354 // Run external blog cron if needed
355 if ($CFG->useexternalblogs) {
356 require_once($CFG->dirroot . '/blog/lib.php');
357 mtrace("Fetching external blog entries...", '');
358 $sql = "timefetched < ? OR timefetched = 0";
359 $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
361 foreach ($externalblogs as $eb) {
362 blog_sync_external_entries($eb);
366 // Run blog associations cleanup
367 if ($CFG->useblogassociations) {
368 require_once($CFG->dirroot . '/blog/lib.php');
369 // delete entries whose contextids no longer exists
370 mtrace("Deleting blog associations linked to non-existent contexts...", '');
371 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
376 //Run registration updated cron
377 mtrace(get_string('siteupdatesstart', 'hub'));
378 require_once($CFG->dirroot . '/admin/registration/lib.php');
379 $registrationmanager = new registration_manager();
380 $registrationmanager->cron();
381 mtrace(get_string('siteupdatesend', 'hub'));
384 //cleanup old session linked tokens
385 //deletes the session linked tokens that are over a day old.
386 mtrace("Deleting session linked tokens more than one day old...", '');
387 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
388 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
393 cron_execute_plugin_type('message', 'message plugins');
394 cron_execute_plugin_type('filter', 'filters');
395 cron_execute_plugin_type('editor', 'editors');
396 cron_execute_plugin_type('format', 'course formats');
397 cron_execute_plugin_type('profilefield', 'profile fields');
398 cron_execute_plugin_type('webservice', 'webservices');
399 // TODO: Repository lib.php files are messed up (include many other files, etc), so it is
400 // currently not possible to implement repository plugin cron using this infrastructure
401 // cron_execute_plugin_type('repository', 'repository plugins');
402 cron_execute_plugin_type('qbehaviour', 'question behaviours');
403 cron_execute_plugin_type('qformat', 'question import/export formats');
404 cron_execute_plugin_type('qtype', 'question types');
405 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
406 cron_execute_plugin_type('theme', 'themes');
407 cron_execute_plugin_type('tool', 'admin tools');
410 // and finally run any local cronjobs, if any
411 if ($locals = get_plugin_list('local')) {
412 mtrace('Processing customized cron scripts ...', '');
413 // new cron functions in lib.php first
414 cron_execute_plugin_type('local');
415 // legacy cron files are executed directly
416 foreach ($locals as $local => $localdir) {
417 if (file_exists("$localdir/cron.php")) {
418 include("$localdir/cron.php");
425 // Run automated backups if required - these may take a long time to execute
426 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
427 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
428 backup_cron_automated_helper::run_automated_backup();
431 // Run stats as at the end because they are known to take very long time on large sites
432 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
433 require_once($CFG->dirroot.'/lib/statslib.php');
434 // check we're not before our runtime
435 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
437 if (time() > $timetocheck) {
438 // process configured number of days as max (defaulting to 31)
439 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
440 if (stats_cron_daily($maxdays)) {
441 if (stats_cron_weekly()) {
442 if (stats_cron_monthly()) {
449 mtrace('Next stats run after:'. userdate($timetocheck));
454 // cleanup file trash - not very important
455 $fs = get_file_storage();
459 mtrace("Cron script completed correctly");
461 $difftime = microtime_diff($starttime, microtime());
462 mtrace("Execution took ".$difftime." seconds");
466 * Executes cron functions for a specific type of plugin.
468 * @param string $plugintype Plugin type (e.g. 'report')
469 * @param string $description If specified, will display 'Starting (whatever)'
470 * and 'Finished (whatever)' lines, otherwise does not display
472 function cron_execute_plugin_type($plugintype, $description = null) {
475 // Get list from plugin => function for all plugins
476 $plugins = get_plugin_list_with_function($plugintype, 'cron');
478 // Modify list for backward compatibility (different files/names)
479 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
481 // Return if no plugins with cron function to process
487 mtrace('Starting '.$description);
490 foreach ($plugins as $component=>$cronfunction) {
491 $dir = get_component_directory($component);
493 // Get cron period if specified in version.php, otherwise assume every cron
495 if (file_exists("$dir/version.php")) {
496 $plugin = new stdClass();
497 include("$dir/version.php");
498 if (isset($plugin->cron)) {
499 $cronperiod = $plugin->cron;
503 // Using last cron and cron period, don't run if it already ran recently
504 $lastcron = get_config($component, 'lastcron');
505 if ($cronperiod && $lastcron) {
506 if ($lastcron + $cronperiod > time()) {
507 // do not execute cron yet
512 mtrace('Processing cron function for ' . $component . '...');
513 $pre_dbqueries = $DB->perf_get_queries();
514 $pre_time = microtime(true);
518 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
519 round(microtime(true) - $pre_time, 2) . " seconds)");
521 set_config('lastcron', time(), $component);
526 mtrace('Finished ' . $description);
531 * Used to add in old-style cron functions within plugins that have not been converted to the
532 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
533 * cron.php and some used a different name.)
535 * @param string $plugintype Plugin type e.g. 'report'
536 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
537 * 'report_frog_cron') for plugin cron functions that were already found using the new API
538 * @return array Revised version of $plugins that adds in any extra plugin functions found by
539 * looking in the older location
541 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
542 global $CFG; // mandatory in case it is referenced by include()d PHP script
544 if ($plugintype === 'report') {
545 // Admin reports only - not course report because course report was
546 // never implemented before, so doesn't need BC
547 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
548 $component = $plugintype . '_' . $pluginname;
549 if (isset($plugins[$component])) {
550 // We already have detected the function using the new API
553 if (!file_exists("$dir/cron.php")) {
554 // No old style cron file present
557 include_once("$dir/cron.php");
558 $cronfunction = $component . '_cron';
559 if (function_exists($cronfunction)) {
560 $plugins[$component] = $cronfunction;
562 debugging("Invalid legacy cron.php detected in $component, " .
563 "please use lib.php instead");
566 } else if (strpos($plugintype, 'grade') === 0) {
567 // Detect old style cron function names
568 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
569 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
570 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
571 $component = $plugintype.'_'.$pluginname;
572 if (isset($plugins[$component])) {
573 // We already have detected the function using the new API
576 if (!file_exists("$dir/lib.php")) {
579 include_once("$dir/lib.php");
580 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
581 $pluginname . '_cron';
582 if (function_exists($cronfunction)) {
583 $plugins[$component] = $cronfunction;
593 * Notify admin users or admin user of any failed logins (since last notification).
595 * Note that this function must be only executed from the cron script
596 * It uses the cache_flags system to store temporary records, deleting them
597 * by name before finishing
599 function notify_login_failures() {
600 global $CFG, $DB, $OUTPUT;
602 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
604 if (empty($CFG->lastnotifyfailure)) {
605 $CFG->lastnotifyfailure=0;
608 // we need to deal with the threshold stuff first.
609 if (empty($CFG->notifyloginthreshold)) {
610 $CFG->notifyloginthreshold = 10; // default to something sensible.
613 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
614 // and insert them into the cache_flags temp table
615 $sql = "SELECT ip, COUNT(*)
617 WHERE module = 'login' AND action = 'error'
620 HAVING COUNT(*) >= ?";
621 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
622 $rs = $DB->get_recordset_sql($sql, $params);
623 foreach ($rs as $iprec) {
624 if (!empty($iprec->ip)) {
625 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
630 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
631 // and insert them into the cache_flags temp table
632 $sql = "SELECT info, count(*)
634 WHERE module = 'login' AND action = 'error'
637 HAVING count(*) >= ?";
638 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
639 $rs = $DB->get_recordset_sql($sql, $params);
640 foreach ($rs as $inforec) {
641 if (!empty($inforec->info)) {
642 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
647 // Now, select all the login error logged records belonging to the ips and infos
648 // since lastnotifyfailure, that we have stored in the cache_flags table
649 $sql = "SELECT l.*, u.firstname, u.lastname
651 JOIN {cache_flags} cf ON l.ip = cf.name
652 LEFT JOIN {user} u ON l.userid = u.id
653 WHERE l.module = 'login' AND l.action = 'error'
655 AND cf.flagtype = 'login_failure_by_ip'
657 SELECT l.*, u.firstname, u.lastname
659 JOIN {cache_flags} cf ON l.info = cf.name
660 LEFT JOIN {user} u ON l.userid = u.id
661 WHERE l.module = 'login' AND l.action = 'error'
663 AND cf.flagtype = 'login_failure_by_info'
665 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
667 // Init some variables
670 // Iterate over the logs recordset
671 $rs = $DB->get_recordset_sql($sql, $params);
672 foreach ($rs as $log) {
673 $log->time = userdate($log->time);
674 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
679 // If we haven't run in the last hour and
680 // we have something useful to report and we
681 // are actually supposed to be reporting to somebody
682 if ((time() - HOURSECS) > $CFG->lastnotifyfailure && $count > 0 && is_array($recip) && count($recip) > 0) {
684 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
685 // Calculate the complete body of notification (start + messages + end)
686 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
687 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
689 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
691 // For each destination, send mail
692 mtrace('Emailing admins about '. $count .' failed login attempts');
693 foreach ($recip as $admin) {
694 //emailing the admins directly rather than putting these through the messaging system
695 email_to_user($admin,get_admin(), $subject, $body);
698 // Update lastnotifyfailure with current time
699 set_config('lastnotifyfailure', time());
702 // Finally, delete all the temp records we have created in cache_flags
703 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");