MDL-41623 ensure all rss links are valid urls.
[moodle.git] / lib / cronlib.php
blob0e7bbe148aca628fae98fe6ea176f45da5e6a3bc
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...");
74 cron_trace_time_and_memory();
76 // Delete users who haven't confirmed within required period
77 if (!empty($CFG->deleteunconfirmed)) {
78 $cuttime = $timenow - ($CFG->deleteunconfirmed * 3600);
79 $rs = $DB->get_recordset_sql ("SELECT *
80 FROM {user}
81 WHERE confirmed = 0 AND firstaccess > 0
82 AND firstaccess < ?", array($cuttime));
83 foreach ($rs as $user) {
84 delete_user($user); // we MUST delete user properly first
85 $DB->delete_records('user', array('id'=>$user->id)); // this is a bloody hack, but it might work
86 mtrace(" Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
88 $rs->close();
92 // Delete users who haven't completed profile within required period
93 if (!empty($CFG->deleteincompleteusers)) {
94 $cuttime = $timenow - ($CFG->deleteincompleteusers * 3600);
95 $rs = $DB->get_recordset_sql ("SELECT *
96 FROM {user}
97 WHERE confirmed = 1 AND lastaccess > 0
98 AND lastaccess < ? AND deleted = 0
99 AND (lastname = '' OR firstname = '' OR email = '')",
100 array($cuttime));
101 foreach ($rs as $user) {
102 if (isguestuser($user) or is_siteadmin($user)) {
103 continue;
105 delete_user($user);
106 mtrace(" Deleted not fully setup user $user->username ($user->id)");
108 $rs->close();
112 // Delete old logs to save space (this might need a timer to slow it down...)
113 if (!empty($CFG->loglifetime)) { // value in days
114 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
115 $DB->delete_records_select("log", "time < ?", array($loglifetime));
116 mtrace(" Deleted old log records");
120 // Delete old backup_controllers and logs.
121 $loglifetime = get_config('backup', 'loglifetime');
122 if (!empty($loglifetime)) { // Value in days.
123 $loglifetime = $timenow - ($loglifetime * 3600 * 24);
124 // Delete child records from backup_logs.
125 $DB->execute("DELETE FROM {backup_logs}
126 WHERE EXISTS (
127 SELECT 'x'
128 FROM {backup_controllers} bc
129 WHERE bc.backupid = {backup_logs}.backupid
130 AND bc.timecreated < ?)", array($loglifetime));
131 // Delete records from backup_controllers.
132 $DB->execute("DELETE FROM {backup_controllers}
133 WHERE timecreated < ?", array($loglifetime));
134 mtrace(" Deleted old backup records");
138 // Delete old cached texts
139 if (!empty($CFG->cachetext)) { // Defined in config.php
140 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
141 $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
142 mtrace(" Deleted old cache_text records");
146 if (!empty($CFG->usetags)) {
147 require_once($CFG->dirroot.'/tag/lib.php');
148 tag_cron();
149 mtrace(' Executed tag cron');
153 // Context maintenance stuff
154 context_helper::cleanup_instances();
155 mtrace(' Cleaned up context instances');
156 context_helper::build_all_paths(false);
157 // If you suspect that the context paths are somehow corrupt
158 // replace the line below with: context_helper::build_all_paths(true);
159 mtrace(' Built context paths');
162 // Remove expired cache flags
163 gc_cache_flags();
164 mtrace(' Cleaned cache flags');
167 // Cleanup messaging
168 if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
169 $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
170 $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime'=>$notificationdeletetime));
171 mtrace(' Cleaned up read notifications');
174 mtrace("...finished clean-up tasks");
176 } // End of occasional clean-up tasks
179 // Send login failures notification - brute force protection in moodle is weak,
180 // we should at least send notices early in each cron execution
181 if (notify_login_failures()) {
182 mtrace(' Notified login failures');
186 // Make sure all context instances are properly created - they may be required in auth, enrol, etc.
187 context_helper::create_instances();
188 mtrace(' Created missing context instances');
191 // Session gc
192 session_gc();
193 mtrace("Cleaned up stale user sessions");
196 // Run the auth cron, if any before enrolments
197 // because it might add users that will be needed in enrol plugins
198 $auths = get_enabled_auth_plugins();
199 mtrace("Running auth crons if required...");
200 cron_trace_time_and_memory();
201 foreach ($auths as $auth) {
202 $authplugin = get_auth_plugin($auth);
203 if (method_exists($authplugin, 'cron')) {
204 mtrace("Running cron for auth/$auth...");
205 $authplugin->cron();
206 if (!empty($authplugin->log)) {
207 mtrace($authplugin->log);
210 unset($authplugin);
212 // Generate new password emails for users - ppl expect these generated asap
213 if ($DB->count_records('user_preferences', array('name'=>'create_password', 'value'=>'1'))) {
214 mtrace('Creating passwords for new users...');
215 $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email, u.firstname,
216 u.lastname, u.username, u.lang,
217 p.id as prefid
218 FROM {user} u
219 JOIN {user_preferences} p ON u.id=p.userid
220 WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0");
222 // note: we can not send emails to suspended accounts
223 foreach ($newusers as $newuser) {
224 // Use a low cost factor when generating bcrypt hash otherwise
225 // hashing would be slow when emailing lots of users. Hashes
226 // will be automatically updated to a higher cost factor the first
227 // time the user logs in.
228 if (setnew_password_and_mail($newuser, true)) {
229 unset_user_preference('create_password', $newuser);
230 set_user_preference('auth_forcepasswordchange', 1, $newuser);
231 } else {
232 trigger_error("Could not create and mail new user password!");
235 $newusers->close();
239 // It is very important to run enrol early
240 // because other plugins depend on correct enrolment info.
241 mtrace("Running enrol crons if required...");
242 $enrols = enrol_get_plugins(true);
243 foreach($enrols as $ename=>$enrol) {
244 // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
245 if (!$enrol->is_cron_required()) {
246 continue;
248 mtrace("Running cron for enrol_$ename...");
249 cron_trace_time_and_memory();
250 $enrol->cron();
251 $enrol->set_config('lastcron', time());
255 // Run all cron jobs for each module
256 mtrace("Starting activity modules");
257 get_mailer('buffer');
258 if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
259 foreach ($mods as $mod) {
260 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
261 if (file_exists($libfile)) {
262 include_once($libfile);
263 $cron_function = $mod->name."_cron";
264 if (function_exists($cron_function)) {
265 mtrace("Processing module function $cron_function ...", '');
266 cron_trace_time_and_memory();
267 $pre_dbqueries = null;
268 $pre_dbqueries = $DB->perf_get_queries();
269 $pre_time = microtime(1);
270 if ($cron_function()) {
271 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id));
273 if (isset($pre_dbqueries)) {
274 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
275 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
277 // Reset possible changes by modules to time_limit. MDL-11597
278 @set_time_limit(0);
279 mtrace("done.");
284 get_mailer('close');
285 mtrace("Finished activity modules");
288 mtrace("Starting blocks");
289 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
290 // We will need the base class.
291 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
292 foreach ($blocks as $block) {
293 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
294 if (file_exists($blockfile)) {
295 require_once($blockfile);
296 $classname = 'block_'.$block->name;
297 $blockobj = new $classname;
298 if (method_exists($blockobj,'cron')) {
299 mtrace("Processing cron function for ".$block->name.'....','');
300 cron_trace_time_and_memory();
301 if ($blockobj->cron()) {
302 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id));
304 // Reset possible changes by blocks to time_limit. MDL-11597
305 @set_time_limit(0);
306 mtrace('done.');
312 mtrace('Finished blocks');
315 mtrace('Starting admin reports');
316 cron_execute_plugin_type('report');
317 mtrace('Finished admin reports');
320 mtrace('Starting main gradebook job...');
321 cron_trace_time_and_memory();
322 grade_cron();
323 mtrace('done.');
326 mtrace('Starting processing the event queue...');
327 cron_trace_time_and_memory();
328 events_cron();
329 mtrace('done.');
332 if ($CFG->enablecompletion) {
333 // Completion cron
334 mtrace('Starting the completion cron...');
335 cron_trace_time_and_memory();
336 require_once($CFG->dirroot.'/completion/cron.php');
337 completion_cron();
338 mtrace('done');
342 if ($CFG->enableportfolios) {
343 // Portfolio cron
344 mtrace('Starting the portfolio cron...');
345 cron_trace_time_and_memory();
346 require_once($CFG->libdir . '/portfoliolib.php');
347 portfolio_cron();
348 mtrace('done');
352 //now do plagiarism checks
353 require_once($CFG->libdir.'/plagiarismlib.php');
354 plagiarism_cron();
357 mtrace('Starting course reports');
358 cron_execute_plugin_type('coursereport');
359 mtrace('Finished course reports');
362 // run gradebook import/export/report cron
363 mtrace('Starting gradebook plugins');
364 cron_execute_plugin_type('gradeimport');
365 cron_execute_plugin_type('gradeexport');
366 cron_execute_plugin_type('gradereport');
367 mtrace('Finished gradebook plugins');
369 // run calendar cron
370 require_once "{$CFG->dirroot}/calendar/lib.php";
371 calendar_cron();
373 // Run external blog cron if needed
374 if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
375 require_once($CFG->dirroot . '/blog/lib.php');
376 mtrace("Fetching external blog entries...", '');
377 cron_trace_time_and_memory();
378 $sql = "timefetched < ? OR timefetched = 0";
379 $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
381 foreach ($externalblogs as $eb) {
382 blog_sync_external_entries($eb);
384 mtrace('done.');
386 // Run blog associations cleanup
387 if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
388 require_once($CFG->dirroot . '/blog/lib.php');
389 // delete entries whose contextids no longer exists
390 mtrace("Deleting blog associations linked to non-existent contexts...", '');
391 cron_trace_time_and_memory();
392 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
393 mtrace('done.');
397 // Run question bank clean-up.
398 mtrace("Starting the question bank cron...", '');
399 cron_trace_time_and_memory();
400 require_once($CFG->libdir . '/questionlib.php');
401 question_bank::cron();
402 mtrace('done.');
405 //Run registration updated cron
406 mtrace(get_string('siteupdatesstart', 'hub'));
407 cron_trace_time_and_memory();
408 require_once($CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php');
409 $registrationmanager = new registration_manager();
410 $registrationmanager->cron();
411 mtrace(get_string('siteupdatesend', 'hub'));
413 // If enabled, fetch information about available updates and eventually notify site admins
414 if (empty($CFG->disableupdatenotifications)) {
415 require_once($CFG->libdir.'/pluginlib.php');
416 $updateschecker = available_update_checker::instance();
417 $updateschecker->cron();
420 //cleanup old session linked tokens
421 //deletes the session linked tokens that are over a day old.
422 mtrace("Deleting session linked tokens more than one day old...", '');
423 cron_trace_time_and_memory();
424 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
425 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
426 mtrace('done.');
429 // all other plugins
430 cron_execute_plugin_type('message', 'message plugins');
431 cron_execute_plugin_type('filter', 'filters');
432 cron_execute_plugin_type('editor', 'editors');
433 cron_execute_plugin_type('format', 'course formats');
434 cron_execute_plugin_type('profilefield', 'profile fields');
435 cron_execute_plugin_type('webservice', 'webservices');
436 cron_execute_plugin_type('repository', 'repository plugins');
437 cron_execute_plugin_type('qbehaviour', 'question behaviours');
438 cron_execute_plugin_type('qformat', 'question import/export formats');
439 cron_execute_plugin_type('qtype', 'question types');
440 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
441 cron_execute_plugin_type('theme', 'themes');
442 cron_execute_plugin_type('tool', 'admin tools');
445 // and finally run any local cronjobs, if any
446 if ($locals = get_plugin_list('local')) {
447 mtrace('Processing customized cron scripts ...', '');
448 // new cron functions in lib.php first
449 cron_execute_plugin_type('local');
450 // legacy cron files are executed directly
451 foreach ($locals as $local => $localdir) {
452 if (file_exists("$localdir/cron.php")) {
453 include("$localdir/cron.php");
456 mtrace('done.');
459 mtrace('Running cache cron routines');
460 cache_helper::cron();
461 mtrace('done.');
463 // Run automated backups if required - these may take a long time to execute
464 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
465 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
466 backup_cron_automated_helper::run_automated_backup();
469 // Run stats as at the end because they are known to take very long time on large sites
470 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
471 require_once($CFG->dirroot.'/lib/statslib.php');
472 // check we're not before our runtime
473 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
475 if (time() > $timetocheck) {
476 // process configured number of days as max (defaulting to 31)
477 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
478 if (stats_cron_daily($maxdays)) {
479 if (stats_cron_weekly()) {
480 if (stats_cron_monthly()) {
481 stats_clean_old();
485 @set_time_limit(0);
486 } else {
487 mtrace('Next stats run after:'. userdate($timetocheck));
491 // Run badges review cron.
492 mtrace("Starting badges cron...");
493 require_once($CFG->dirroot . '/badges/cron.php');
494 badge_cron();
495 mtrace('done.');
497 // cleanup file trash - not very important
498 $fs = get_file_storage();
499 $fs->cron();
501 mtrace("Cron script completed correctly");
503 gc_collect_cycles();
504 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
505 $difftime = microtime_diff($starttime, microtime());
506 mtrace("Execution took ".$difftime." seconds");
510 * Executes cron functions for a specific type of plugin.
512 * @param string $plugintype Plugin type (e.g. 'report')
513 * @param string $description If specified, will display 'Starting (whatever)'
514 * and 'Finished (whatever)' lines, otherwise does not display
516 function cron_execute_plugin_type($plugintype, $description = null) {
517 global $DB;
519 // Get list from plugin => function for all plugins
520 $plugins = get_plugin_list_with_function($plugintype, 'cron');
522 // Modify list for backward compatibility (different files/names)
523 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
525 // Return if no plugins with cron function to process
526 if (!$plugins) {
527 return;
530 if ($description) {
531 mtrace('Starting '.$description);
534 foreach ($plugins as $component=>$cronfunction) {
535 $dir = get_component_directory($component);
537 // Get cron period if specified in version.php, otherwise assume every cron
538 $cronperiod = 0;
539 if (file_exists("$dir/version.php")) {
540 $plugin = new stdClass();
541 include("$dir/version.php");
542 if (isset($plugin->cron)) {
543 $cronperiod = $plugin->cron;
547 // Using last cron and cron period, don't run if it already ran recently
548 $lastcron = get_config($component, 'lastcron');
549 if ($cronperiod && $lastcron) {
550 if ($lastcron + $cronperiod > time()) {
551 // do not execute cron yet
552 continue;
556 mtrace('Processing cron function for ' . $component . '...');
557 cron_trace_time_and_memory();
558 $pre_dbqueries = $DB->perf_get_queries();
559 $pre_time = microtime(true);
561 $cronfunction();
563 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
564 round(microtime(true) - $pre_time, 2) . " seconds)");
566 set_config('lastcron', time(), $component);
567 @set_time_limit(0);
570 if ($description) {
571 mtrace('Finished ' . $description);
576 * Used to add in old-style cron functions within plugins that have not been converted to the
577 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
578 * cron.php and some used a different name.)
580 * @param string $plugintype Plugin type e.g. 'report'
581 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
582 * 'report_frog_cron') for plugin cron functions that were already found using the new API
583 * @return array Revised version of $plugins that adds in any extra plugin functions found by
584 * looking in the older location
586 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
587 global $CFG; // mandatory in case it is referenced by include()d PHP script
589 if ($plugintype === 'report') {
590 // Admin reports only - not course report because course report was
591 // never implemented before, so doesn't need BC
592 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
593 $component = $plugintype . '_' . $pluginname;
594 if (isset($plugins[$component])) {
595 // We already have detected the function using the new API
596 continue;
598 if (!file_exists("$dir/cron.php")) {
599 // No old style cron file present
600 continue;
602 include_once("$dir/cron.php");
603 $cronfunction = $component . '_cron';
604 if (function_exists($cronfunction)) {
605 $plugins[$component] = $cronfunction;
606 } else {
607 debugging("Invalid legacy cron.php detected in $component, " .
608 "please use lib.php instead");
611 } else if (strpos($plugintype, 'grade') === 0) {
612 // Detect old style cron function names
613 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
614 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
615 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
616 $component = $plugintype.'_'.$pluginname;
617 if (isset($plugins[$component])) {
618 // We already have detected the function using the new API
619 continue;
621 if (!file_exists("$dir/lib.php")) {
622 continue;
624 include_once("$dir/lib.php");
625 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
626 $pluginname . '_cron';
627 if (function_exists($cronfunction)) {
628 $plugins[$component] = $cronfunction;
633 return $plugins;
637 * Output some standard information during cron runs. Specifically current time
638 * and memory usage. This method also does gc_collect_cycles() (before displaying
639 * memory usage) to try to help PHP manage memory better.
641 function cron_trace_time_and_memory() {
642 gc_collect_cycles();
643 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
647 * Notify admin users or admin user of any failed logins (since last notification).
649 * Note that this function must be only executed from the cron script
650 * It uses the cache_flags system to store temporary records, deleting them
651 * by name before finishing
653 * @return bool True if executed, false if not
655 function notify_login_failures() {
656 global $CFG, $DB, $OUTPUT;
658 if (empty($CFG->notifyloginfailures)) {
659 return false;
662 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
664 if (empty($CFG->lastnotifyfailure)) {
665 $CFG->lastnotifyfailure=0;
668 // If it has been less than an hour, or if there are no recipients, don't execute.
669 if (((time() - HOURSECS) < $CFG->lastnotifyfailure) || !is_array($recip) || count($recip) <= 0) {
670 return false;
673 // we need to deal with the threshold stuff first.
674 if (empty($CFG->notifyloginthreshold)) {
675 $CFG->notifyloginthreshold = 10; // default to something sensible.
678 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
679 // and insert them into the cache_flags temp table
680 $sql = "SELECT ip, COUNT(*)
681 FROM {log}
682 WHERE module = 'login' AND action = 'error'
683 AND time > ?
684 GROUP BY ip
685 HAVING COUNT(*) >= ?";
686 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
687 $rs = $DB->get_recordset_sql($sql, $params);
688 foreach ($rs as $iprec) {
689 if (!empty($iprec->ip)) {
690 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
693 $rs->close();
695 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
696 // and insert them into the cache_flags temp table
697 $sql = "SELECT info, count(*)
698 FROM {log}
699 WHERE module = 'login' AND action = 'error'
700 AND time > ?
701 GROUP BY info
702 HAVING count(*) >= ?";
703 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
704 $rs = $DB->get_recordset_sql($sql, $params);
705 foreach ($rs as $inforec) {
706 if (!empty($inforec->info)) {
707 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
710 $rs->close();
712 // Now, select all the login error logged records belonging to the ips and infos
713 // since lastnotifyfailure, that we have stored in the cache_flags table
714 $sql = "SELECT * FROM (
715 SELECT l.*, u.firstname, u.lastname
716 FROM {log} l
717 JOIN {cache_flags} cf ON l.ip = cf.name
718 LEFT JOIN {user} u ON l.userid = u.id
719 WHERE l.module = 'login' AND l.action = 'error'
720 AND l.time > ?
721 AND cf.flagtype = 'login_failure_by_ip'
722 UNION ALL
723 SELECT l.*, u.firstname, u.lastname
724 FROM {log} l
725 JOIN {cache_flags} cf ON l.info = cf.name
726 LEFT JOIN {user} u ON l.userid = u.id
727 WHERE l.module = 'login' AND l.action = 'error'
728 AND l.time > ?
729 AND cf.flagtype = 'login_failure_by_info') t
730 ORDER BY t.time DESC";
731 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
733 // Init some variables
734 $count = 0;
735 $messages = '';
736 // Iterate over the logs recordset
737 $rs = $DB->get_recordset_sql($sql, $params);
738 foreach ($rs as $log) {
739 $log->time = userdate($log->time);
740 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
741 $count++;
743 $rs->close();
745 // If we have something useful to report.
746 if ($count > 0) {
747 $site = get_site();
748 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
749 // Calculate the complete body of notification (start + messages + end)
750 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
751 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
752 $messages .
753 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
755 // For each destination, send mail
756 mtrace('Emailing admins about '. $count .' failed login attempts');
757 foreach ($recip as $admin) {
758 //emailing the admins directly rather than putting these through the messaging system
759 email_to_user($admin, generate_email_supportuser(), $subject, $body);
763 // Update lastnotifyfailure with current time
764 set_config('lastnotifyfailure', time());
766 // Finally, delete all the temp records we have created in cache_flags
767 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
769 return true;