MDL-38311 question manual grading: comment fixes.
[moodle.git] / lib / cronlib.php
blob79e808bd4d3e9f73378d2c39e23e98a1398ece48
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 (notify_login_failures()) {
178 mtrace(' Notified login failures');
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');
187 // Session gc
188 session_gc();
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...");
200 $authplugin->cron();
201 if (!empty($authplugin->log)) {
202 mtrace($authplugin->log);
205 unset($authplugin);
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, u.lang,
212 p.id as prefid
213 FROM {user} u
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' AND u.deleted = 0");
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);
222 } else {
223 trigger_error("Could not create and mail new user password!");
226 $newusers->close();
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()) {
237 continue;
239 mtrace("Running cron for enrol_$ename...");
240 $enrol->cron();
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
267 @set_time_limit(0);
268 mtrace("done.");
273 get_mailer('close');
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
293 @set_time_limit(0);
294 mtrace('done.');
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...');
309 grade_cron();
310 mtrace('done.');
313 mtrace('Starting processing the event queue...');
314 events_cron();
315 mtrace('done.');
318 if ($CFG->enablecompletion) {
319 // Completion cron
320 mtrace('Starting the completion cron...');
321 require_once($CFG->dirroot.'/completion/cron.php');
322 completion_cron();
323 mtrace('done');
327 if ($CFG->enableportfolios) {
328 // Portfolio cron
329 mtrace('Starting the portfolio cron...');
330 require_once($CFG->libdir . '/portfoliolib.php');
331 portfolio_cron();
332 mtrace('done');
336 //now do plagiarism checks
337 require_once($CFG->libdir.'/plagiarismlib.php');
338 plagiarism_cron();
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');
353 // run calendar cron
354 require_once "{$CFG->dirroot}/calendar/lib.php";
355 calendar_cron();
357 // Run external blog cron if needed
358 if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
359 require_once($CFG->dirroot . '/blog/lib.php');
360 mtrace("Fetching external blog entries...", '');
361 $sql = "timefetched < ? OR timefetched = 0";
362 $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
364 foreach ($externalblogs as $eb) {
365 blog_sync_external_entries($eb);
367 mtrace('done.');
369 // Run blog associations cleanup
370 if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
371 require_once($CFG->dirroot . '/blog/lib.php');
372 // delete entries whose contextids no longer exists
373 mtrace("Deleting blog associations linked to non-existent contexts...", '');
374 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
375 mtrace('done.');
379 // Run question bank clean-up.
380 mtrace("Starting the question bank cron...", '');
381 require_once($CFG->libdir . '/questionlib.php');
382 question_bank::cron();
383 mtrace('done.');
386 //Run registration updated cron
387 mtrace(get_string('siteupdatesstart', 'hub'));
388 require_once($CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php');
389 $registrationmanager = new registration_manager();
390 $registrationmanager->cron();
391 mtrace(get_string('siteupdatesend', 'hub'));
393 // If enabled, fetch information about available updates and eventually notify site admins
394 if (empty($CFG->disableupdatenotifications)) {
395 require_once($CFG->libdir.'/pluginlib.php');
396 $updateschecker = available_update_checker::instance();
397 $updateschecker->cron();
400 //cleanup old session linked tokens
401 //deletes the session linked tokens that are over a day old.
402 mtrace("Deleting session linked tokens more than one day old...", '');
403 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
404 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
405 mtrace('done.');
408 // all other plugins
409 cron_execute_plugin_type('message', 'message plugins');
410 cron_execute_plugin_type('filter', 'filters');
411 cron_execute_plugin_type('editor', 'editors');
412 cron_execute_plugin_type('format', 'course formats');
413 cron_execute_plugin_type('profilefield', 'profile fields');
414 cron_execute_plugin_type('webservice', 'webservices');
415 cron_execute_plugin_type('repository', 'repository plugins');
416 cron_execute_plugin_type('qbehaviour', 'question behaviours');
417 cron_execute_plugin_type('qformat', 'question import/export formats');
418 cron_execute_plugin_type('qtype', 'question types');
419 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
420 cron_execute_plugin_type('theme', 'themes');
421 cron_execute_plugin_type('tool', 'admin tools');
424 // and finally run any local cronjobs, if any
425 if ($locals = get_plugin_list('local')) {
426 mtrace('Processing customized cron scripts ...', '');
427 // new cron functions in lib.php first
428 cron_execute_plugin_type('local');
429 // legacy cron files are executed directly
430 foreach ($locals as $local => $localdir) {
431 if (file_exists("$localdir/cron.php")) {
432 include("$localdir/cron.php");
435 mtrace('done.');
439 // Run automated backups if required - these may take a long time to execute
440 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
441 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
442 backup_cron_automated_helper::run_automated_backup();
445 // Run stats as at the end because they are known to take very long time on large sites
446 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
447 require_once($CFG->dirroot.'/lib/statslib.php');
448 // check we're not before our runtime
449 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
451 if (time() > $timetocheck) {
452 // process configured number of days as max (defaulting to 31)
453 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
454 if (stats_cron_daily($maxdays)) {
455 if (stats_cron_weekly()) {
456 if (stats_cron_monthly()) {
457 stats_clean_old();
461 @set_time_limit(0);
462 } else {
463 mtrace('Next stats run after:'. userdate($timetocheck));
468 // cleanup file trash - not very important
469 $fs = get_file_storage();
470 $fs->cron();
472 mtrace("Cron script completed correctly");
474 $difftime = microtime_diff($starttime, microtime());
475 mtrace("Execution took ".$difftime." seconds");
479 * Executes cron functions for a specific type of plugin.
481 * @param string $plugintype Plugin type (e.g. 'report')
482 * @param string $description If specified, will display 'Starting (whatever)'
483 * and 'Finished (whatever)' lines, otherwise does not display
485 function cron_execute_plugin_type($plugintype, $description = null) {
486 global $DB;
488 // Get list from plugin => function for all plugins
489 $plugins = get_plugin_list_with_function($plugintype, 'cron');
491 // Modify list for backward compatibility (different files/names)
492 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
494 // Return if no plugins with cron function to process
495 if (!$plugins) {
496 return;
499 if ($description) {
500 mtrace('Starting '.$description);
503 foreach ($plugins as $component=>$cronfunction) {
504 $dir = get_component_directory($component);
506 // Get cron period if specified in version.php, otherwise assume every cron
507 $cronperiod = 0;
508 if (file_exists("$dir/version.php")) {
509 $plugin = new stdClass();
510 include("$dir/version.php");
511 if (isset($plugin->cron)) {
512 $cronperiod = $plugin->cron;
516 // Using last cron and cron period, don't run if it already ran recently
517 $lastcron = get_config($component, 'lastcron');
518 if ($cronperiod && $lastcron) {
519 if ($lastcron + $cronperiod > time()) {
520 // do not execute cron yet
521 continue;
525 mtrace('Processing cron function for ' . $component . '...');
526 $pre_dbqueries = $DB->perf_get_queries();
527 $pre_time = microtime(true);
529 $cronfunction();
531 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
532 round(microtime(true) - $pre_time, 2) . " seconds)");
534 set_config('lastcron', time(), $component);
535 @set_time_limit(0);
538 if ($description) {
539 mtrace('Finished ' . $description);
544 * Used to add in old-style cron functions within plugins that have not been converted to the
545 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
546 * cron.php and some used a different name.)
548 * @param string $plugintype Plugin type e.g. 'report'
549 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
550 * 'report_frog_cron') for plugin cron functions that were already found using the new API
551 * @return array Revised version of $plugins that adds in any extra plugin functions found by
552 * looking in the older location
554 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
555 global $CFG; // mandatory in case it is referenced by include()d PHP script
557 if ($plugintype === 'report') {
558 // Admin reports only - not course report because course report was
559 // never implemented before, so doesn't need BC
560 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
561 $component = $plugintype . '_' . $pluginname;
562 if (isset($plugins[$component])) {
563 // We already have detected the function using the new API
564 continue;
566 if (!file_exists("$dir/cron.php")) {
567 // No old style cron file present
568 continue;
570 include_once("$dir/cron.php");
571 $cronfunction = $component . '_cron';
572 if (function_exists($cronfunction)) {
573 $plugins[$component] = $cronfunction;
574 } else {
575 debugging("Invalid legacy cron.php detected in $component, " .
576 "please use lib.php instead");
579 } else if (strpos($plugintype, 'grade') === 0) {
580 // Detect old style cron function names
581 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
582 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
583 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
584 $component = $plugintype.'_'.$pluginname;
585 if (isset($plugins[$component])) {
586 // We already have detected the function using the new API
587 continue;
589 if (!file_exists("$dir/lib.php")) {
590 continue;
592 include_once("$dir/lib.php");
593 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
594 $pluginname . '_cron';
595 if (function_exists($cronfunction)) {
596 $plugins[$component] = $cronfunction;
601 return $plugins;
606 * Notify admin users or admin user of any failed logins (since last notification).
608 * Note that this function must be only executed from the cron script
609 * It uses the cache_flags system to store temporary records, deleting them
610 * by name before finishing
612 * @return bool True if executed, false if not
614 function notify_login_failures() {
615 global $CFG, $DB, $OUTPUT;
617 if (empty($CFG->notifyloginfailures)) {
618 return false;
621 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
623 if (empty($CFG->lastnotifyfailure)) {
624 $CFG->lastnotifyfailure=0;
627 // If it has been less than an hour, or if there are no recipients, don't execute.
628 if (((time() - HOURSECS) < $CFG->lastnotifyfailure) || !is_array($recip) || count($recip) <= 0) {
629 return false;
632 // we need to deal with the threshold stuff first.
633 if (empty($CFG->notifyloginthreshold)) {
634 $CFG->notifyloginthreshold = 10; // default to something sensible.
637 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
638 // and insert them into the cache_flags temp table
639 $sql = "SELECT ip, COUNT(*)
640 FROM {log}
641 WHERE module = 'login' AND action = 'error'
642 AND time > ?
643 GROUP BY ip
644 HAVING COUNT(*) >= ?";
645 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
646 $rs = $DB->get_recordset_sql($sql, $params);
647 foreach ($rs as $iprec) {
648 if (!empty($iprec->ip)) {
649 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
652 $rs->close();
654 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
655 // and insert them into the cache_flags temp table
656 $sql = "SELECT info, count(*)
657 FROM {log}
658 WHERE module = 'login' AND action = 'error'
659 AND time > ?
660 GROUP BY info
661 HAVING count(*) >= ?";
662 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
663 $rs = $DB->get_recordset_sql($sql, $params);
664 foreach ($rs as $inforec) {
665 if (!empty($inforec->info)) {
666 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
669 $rs->close();
671 // Now, select all the login error logged records belonging to the ips and infos
672 // since lastnotifyfailure, that we have stored in the cache_flags table
673 $sql = "SELECT * FROM (
674 SELECT l.*, u.firstname, u.lastname
675 FROM {log} l
676 JOIN {cache_flags} cf ON l.ip = cf.name
677 LEFT JOIN {user} u ON l.userid = u.id
678 WHERE l.module = 'login' AND l.action = 'error'
679 AND l.time > ?
680 AND cf.flagtype = 'login_failure_by_ip'
681 UNION ALL
682 SELECT l.*, u.firstname, u.lastname
683 FROM {log} l
684 JOIN {cache_flags} cf ON l.info = cf.name
685 LEFT JOIN {user} u ON l.userid = u.id
686 WHERE l.module = 'login' AND l.action = 'error'
687 AND l.time > ?
688 AND cf.flagtype = 'login_failure_by_info') t
689 ORDER BY t.time DESC";
690 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
692 // Init some variables
693 $count = 0;
694 $messages = '';
695 // Iterate over the logs recordset
696 $rs = $DB->get_recordset_sql($sql, $params);
697 foreach ($rs as $log) {
698 $log->time = userdate($log->time);
699 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
700 $count++;
702 $rs->close();
704 // If we have something useful to report.
705 if ($count > 0) {
706 $site = get_site();
707 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
708 // Calculate the complete body of notification (start + messages + end)
709 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
710 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
711 $messages .
712 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
714 // For each destination, send mail
715 mtrace('Emailing admins about '. $count .' failed login attempts');
716 foreach ($recip as $admin) {
717 //emailing the admins directly rather than putting these through the messaging system
718 email_to_user($admin, generate_email_supportuser(), $subject, $body);
722 // Update lastnotifyfailure with current time
723 set_config('lastnotifyfailure', time());
725 // Finally, delete all the temp records we have created in cache_flags
726 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
728 return true;