Merge branch 'MDL-32657-master-1' of git://git.luns.net.uk/moodle
[moodle.git] / lib / cronlib.php
blobf02769d7a39308666f01ed8ddcb3fa094f353f4b
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(time() - $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'));
384 // If enabled, fetch information about available updates and eventually notify site admins
385 require_once($CFG->libdir.'/pluginlib.php');
386 $updateschecker = available_update_checker::instance();
387 $updateschecker->cron();
389 //cleanup old session linked tokens
390 //deletes the session linked tokens that are over a day old.
391 mtrace("Deleting session linked tokens more than one day old...", '');
392 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
393 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
394 mtrace('done.');
397 // all other plugins
398 cron_execute_plugin_type('message', 'message plugins');
399 cron_execute_plugin_type('filter', 'filters');
400 cron_execute_plugin_type('editor', 'editors');
401 cron_execute_plugin_type('format', 'course formats');
402 cron_execute_plugin_type('profilefield', 'profile fields');
403 cron_execute_plugin_type('webservice', 'webservices');
404 // TODO: Repository lib.php files are messed up (include many other files, etc), so it is
405 // currently not possible to implement repository plugin cron using this infrastructure
406 // cron_execute_plugin_type('repository', 'repository plugins');
407 cron_execute_plugin_type('qbehaviour', 'question behaviours');
408 cron_execute_plugin_type('qformat', 'question import/export formats');
409 cron_execute_plugin_type('qtype', 'question types');
410 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
411 cron_execute_plugin_type('theme', 'themes');
412 cron_execute_plugin_type('tool', 'admin tools');
415 // and finally run any local cronjobs, if any
416 if ($locals = get_plugin_list('local')) {
417 mtrace('Processing customized cron scripts ...', '');
418 // new cron functions in lib.php first
419 cron_execute_plugin_type('local');
420 // legacy cron files are executed directly
421 foreach ($locals as $local => $localdir) {
422 if (file_exists("$localdir/cron.php")) {
423 include("$localdir/cron.php");
426 mtrace('done.');
430 // Run automated backups if required - these may take a long time to execute
431 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
432 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
433 backup_cron_automated_helper::run_automated_backup();
436 // Run stats as at the end because they are known to take very long time on large sites
437 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
438 require_once($CFG->dirroot.'/lib/statslib.php');
439 // check we're not before our runtime
440 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
442 if (time() > $timetocheck) {
443 // process configured number of days as max (defaulting to 31)
444 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
445 if (stats_cron_daily($maxdays)) {
446 if (stats_cron_weekly()) {
447 if (stats_cron_monthly()) {
448 stats_clean_old();
452 @set_time_limit(0);
453 } else {
454 mtrace('Next stats run after:'. userdate($timetocheck));
459 // cleanup file trash - not very important
460 $fs = get_file_storage();
461 $fs->cron();
464 mtrace("Cron script completed correctly");
466 $difftime = microtime_diff($starttime, microtime());
467 mtrace("Execution took ".$difftime." seconds");
471 * Executes cron functions for a specific type of plugin.
473 * @param string $plugintype Plugin type (e.g. 'report')
474 * @param string $description If specified, will display 'Starting (whatever)'
475 * and 'Finished (whatever)' lines, otherwise does not display
477 function cron_execute_plugin_type($plugintype, $description = null) {
478 global $DB;
480 // Get list from plugin => function for all plugins
481 $plugins = get_plugin_list_with_function($plugintype, 'cron');
483 // Modify list for backward compatibility (different files/names)
484 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
486 // Return if no plugins with cron function to process
487 if (!$plugins) {
488 return;
491 if ($description) {
492 mtrace('Starting '.$description);
495 foreach ($plugins as $component=>$cronfunction) {
496 $dir = get_component_directory($component);
498 // Get cron period if specified in version.php, otherwise assume every cron
499 $cronperiod = 0;
500 if (file_exists("$dir/version.php")) {
501 $plugin = new stdClass();
502 include("$dir/version.php");
503 if (isset($plugin->cron)) {
504 $cronperiod = $plugin->cron;
508 // Using last cron and cron period, don't run if it already ran recently
509 $lastcron = get_config($component, 'lastcron');
510 if ($cronperiod && $lastcron) {
511 if ($lastcron + $cronperiod > time()) {
512 // do not execute cron yet
513 continue;
517 mtrace('Processing cron function for ' . $component . '...');
518 $pre_dbqueries = $DB->perf_get_queries();
519 $pre_time = microtime(true);
521 $cronfunction();
523 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
524 round(microtime(true) - $pre_time, 2) . " seconds)");
526 set_config('lastcron', time(), $component);
527 @set_time_limit(0);
530 if ($description) {
531 mtrace('Finished ' . $description);
536 * Used to add in old-style cron functions within plugins that have not been converted to the
537 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
538 * cron.php and some used a different name.)
540 * @param string $plugintype Plugin type e.g. 'report'
541 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
542 * 'report_frog_cron') for plugin cron functions that were already found using the new API
543 * @return array Revised version of $plugins that adds in any extra plugin functions found by
544 * looking in the older location
546 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
547 global $CFG; // mandatory in case it is referenced by include()d PHP script
549 if ($plugintype === 'report') {
550 // Admin reports only - not course report because course report was
551 // never implemented before, so doesn't need BC
552 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
553 $component = $plugintype . '_' . $pluginname;
554 if (isset($plugins[$component])) {
555 // We already have detected the function using the new API
556 continue;
558 if (!file_exists("$dir/cron.php")) {
559 // No old style cron file present
560 continue;
562 include_once("$dir/cron.php");
563 $cronfunction = $component . '_cron';
564 if (function_exists($cronfunction)) {
565 $plugins[$component] = $cronfunction;
566 } else {
567 debugging("Invalid legacy cron.php detected in $component, " .
568 "please use lib.php instead");
571 } else if (strpos($plugintype, 'grade') === 0) {
572 // Detect old style cron function names
573 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
574 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
575 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
576 $component = $plugintype.'_'.$pluginname;
577 if (isset($plugins[$component])) {
578 // We already have detected the function using the new API
579 continue;
581 if (!file_exists("$dir/lib.php")) {
582 continue;
584 include_once("$dir/lib.php");
585 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
586 $pluginname . '_cron';
587 if (function_exists($cronfunction)) {
588 $plugins[$component] = $cronfunction;
593 return $plugins;
598 * Notify admin users or admin user of any failed logins (since last notification).
600 * Note that this function must be only executed from the cron script
601 * It uses the cache_flags system to store temporary records, deleting them
602 * by name before finishing
604 function notify_login_failures() {
605 global $CFG, $DB, $OUTPUT;
607 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
609 if (empty($CFG->lastnotifyfailure)) {
610 $CFG->lastnotifyfailure=0;
613 // we need to deal with the threshold stuff first.
614 if (empty($CFG->notifyloginthreshold)) {
615 $CFG->notifyloginthreshold = 10; // default to something sensible.
618 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
619 // and insert them into the cache_flags temp table
620 $sql = "SELECT ip, COUNT(*)
621 FROM {log}
622 WHERE module = 'login' AND action = 'error'
623 AND time > ?
624 GROUP BY ip
625 HAVING COUNT(*) >= ?";
626 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
627 $rs = $DB->get_recordset_sql($sql, $params);
628 foreach ($rs as $iprec) {
629 if (!empty($iprec->ip)) {
630 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
633 $rs->close();
635 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
636 // and insert them into the cache_flags temp table
637 $sql = "SELECT info, count(*)
638 FROM {log}
639 WHERE module = 'login' AND action = 'error'
640 AND time > ?
641 GROUP BY info
642 HAVING count(*) >= ?";
643 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
644 $rs = $DB->get_recordset_sql($sql, $params);
645 foreach ($rs as $inforec) {
646 if (!empty($inforec->info)) {
647 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
650 $rs->close();
652 // Now, select all the login error logged records belonging to the ips and infos
653 // since lastnotifyfailure, that we have stored in the cache_flags table
654 $sql = "SELECT * FROM (
655 SELECT l.*, u.firstname, u.lastname
656 FROM {log} l
657 JOIN {cache_flags} cf ON l.ip = cf.name
658 LEFT JOIN {user} u ON l.userid = u.id
659 WHERE l.module = 'login' AND l.action = 'error'
660 AND l.time > ?
661 AND cf.flagtype = 'login_failure_by_ip'
662 UNION ALL
663 SELECT l.*, u.firstname, u.lastname
664 FROM {log} l
665 JOIN {cache_flags} cf ON l.info = cf.name
666 LEFT JOIN {user} u ON l.userid = u.id
667 WHERE l.module = 'login' AND l.action = 'error'
668 AND l.time > ?
669 AND cf.flagtype = 'login_failure_by_info') t
670 ORDER BY t.time DESC";
671 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
673 // Init some variables
674 $count = 0;
675 $messages = '';
676 // Iterate over the logs recordset
677 $rs = $DB->get_recordset_sql($sql, $params);
678 foreach ($rs as $log) {
679 $log->time = userdate($log->time);
680 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
681 $count++;
683 $rs->close();
685 // If we haven't run in the last hour and
686 // we have something useful to report and we
687 // are actually supposed to be reporting to somebody
688 if ((time() - HOURSECS) > $CFG->lastnotifyfailure && $count > 0 && is_array($recip) && count($recip) > 0) {
689 $site = get_site();
690 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
691 // Calculate the complete body of notification (start + messages + end)
692 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
693 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
694 $messages .
695 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
697 // For each destination, send mail
698 mtrace('Emailing admins about '. $count .' failed login attempts');
699 foreach ($recip as $admin) {
700 //emailing the admins directly rather than putting these through the messaging system
701 email_to_user($admin,get_admin(), $subject, $body);
704 // Update lastnotifyfailure with current time
705 set_config('lastnotifyfailure', time());
708 // Finally, delete all the temp records we have created in cache_flags
709 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");