MDL-33318 lib : code style fix
[moodle.git] / lib / cronlib.php
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.
13 //
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.
19  *
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
24  */
26 /**
27  * Execute cron tasks
28  */
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);
35     }
37     if (moodle_needs_upgrading()) {
38         echo "Moodle upgrade pending, cron execution suspended.\n";
39         exit(1);
40     }
42     require_once($CFG->libdir.'/adminlib.php');
43     require_once($CFG->libdir.'/gradelib.php');
45     if (!empty($CFG->showcronsql)) {
46         $DB->set_debug(true);
47     }
48     if (!empty($CFG->showcrondebugging)) {
49         $CFG->debug = DEBUG_DEVELOPER;
50         $CFG->debugdisplay = true;
51     }
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)");
86             }
87             $rs->close();
88         }
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)");
103             }
104             $rs->close();
105         }
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");
113         }
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");
131         }
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");
139         }
142         if (!empty($CFG->usetags)) {
143             require_once($CFG->dirroot.'/tag/lib.php');
144             tag_cron();
145             mtrace(' Executed tag cron');
146         }
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');
168         }
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');
180     }
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);
204             }
205         }
206         unset($authplugin);
207     }
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!");
225             }
226         }
227         $newusers->close();
228     }
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;
239         }
240         mtrace("Running cron for enrol_$ename...");
241         $enrol->cron();
242         $enrol->set_config('lastcron', time());
243     }
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));
262                     }
263                     if (isset($pre_dbqueries)) {
264                         mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
265                         mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
266                     }
267                     // Reset possible changes by modules to time_limit. MDL-11597
268                     @set_time_limit(0);
269                     mtrace("done.");
270                 }
271             }
272         }
273     }
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));
292                     }
293                     // Reset possible changes by blocks to time_limit. MDL-11597
294                     @set_time_limit(0);
295                     mtrace('done.');
296                 }
297             }
299         }
300     }
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');
325     }
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');
334     }
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);
364         }
365         mtrace('done.');
366     }
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.');
374     }
377     //Run registration updated cron
378     mtrace(get_string('siteupdatesstart', 'hub'));
379     require_once($CFG->dirroot . '/' . $CFG->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     if (empty($CFG->disableupdatenotifications)) {
386         require_once($CFG->libdir.'/pluginlib.php');
387         $updateschecker = available_update_checker::instance();
388         $updateschecker->cron();
389     }
391     //cleanup old session linked tokens
392     //deletes the session linked tokens that are over a day old.
393     mtrace("Deleting session linked tokens more than one day old...", '');
394     $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
395                     array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
396     mtrace('done.');
399     // all other plugins
400     cron_execute_plugin_type('message', 'message plugins');
401     cron_execute_plugin_type('filter', 'filters');
402     cron_execute_plugin_type('editor', 'editors');
403     cron_execute_plugin_type('format', 'course formats');
404     cron_execute_plugin_type('profilefield', 'profile fields');
405     cron_execute_plugin_type('webservice', 'webservices');
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");
424             }
425         }
426         mtrace('done.');
427     }
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();
449                     }
450                 }
451             }
452             @set_time_limit(0);
453         } else {
454             mtrace('Next stats run after:'. userdate($timetocheck));
455         }
456     }
459     // cleanup file trash - not very important
460     $fs = get_file_storage();
461     $fs->cron();
463     mtrace("Clean up cached external files");
464     // 1 week
465     cache_file::cleanup(array(), 60 * 60 * 24 * 7);
467     mtrace("Cron script completed correctly");
469     $difftime = microtime_diff($starttime, microtime());
470     mtrace("Execution took ".$difftime." seconds");
473 /**
474  * Executes cron functions for a specific type of plugin.
475  *
476  * @param string $plugintype Plugin type (e.g. 'report')
477  * @param string $description If specified, will display 'Starting (whatever)'
478  *   and 'Finished (whatever)' lines, otherwise does not display
479  */
480 function cron_execute_plugin_type($plugintype, $description = null) {
481     global $DB;
483     // Get list from plugin => function for all plugins
484     $plugins = get_plugin_list_with_function($plugintype, 'cron');
486     // Modify list for backward compatibility (different files/names)
487     $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
489     // Return if no plugins with cron function to process
490     if (!$plugins) {
491         return;
492     }
494     if ($description) {
495         mtrace('Starting '.$description);
496     }
498     foreach ($plugins as $component=>$cronfunction) {
499         $dir = get_component_directory($component);
501         // Get cron period if specified in version.php, otherwise assume every cron
502         $cronperiod = 0;
503         if (file_exists("$dir/version.php")) {
504             $plugin = new stdClass();
505             include("$dir/version.php");
506             if (isset($plugin->cron)) {
507                 $cronperiod = $plugin->cron;
508             }
509         }
511         // Using last cron and cron period, don't run if it already ran recently
512         $lastcron = get_config($component, 'lastcron');
513         if ($cronperiod && $lastcron) {
514             if ($lastcron + $cronperiod > time()) {
515                 // do not execute cron yet
516                 continue;
517             }
518         }
520         mtrace('Processing cron function for ' . $component . '...');
521         $pre_dbqueries = $DB->perf_get_queries();
522         $pre_time = microtime(true);
524         $cronfunction();
526         mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
527                 round(microtime(true) - $pre_time, 2) . " seconds)");
529         set_config('lastcron', time(), $component);
530         @set_time_limit(0);
531     }
533     if ($description) {
534         mtrace('Finished ' . $description);
535     }
538 /**
539  * Used to add in old-style cron functions within plugins that have not been converted to the
540  * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
541  * cron.php and some used a different name.)
542  *
543  * @param string $plugintype Plugin type e.g. 'report'
544  * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
545  *   'report_frog_cron') for plugin cron functions that were already found using the new API
546  * @return array Revised version of $plugins that adds in any extra plugin functions found by
547  *   looking in the older location
548  */
549 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
550     global $CFG; // mandatory in case it is referenced by include()d PHP script
552     if ($plugintype === 'report') {
553         // Admin reports only - not course report because course report was
554         // never implemented before, so doesn't need BC
555         foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
556             $component = $plugintype . '_' . $pluginname;
557             if (isset($plugins[$component])) {
558                 // We already have detected the function using the new API
559                 continue;
560             }
561             if (!file_exists("$dir/cron.php")) {
562                 // No old style cron file present
563                 continue;
564             }
565             include_once("$dir/cron.php");
566             $cronfunction = $component . '_cron';
567             if (function_exists($cronfunction)) {
568                 $plugins[$component] = $cronfunction;
569             } else {
570                 debugging("Invalid legacy cron.php detected in $component, " .
571                         "please use lib.php instead");
572             }
573         }
574     } else if (strpos($plugintype, 'grade') === 0) {
575         // Detect old style cron function names
576         // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
577         // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
578         foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
579             $component = $plugintype.'_'.$pluginname;
580             if (isset($plugins[$component])) {
581                 // We already have detected the function using the new API
582                 continue;
583             }
584             if (!file_exists("$dir/lib.php")) {
585                 continue;
586             }
587             include_once("$dir/lib.php");
588             $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
589                     $pluginname . '_cron';
590             if (function_exists($cronfunction)) {
591                 $plugins[$component] = $cronfunction;
592             }
593         }
594     }
596     return $plugins;
600 /**
601  * Notify admin users or admin user of any failed logins (since last notification).
602  *
603  * Note that this function must be only executed from the cron script
604  * It uses the cache_flags system to store temporary records, deleting them
605  * by name before finishing
606  */
607 function notify_login_failures() {
608     global $CFG, $DB, $OUTPUT;
610     $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
612     if (empty($CFG->lastnotifyfailure)) {
613         $CFG->lastnotifyfailure=0;
614     }
616     // we need to deal with the threshold stuff first.
617     if (empty($CFG->notifyloginthreshold)) {
618         $CFG->notifyloginthreshold = 10; // default to something sensible.
619     }
621     // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
622     // and insert them into the cache_flags temp table
623     $sql = "SELECT ip, COUNT(*)
624               FROM {log}
625              WHERE module = 'login' AND action = 'error'
626                    AND time > ?
627           GROUP BY ip
628             HAVING COUNT(*) >= ?";
629     $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
630     $rs = $DB->get_recordset_sql($sql, $params);
631     foreach ($rs as $iprec) {
632         if (!empty($iprec->ip)) {
633             set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
634         }
635     }
636     $rs->close();
638     // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
639     // and insert them into the cache_flags temp table
640     $sql = "SELECT info, count(*)
641               FROM {log}
642              WHERE module = 'login' AND action = 'error'
643                    AND time > ?
644           GROUP BY info
645             HAVING count(*) >= ?";
646     $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
647     $rs = $DB->get_recordset_sql($sql, $params);
648     foreach ($rs as $inforec) {
649         if (!empty($inforec->info)) {
650             set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
651         }
652     }
653     $rs->close();
655     // Now, select all the login error logged records belonging to the ips and infos
656     // since lastnotifyfailure, that we have stored in the cache_flags table
657     $sql = "SELECT * FROM (
658         SELECT l.*, u.firstname, u.lastname
659               FROM {log} l
660               JOIN {cache_flags} cf ON l.ip = cf.name
661          LEFT JOIN {user} u         ON l.userid = u.id
662              WHERE l.module = 'login' AND l.action = 'error'
663                    AND l.time > ?
664                    AND cf.flagtype = 'login_failure_by_ip'
665         UNION ALL
666             SELECT l.*, u.firstname, u.lastname
667               FROM {log} l
668               JOIN {cache_flags} cf ON l.info = cf.name
669          LEFT JOIN {user} u         ON l.userid = u.id
670              WHERE l.module = 'login' AND l.action = 'error'
671                    AND l.time > ?
672                    AND cf.flagtype = 'login_failure_by_info') t
673         ORDER BY t.time DESC";
674     $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
676     // Init some variables
677     $count = 0;
678     $messages = '';
679     // Iterate over the logs recordset
680     $rs = $DB->get_recordset_sql($sql, $params);
681     foreach ($rs as $log) {
682         $log->time = userdate($log->time);
683         $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
684         $count++;
685     }
686     $rs->close();
688     // If we haven't run in the last hour and
689     // we have something useful to report and we
690     // are actually supposed to be reporting to somebody
691     if ((time() - HOURSECS) > $CFG->lastnotifyfailure && $count > 0 && is_array($recip) && count($recip) > 0) {
692         $site = get_site();
693         $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
694         // Calculate the complete body of notification (start + messages + end)
695         $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
696                 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
697                 $messages .
698                 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
700         // For each destination, send mail
701         mtrace('Emailing admins about '. $count .' failed login attempts');
702         foreach ($recip as $admin) {
703             //emailing the admins directly rather than putting these through the messaging system
704             email_to_user($admin,get_admin(), $subject, $body);
705         }
707         // Update lastnotifyfailure with current time
708         set_config('lastnotifyfailure', time());
709     }
711     // Finally, delete all the temp records we have created in cache_flags
712     $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");