MDL-31914 db fix - cannot use table aliases on DELETE statements. Credit goes to...
[moodle.git] / lib / cronlib.php
blobec86c67aade245919790ec56e98662ec4bfb1353
1 <?php
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.
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/>.
17 /**
18 * Cron functions.
20 * @package core
21 * @subpackage admin
22 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 /**
27 * Execute cron tasks
29 function cron_run() {
30 global $DB, $CFG, $OUTPUT;
32 if (CLI_MAINTENANCE) {
33 echo "CLI maintenance mode active, cron execution suspended.\n";
34 exit(1);
37 if (moodle_needs_upgrading()) {
38 echo "Moodle upgrade pending, cron execution suspended.\n";
39 exit(1);
42 require_once($CFG->libdir.'/adminlib.php');
43 require_once($CFG->libdir.'/gradelib.php');
45 if (!empty($CFG->showcronsql)) {
46 $DB->set_debug(true);
48 if (!empty($CFG->showcrondebugging)) {
49 $CFG->debug = DEBUG_DEVELOPER;
50 $CFG->debugdisplay = true;
53 set_time_limit(0);
54 $starttime = microtime();
56 // Increase memory limit
57 raise_memory_limit(MEMORY_EXTRA);
59 // Emulate normal session - we use admin accoutn by default
60 cron_setup_user();
62 // Start output log
63 $timenow = time();
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 *
79 FROM {user}
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)");
87 $rs->close();
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 *
95 FROM {user}
96 WHERE confirmed = 1 AND lastaccess > 0
97 AND lastaccess < ? AND deleted = 0
98 AND (lastname = '' OR firstname = '' OR email = '')",
99 array($cuttime));
100 foreach ($rs as $user) {
101 delete_user($user);
102 mtrace(" Deleted not fully setup user $user->username ($user->id)");
104 $rs->close();
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 $loglifetime = get_config('backup', 'loglifetime');
118 if (!empty($loglifetime)) { // Value in days.
119 $loglifetime = $timenow - ($loglifetime * 3600 * 24);
120 // Delete child records from backup_logs.
121 $DB->execute("DELETE FROM {backup_logs}
122 WHERE EXISTS (
123 SELECT 'x'
124 FROM {backup_controllers} bc
125 WHERE bc.backupid = {backup_logs}.backupid
126 AND bc.timecreated < ?)", array($loglifetime));
127 // Delete records from backup_controllers.
128 $DB->execute("DELETE FROM {backup_controllers}
129 WHERE timecreated < ?", array($loglifetime));
130 mtrace(" Deleted old backup records");
134 // Delete old cached texts
135 if (!empty($CFG->cachetext)) { // Defined in config.php
136 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
137 $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
138 mtrace(" Deleted old cache_text records");
142 if (!empty($CFG->usetags)) {
143 require_once($CFG->dirroot.'/tag/lib.php');
144 tag_cron();
145 mtrace(' Executed tag cron');
149 // Context maintenance stuff
150 context_helper::cleanup_instances();
151 mtrace(' Cleaned up context instances');
152 context_helper::build_all_paths(false);
153 // If you suspect that the context paths are somehow corrupt
154 // replace the line below with: context_helper::build_all_paths(true);
155 mtrace(' Built context paths');
158 // Remove expired cache flags
159 gc_cache_flags();
160 mtrace(' Cleaned cache flags');
163 // Cleanup messaging
164 if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
165 $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
166 $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime'=>$notificationdeletetime));
167 mtrace(' Cleaned up read notifications');
170 mtrace("...finished clean-up tasks");
172 } // End of occasional clean-up tasks
175 // Send login failures notification - brute force protection in moodle is weak,
176 // we should at least send notices early in each cron execution
177 if (!empty($CFG->notifyloginfailures)) {
178 notify_login_failures();
179 mtrace(' Notified login failured');
183 // Make sure all context instances are properly created - they may be required in auth, enrol, etc.
184 context_helper::create_instances();
185 mtrace(' Created missing context instances');
188 // Session gc
189 session_gc();
190 mtrace("Cleaned up stale user sessions");
193 // Run the auth cron, if any before enrolments
194 // because it might add users that will be needed in enrol plugins
195 $auths = get_enabled_auth_plugins();
196 mtrace("Running auth crons if required...");
197 foreach ($auths as $auth) {
198 $authplugin = get_auth_plugin($auth);
199 if (method_exists($authplugin, 'cron')) {
200 mtrace("Running cron for auth/$auth...");
201 $authplugin->cron();
202 if (!empty($authplugin->log)) {
203 mtrace($authplugin->log);
206 unset($authplugin);
208 // Generate new password emails for users - ppl expect these generated asap
209 if ($DB->count_records('user_preferences', array('name'=>'create_password', 'value'=>'1'))) {
210 mtrace('Creating passwords for new users...');
211 $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email, u.firstname,
212 u.lastname, u.username,
213 p.id as prefid
214 FROM {user} u
215 JOIN {user_preferences} p ON u.id=p.userid
216 WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin'");
218 // note: we can not send emails to suspended accounts
219 foreach ($newusers as $newuser) {
220 if (setnew_password_and_mail($newuser)) {
221 unset_user_preference('create_password', $newuser);
222 set_user_preference('auth_forcepasswordchange', 1, $newuser);
223 } else {
224 trigger_error("Could not create and mail new user password!");
227 $newusers->close();
231 // It is very important to run enrol early
232 // because other plugins depend on correct enrolment info.
233 mtrace("Running enrol crons if required...");
234 $enrols = enrol_get_plugins(true);
235 foreach($enrols as $ename=>$enrol) {
236 // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
237 if (!$enrol->is_cron_required()) {
238 continue;
240 mtrace("Running cron for enrol_$ename...");
241 $enrol->cron();
242 $enrol->set_config('lastcron', time());
246 // Run all cron jobs for each module
247 mtrace("Starting activity modules");
248 get_mailer('buffer');
249 if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
250 foreach ($mods as $mod) {
251 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
252 if (file_exists($libfile)) {
253 include_once($libfile);
254 $cron_function = $mod->name."_cron";
255 if (function_exists($cron_function)) {
256 mtrace("Processing module function $cron_function ...", '');
257 $pre_dbqueries = null;
258 $pre_dbqueries = $DB->perf_get_queries();
259 $pre_time = microtime(1);
260 if ($cron_function()) {
261 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id));
263 if (isset($pre_dbqueries)) {
264 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
265 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
267 // Reset possible changes by modules to time_limit. MDL-11597
268 @set_time_limit(0);
269 mtrace("done.");
274 get_mailer('close');
275 mtrace("Finished activity modules");
278 mtrace("Starting blocks");
279 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
280 // We will need the base class.
281 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
282 foreach ($blocks as $block) {
283 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
284 if (file_exists($blockfile)) {
285 require_once($blockfile);
286 $classname = 'block_'.$block->name;
287 $blockobj = new $classname;
288 if (method_exists($blockobj,'cron')) {
289 mtrace("Processing cron function for ".$block->name.'....','');
290 if ($blockobj->cron()) {
291 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id));
293 // Reset possible changes by blocks to time_limit. MDL-11597
294 @set_time_limit(0);
295 mtrace('done.');
301 mtrace('Finished blocks');
304 mtrace('Starting admin reports');
305 cron_execute_plugin_type('report');
306 mtrace('Finished admin reports');
309 mtrace('Starting main gradebook job...');
310 grade_cron();
311 mtrace('done.');
314 mtrace('Starting processing the event queue...');
315 events_cron();
316 mtrace('done.');
319 if ($CFG->enablecompletion) {
320 // Completion cron
321 mtrace('Starting the completion cron...');
322 require_once($CFG->libdir . '/completion/cron.php');
323 completion_cron();
324 mtrace('done');
328 if ($CFG->enableportfolios) {
329 // Portfolio cron
330 mtrace('Starting the portfolio cron...');
331 require_once($CFG->libdir . '/portfoliolib.php');
332 portfolio_cron();
333 mtrace('done');
337 //now do plagiarism checks
338 require_once($CFG->libdir.'/plagiarismlib.php');
339 plagiarism_cron();
342 mtrace('Starting course reports');
343 cron_execute_plugin_type('coursereport');
344 mtrace('Finished course reports');
347 // run gradebook import/export/report cron
348 mtrace('Starting gradebook plugins');
349 cron_execute_plugin_type('gradeimport');
350 cron_execute_plugin_type('gradeexport');
351 cron_execute_plugin_type('gradereport');
352 mtrace('Finished gradebook plugins');
355 // Run external blog cron if needed
356 if ($CFG->useexternalblogs) {
357 require_once($CFG->dirroot . '/blog/lib.php');
358 mtrace("Fetching external blog entries...", '');
359 $sql = "timefetched < ? OR timefetched = 0";
360 $externalblogs = $DB->get_records_select('blog_external', $sql, array(mktime() - $CFG->externalblogcrontime));
362 foreach ($externalblogs as $eb) {
363 blog_sync_external_entries($eb);
365 mtrace('done.');
367 // Run blog associations cleanup
368 if ($CFG->useblogassociations) {
369 require_once($CFG->dirroot . '/blog/lib.php');
370 // delete entries whose contextids no longer exists
371 mtrace("Deleting blog associations linked to non-existent contexts...", '');
372 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
373 mtrace('done.');
377 //Run registration updated cron
378 mtrace(get_string('siteupdatesstart', 'hub'));
379 require_once($CFG->dirroot . '/admin/registration/lib.php');
380 $registrationmanager = new registration_manager();
381 $registrationmanager->cron();
382 mtrace(get_string('siteupdatesend', 'hub'));
385 //cleanup old session linked tokens
386 //deletes the session linked tokens that are over a day old.
387 mtrace("Deleting session linked tokens more than one day old...", '');
388 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
389 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
390 mtrace('done.');
393 // all other plugins
394 cron_execute_plugin_type('message', 'message plugins');
395 cron_execute_plugin_type('filter', 'filters');
396 cron_execute_plugin_type('editor', 'editors');
397 cron_execute_plugin_type('format', 'course formats');
398 cron_execute_plugin_type('profilefield', 'profile fields');
399 cron_execute_plugin_type('webservice', 'webservices');
400 // TODO: Repository lib.php files are messed up (include many other files, etc), so it is
401 // currently not possible to implement repository plugin cron using this infrastructure
402 // cron_execute_plugin_type('repository', 'repository plugins');
403 cron_execute_plugin_type('qtype', 'question types');
404 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
405 cron_execute_plugin_type('theme', 'themes');
406 cron_execute_plugin_type('tool', 'admin tools');
409 // and finally run any local cronjobs, if any
410 if ($locals = get_plugin_list('local')) {
411 mtrace('Processing customized cron scripts ...', '');
412 // new cron functions in lib.php first
413 cron_execute_plugin_type('local');
414 // legacy cron files are executed directly
415 foreach ($locals as $local => $localdir) {
416 if (file_exists("$localdir/cron.php")) {
417 include("$localdir/cron.php");
420 mtrace('done.');
424 // Run automated backups if required - these may take a long time to execute
425 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
426 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
427 backup_cron_automated_helper::run_automated_backup();
430 // Run stats as at the end because they are known to take very long time on large sites
431 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
432 require_once($CFG->dirroot.'/lib/statslib.php');
433 // check we're not before our runtime
434 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
436 if (time() > $timetocheck) {
437 // process configured number of days as max (defaulting to 31)
438 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
439 if (stats_cron_daily($maxdays)) {
440 if (stats_cron_weekly()) {
441 if (stats_cron_monthly()) {
442 stats_clean_old();
446 @set_time_limit(0);
447 } else {
448 mtrace('Next stats run after:'. userdate($timetocheck));
453 // cleanup file trash - not very important
454 $fs = get_file_storage();
455 $fs->cron();
458 mtrace("Cron script completed correctly");
460 $difftime = microtime_diff($starttime, microtime());
461 mtrace("Execution took ".$difftime." seconds");
465 * Executes cron functions for a specific type of plugin.
467 * @param string $plugintype Plugin type (e.g. 'report')
468 * @param string $description If specified, will display 'Starting (whatever)'
469 * and 'Finished (whatever)' lines, otherwise does not display
471 function cron_execute_plugin_type($plugintype, $description = null) {
472 global $DB;
474 // Get list from plugin => function for all plugins
475 $plugins = get_plugin_list_with_function($plugintype, 'cron');
477 // Modify list for backward compatibility (different files/names)
478 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
480 // Return if no plugins with cron function to process
481 if (!$plugins) {
482 return;
485 if ($description) {
486 mtrace('Starting '.$description);
489 foreach ($plugins as $component=>$cronfunction) {
490 $dir = get_component_directory($component);
492 // Get cron period if specified in version.php, otherwise assume every cron
493 $cronperiod = 0;
494 if (file_exists("$dir/version.php")) {
495 $plugin = new stdClass();
496 include("$dir/version.php");
497 if (isset($plugin->cron)) {
498 $cronperiod = $plugin->cron;
502 // Using last cron and cron period, don't run if it already ran recently
503 $lastcron = get_config($component, 'lastcron');
504 if ($cronperiod && $lastcron) {
505 if ($lastcron + $cronperiod > time()) {
506 // do not execute cron yet
507 continue;
511 mtrace('Processing cron function for ' . $component . '...');
512 $pre_dbqueries = $DB->perf_get_queries();
513 $pre_time = microtime(true);
515 $cronfunction();
517 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
518 round(microtime(true) - $pre_time, 2) . " seconds)");
520 set_config('lastcron', time(), $component);
521 @set_time_limit(0);
524 if ($description) {
525 mtrace('Finished ' . $description);
530 * Used to add in old-style cron functions within plugins that have not been converted to the
531 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
532 * cron.php and some used a different name.)
534 * @param string $plugintype Plugin type e.g. 'report'
535 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
536 * 'report_frog_cron') for plugin cron functions that were already found using the new API
537 * @return array Revised version of $plugins that adds in any extra plugin functions found by
538 * looking in the older location
540 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
541 global $CFG; // mandatory in case it is referenced by include()d PHP script
543 if ($plugintype === 'report') {
544 // Admin reports only - not course report because course report was
545 // never implemented before, so doesn't need BC
546 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
547 $component = $plugintype . '_' . $pluginname;
548 if (isset($plugins[$component])) {
549 // We already have detected the function using the new API
550 continue;
552 if (!file_exists("$dir/cron.php")) {
553 // No old style cron file present
554 continue;
556 include_once("$dir/cron.php");
557 $cronfunction = $component . '_cron';
558 if (function_exists($cronfunction)) {
559 $plugins[$component] = $cronfunction;
560 } else {
561 debugging("Invalid legacy cron.php detected in $component, " .
562 "please use lib.php instead");
565 } else if (strpos($plugintype, 'grade') === 0) {
566 // Detect old style cron function names
567 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
568 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
569 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
570 $component = $plugintype.'_'.$pluginname;
571 if (isset($plugins[$component])) {
572 // We already have detected the function using the new API
573 continue;
575 if (!file_exists("$dir/lib.php")) {
576 continue;
578 include_once("$dir/lib.php");
579 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
580 $pluginname . '_cron';
581 if (function_exists($cronfunction)) {
582 $plugins[$component] = $cronfunction;
587 return $plugins;
592 * Notify admin users or admin user of any failed logins (since last notification).
594 * Note that this function must be only executed from the cron script
595 * It uses the cache_flags system to store temporary records, deleting them
596 * by name before finishing
598 function notify_login_failures() {
599 global $CFG, $DB, $OUTPUT;
601 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
603 if (empty($CFG->lastnotifyfailure)) {
604 $CFG->lastnotifyfailure=0;
607 // we need to deal with the threshold stuff first.
608 if (empty($CFG->notifyloginthreshold)) {
609 $CFG->notifyloginthreshold = 10; // default to something sensible.
612 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
613 // and insert them into the cache_flags temp table
614 $sql = "SELECT ip, COUNT(*)
615 FROM {log}
616 WHERE module = 'login' AND action = 'error'
617 AND time > ?
618 GROUP BY ip
619 HAVING COUNT(*) >= ?";
620 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
621 $rs = $DB->get_recordset_sql($sql, $params);
622 foreach ($rs as $iprec) {
623 if (!empty($iprec->ip)) {
624 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
627 $rs->close();
629 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
630 // and insert them into the cache_flags temp table
631 $sql = "SELECT info, count(*)
632 FROM {log}
633 WHERE module = 'login' AND action = 'error'
634 AND time > ?
635 GROUP BY info
636 HAVING count(*) >= ?";
637 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
638 $rs = $DB->get_recordset_sql($sql, $params);
639 foreach ($rs as $inforec) {
640 if (!empty($inforec->info)) {
641 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
644 $rs->close();
646 // Now, select all the login error logged records belonging to the ips and infos
647 // since lastnotifyfailure, that we have stored in the cache_flags table
648 $sql = "SELECT * FROM (
649 SELECT l.*, u.firstname, u.lastname
650 FROM {log} l
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'
654 AND l.time > ?
655 AND cf.flagtype = 'login_failure_by_ip'
656 UNION ALL
657 SELECT l.*, u.firstname, u.lastname
658 FROM {log} l
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'
662 AND l.time > ?
663 AND cf.flagtype = 'login_failure_by_info') t
664 ORDER BY t.time DESC";
665 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
667 // Init some variables
668 $count = 0;
669 $messages = '';
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";
675 $count++;
677 $rs->close();
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) {
683 $site = get_site();
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" .
688 $messages .
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')");