MDL-40490 - database: Fixed a check on database port options.
[moodle.git] / lib / cronlib.php
blob8762e4424171ade6780b82cc4cebc825fd6e2346
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 delete_user($user);
103 mtrace(" Deleted not fully setup user $user->username ($user->id)");
105 $rs->close();
109 // Delete old logs to save space (this might need a timer to slow it down...)
110 if (!empty($CFG->loglifetime)) { // value in days
111 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
112 $DB->delete_records_select("log", "time < ?", array($loglifetime));
113 mtrace(" Deleted old log records");
117 // Delete old backup_controllers and logs.
118 $loglifetime = get_config('backup', 'loglifetime');
119 if (!empty($loglifetime)) { // Value in days.
120 $loglifetime = $timenow - ($loglifetime * 3600 * 24);
121 // Delete child records from backup_logs.
122 $DB->execute("DELETE FROM {backup_logs}
123 WHERE EXISTS (
124 SELECT 'x'
125 FROM {backup_controllers} bc
126 WHERE bc.backupid = {backup_logs}.backupid
127 AND bc.timecreated < ?)", array($loglifetime));
128 // Delete records from backup_controllers.
129 $DB->execute("DELETE FROM {backup_controllers}
130 WHERE timecreated < ?", array($loglifetime));
131 mtrace(" Deleted old backup records");
135 // Delete old cached texts
136 if (!empty($CFG->cachetext)) { // Defined in config.php
137 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
138 $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
139 mtrace(" Deleted old cache_text records");
143 if (!empty($CFG->usetags)) {
144 require_once($CFG->dirroot.'/tag/lib.php');
145 tag_cron();
146 mtrace(' Executed tag cron');
150 // Context maintenance stuff
151 context_helper::cleanup_instances();
152 mtrace(' Cleaned up context instances');
153 context_helper::build_all_paths(false);
154 // If you suspect that the context paths are somehow corrupt
155 // replace the line below with: context_helper::build_all_paths(true);
156 mtrace(' Built context paths');
159 // Remove expired cache flags
160 gc_cache_flags();
161 mtrace(' Cleaned cache flags');
164 // Cleanup messaging
165 if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
166 $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
167 $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime'=>$notificationdeletetime));
168 mtrace(' Cleaned up read notifications');
171 mtrace("...finished clean-up tasks");
173 } // End of occasional clean-up tasks
176 // Send login failures notification - brute force protection in moodle is weak,
177 // we should at least send notices early in each cron execution
178 if (notify_login_failures()) {
179 mtrace(' Notified login failures');
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 cron_trace_time_and_memory();
198 foreach ($auths as $auth) {
199 $authplugin = get_auth_plugin($auth);
200 if (method_exists($authplugin, 'cron')) {
201 mtrace("Running cron for auth/$auth...");
202 $authplugin->cron();
203 if (!empty($authplugin->log)) {
204 mtrace($authplugin->log);
207 unset($authplugin);
209 // Generate new password emails for users - ppl expect these generated asap
210 if ($DB->count_records('user_preferences', array('name'=>'create_password', 'value'=>'1'))) {
211 mtrace('Creating passwords for new users...');
212 $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email, u.firstname,
213 u.lastname, u.username, u.lang,
214 p.id as prefid
215 FROM {user} u
216 JOIN {user_preferences} p ON u.id=p.userid
217 WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0");
219 // note: we can not send emails to suspended accounts
220 foreach ($newusers as $newuser) {
221 // Use a low cost factor when generating bcrypt hash otherwise
222 // hashing would be slow when emailing lots of users. Hashes
223 // will be automatically updated to a higher cost factor the first
224 // time the user logs in.
225 if (setnew_password_and_mail($newuser, true)) {
226 unset_user_preference('create_password', $newuser);
227 set_user_preference('auth_forcepasswordchange', 1, $newuser);
228 } else {
229 trigger_error("Could not create and mail new user password!");
232 $newusers->close();
236 // It is very important to run enrol early
237 // because other plugins depend on correct enrolment info.
238 mtrace("Running enrol crons if required...");
239 $enrols = enrol_get_plugins(true);
240 foreach($enrols as $ename=>$enrol) {
241 // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
242 if (!$enrol->is_cron_required()) {
243 continue;
245 mtrace("Running cron for enrol_$ename...");
246 cron_trace_time_and_memory();
247 $enrol->cron();
248 $enrol->set_config('lastcron', time());
252 // Run all cron jobs for each module
253 mtrace("Starting activity modules");
254 get_mailer('buffer');
255 if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
256 foreach ($mods as $mod) {
257 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
258 if (file_exists($libfile)) {
259 include_once($libfile);
260 $cron_function = $mod->name."_cron";
261 if (function_exists($cron_function)) {
262 mtrace("Processing module function $cron_function ...", '');
263 cron_trace_time_and_memory();
264 $pre_dbqueries = null;
265 $pre_dbqueries = $DB->perf_get_queries();
266 $pre_time = microtime(1);
267 if ($cron_function()) {
268 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id));
270 if (isset($pre_dbqueries)) {
271 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
272 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
274 // Reset possible changes by modules to time_limit. MDL-11597
275 @set_time_limit(0);
276 mtrace("done.");
281 get_mailer('close');
282 mtrace("Finished activity modules");
285 mtrace("Starting blocks");
286 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
287 // We will need the base class.
288 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
289 foreach ($blocks as $block) {
290 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
291 if (file_exists($blockfile)) {
292 require_once($blockfile);
293 $classname = 'block_'.$block->name;
294 $blockobj = new $classname;
295 if (method_exists($blockobj,'cron')) {
296 mtrace("Processing cron function for ".$block->name.'....','');
297 cron_trace_time_and_memory();
298 if ($blockobj->cron()) {
299 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id));
301 // Reset possible changes by blocks to time_limit. MDL-11597
302 @set_time_limit(0);
303 mtrace('done.');
309 mtrace('Finished blocks');
312 mtrace('Starting admin reports');
313 cron_execute_plugin_type('report');
314 mtrace('Finished admin reports');
317 mtrace('Starting main gradebook job...');
318 cron_trace_time_and_memory();
319 grade_cron();
320 mtrace('done.');
323 mtrace('Starting processing the event queue...');
324 cron_trace_time_and_memory();
325 events_cron();
326 mtrace('done.');
329 if ($CFG->enablecompletion) {
330 // Completion cron
331 mtrace('Starting the completion cron...');
332 cron_trace_time_and_memory();
333 require_once($CFG->dirroot.'/completion/cron.php');
334 completion_cron();
335 mtrace('done');
339 if ($CFG->enableportfolios) {
340 // Portfolio cron
341 mtrace('Starting the portfolio cron...');
342 cron_trace_time_and_memory();
343 require_once($CFG->libdir . '/portfoliolib.php');
344 portfolio_cron();
345 mtrace('done');
349 //now do plagiarism checks
350 require_once($CFG->libdir.'/plagiarismlib.php');
351 plagiarism_cron();
354 mtrace('Starting course reports');
355 cron_execute_plugin_type('coursereport');
356 mtrace('Finished course reports');
359 // run gradebook import/export/report cron
360 mtrace('Starting gradebook plugins');
361 cron_execute_plugin_type('gradeimport');
362 cron_execute_plugin_type('gradeexport');
363 cron_execute_plugin_type('gradereport');
364 mtrace('Finished gradebook plugins');
366 // run calendar cron
367 require_once "{$CFG->dirroot}/calendar/lib.php";
368 calendar_cron();
370 // Run external blog cron if needed
371 if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
372 require_once($CFG->dirroot . '/blog/lib.php');
373 mtrace("Fetching external blog entries...", '');
374 cron_trace_time_and_memory();
375 $sql = "timefetched < ? OR timefetched = 0";
376 $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
378 foreach ($externalblogs as $eb) {
379 blog_sync_external_entries($eb);
381 mtrace('done.');
383 // Run blog associations cleanup
384 if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
385 require_once($CFG->dirroot . '/blog/lib.php');
386 // delete entries whose contextids no longer exists
387 mtrace("Deleting blog associations linked to non-existent contexts...", '');
388 cron_trace_time_and_memory();
389 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
390 mtrace('done.');
394 // Run question bank clean-up.
395 mtrace("Starting the question bank cron...", '');
396 cron_trace_time_and_memory();
397 require_once($CFG->libdir . '/questionlib.php');
398 question_bank::cron();
399 mtrace('done.');
402 //Run registration updated cron
403 mtrace(get_string('siteupdatesstart', 'hub'));
404 cron_trace_time_and_memory();
405 require_once($CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php');
406 $registrationmanager = new registration_manager();
407 $registrationmanager->cron();
408 mtrace(get_string('siteupdatesend', 'hub'));
410 // If enabled, fetch information about available updates and eventually notify site admins
411 if (empty($CFG->disableupdatenotifications)) {
412 require_once($CFG->libdir.'/pluginlib.php');
413 $updateschecker = available_update_checker::instance();
414 $updateschecker->cron();
417 //cleanup old session linked tokens
418 //deletes the session linked tokens that are over a day old.
419 mtrace("Deleting session linked tokens more than one day old...", '');
420 cron_trace_time_and_memory();
421 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
422 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
423 mtrace('done.');
426 // all other plugins
427 cron_execute_plugin_type('message', 'message plugins');
428 cron_execute_plugin_type('filter', 'filters');
429 cron_execute_plugin_type('editor', 'editors');
430 cron_execute_plugin_type('format', 'course formats');
431 cron_execute_plugin_type('profilefield', 'profile fields');
432 cron_execute_plugin_type('webservice', 'webservices');
433 cron_execute_plugin_type('repository', 'repository plugins');
434 cron_execute_plugin_type('qbehaviour', 'question behaviours');
435 cron_execute_plugin_type('qformat', 'question import/export formats');
436 cron_execute_plugin_type('qtype', 'question types');
437 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
438 cron_execute_plugin_type('theme', 'themes');
439 cron_execute_plugin_type('tool', 'admin tools');
442 // and finally run any local cronjobs, if any
443 if ($locals = get_plugin_list('local')) {
444 mtrace('Processing customized cron scripts ...', '');
445 // new cron functions in lib.php first
446 cron_execute_plugin_type('local');
447 // legacy cron files are executed directly
448 foreach ($locals as $local => $localdir) {
449 if (file_exists("$localdir/cron.php")) {
450 include("$localdir/cron.php");
453 mtrace('done.');
456 mtrace('Running cache cron routines');
457 cache_helper::cron();
458 mtrace('done.');
460 // Run automated backups if required - these may take a long time to execute
461 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
462 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
463 backup_cron_automated_helper::run_automated_backup();
466 // Run stats as at the end because they are known to take very long time on large sites
467 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
468 require_once($CFG->dirroot.'/lib/statslib.php');
469 // check we're not before our runtime
470 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
472 if (time() > $timetocheck) {
473 // process configured number of days as max (defaulting to 31)
474 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
475 if (stats_cron_daily($maxdays)) {
476 if (stats_cron_weekly()) {
477 if (stats_cron_monthly()) {
478 stats_clean_old();
482 @set_time_limit(0);
483 } else {
484 mtrace('Next stats run after:'. userdate($timetocheck));
488 // Run badges review cron.
489 mtrace("Starting badges cron...");
490 require_once($CFG->dirroot . '/badges/cron.php');
491 badge_cron();
492 mtrace('done.');
494 // cleanup file trash - not very important
495 $fs = get_file_storage();
496 $fs->cron();
498 mtrace("Cron script completed correctly");
500 gc_collect_cycles();
501 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
502 $difftime = microtime_diff($starttime, microtime());
503 mtrace("Execution took ".$difftime." seconds");
507 * Executes cron functions for a specific type of plugin.
509 * @param string $plugintype Plugin type (e.g. 'report')
510 * @param string $description If specified, will display 'Starting (whatever)'
511 * and 'Finished (whatever)' lines, otherwise does not display
513 function cron_execute_plugin_type($plugintype, $description = null) {
514 global $DB;
516 // Get list from plugin => function for all plugins
517 $plugins = get_plugin_list_with_function($plugintype, 'cron');
519 // Modify list for backward compatibility (different files/names)
520 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
522 // Return if no plugins with cron function to process
523 if (!$plugins) {
524 return;
527 if ($description) {
528 mtrace('Starting '.$description);
531 foreach ($plugins as $component=>$cronfunction) {
532 $dir = get_component_directory($component);
534 // Get cron period if specified in version.php, otherwise assume every cron
535 $cronperiod = 0;
536 if (file_exists("$dir/version.php")) {
537 $plugin = new stdClass();
538 include("$dir/version.php");
539 if (isset($plugin->cron)) {
540 $cronperiod = $plugin->cron;
544 // Using last cron and cron period, don't run if it already ran recently
545 $lastcron = get_config($component, 'lastcron');
546 if ($cronperiod && $lastcron) {
547 if ($lastcron + $cronperiod > time()) {
548 // do not execute cron yet
549 continue;
553 mtrace('Processing cron function for ' . $component . '...');
554 cron_trace_time_and_memory();
555 $pre_dbqueries = $DB->perf_get_queries();
556 $pre_time = microtime(true);
558 $cronfunction();
560 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
561 round(microtime(true) - $pre_time, 2) . " seconds)");
563 set_config('lastcron', time(), $component);
564 @set_time_limit(0);
567 if ($description) {
568 mtrace('Finished ' . $description);
573 * Used to add in old-style cron functions within plugins that have not been converted to the
574 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
575 * cron.php and some used a different name.)
577 * @param string $plugintype Plugin type e.g. 'report'
578 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
579 * 'report_frog_cron') for plugin cron functions that were already found using the new API
580 * @return array Revised version of $plugins that adds in any extra plugin functions found by
581 * looking in the older location
583 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
584 global $CFG; // mandatory in case it is referenced by include()d PHP script
586 if ($plugintype === 'report') {
587 // Admin reports only - not course report because course report was
588 // never implemented before, so doesn't need BC
589 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
590 $component = $plugintype . '_' . $pluginname;
591 if (isset($plugins[$component])) {
592 // We already have detected the function using the new API
593 continue;
595 if (!file_exists("$dir/cron.php")) {
596 // No old style cron file present
597 continue;
599 include_once("$dir/cron.php");
600 $cronfunction = $component . '_cron';
601 if (function_exists($cronfunction)) {
602 $plugins[$component] = $cronfunction;
603 } else {
604 debugging("Invalid legacy cron.php detected in $component, " .
605 "please use lib.php instead");
608 } else if (strpos($plugintype, 'grade') === 0) {
609 // Detect old style cron function names
610 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
611 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
612 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
613 $component = $plugintype.'_'.$pluginname;
614 if (isset($plugins[$component])) {
615 // We already have detected the function using the new API
616 continue;
618 if (!file_exists("$dir/lib.php")) {
619 continue;
621 include_once("$dir/lib.php");
622 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
623 $pluginname . '_cron';
624 if (function_exists($cronfunction)) {
625 $plugins[$component] = $cronfunction;
630 return $plugins;
634 * Output some standard information during cron runs. Specifically current time
635 * and memory usage. This method also does gc_collect_cycles() (before displaying
636 * memory usage) to try to help PHP manage memory better.
638 function cron_trace_time_and_memory() {
639 gc_collect_cycles();
640 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
644 * Notify admin users or admin user of any failed logins (since last notification).
646 * Note that this function must be only executed from the cron script
647 * It uses the cache_flags system to store temporary records, deleting them
648 * by name before finishing
650 * @return bool True if executed, false if not
652 function notify_login_failures() {
653 global $CFG, $DB, $OUTPUT;
655 if (empty($CFG->notifyloginfailures)) {
656 return false;
659 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
661 if (empty($CFG->lastnotifyfailure)) {
662 $CFG->lastnotifyfailure=0;
665 // If it has been less than an hour, or if there are no recipients, don't execute.
666 if (((time() - HOURSECS) < $CFG->lastnotifyfailure) || !is_array($recip) || count($recip) <= 0) {
667 return false;
670 // we need to deal with the threshold stuff first.
671 if (empty($CFG->notifyloginthreshold)) {
672 $CFG->notifyloginthreshold = 10; // default to something sensible.
675 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
676 // and insert them into the cache_flags temp table
677 $sql = "SELECT ip, COUNT(*)
678 FROM {log}
679 WHERE module = 'login' AND action = 'error'
680 AND time > ?
681 GROUP BY ip
682 HAVING COUNT(*) >= ?";
683 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
684 $rs = $DB->get_recordset_sql($sql, $params);
685 foreach ($rs as $iprec) {
686 if (!empty($iprec->ip)) {
687 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
690 $rs->close();
692 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
693 // and insert them into the cache_flags temp table
694 $sql = "SELECT info, count(*)
695 FROM {log}
696 WHERE module = 'login' AND action = 'error'
697 AND time > ?
698 GROUP BY info
699 HAVING count(*) >= ?";
700 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
701 $rs = $DB->get_recordset_sql($sql, $params);
702 foreach ($rs as $inforec) {
703 if (!empty($inforec->info)) {
704 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
707 $rs->close();
709 // Now, select all the login error logged records belonging to the ips and infos
710 // since lastnotifyfailure, that we have stored in the cache_flags table
711 $sql = "SELECT * FROM (
712 SELECT l.*, u.firstname, u.lastname
713 FROM {log} l
714 JOIN {cache_flags} cf ON l.ip = cf.name
715 LEFT JOIN {user} u ON l.userid = u.id
716 WHERE l.module = 'login' AND l.action = 'error'
717 AND l.time > ?
718 AND cf.flagtype = 'login_failure_by_ip'
719 UNION ALL
720 SELECT l.*, u.firstname, u.lastname
721 FROM {log} l
722 JOIN {cache_flags} cf ON l.info = cf.name
723 LEFT JOIN {user} u ON l.userid = u.id
724 WHERE l.module = 'login' AND l.action = 'error'
725 AND l.time > ?
726 AND cf.flagtype = 'login_failure_by_info') t
727 ORDER BY t.time DESC";
728 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
730 // Init some variables
731 $count = 0;
732 $messages = '';
733 // Iterate over the logs recordset
734 $rs = $DB->get_recordset_sql($sql, $params);
735 foreach ($rs as $log) {
736 $log->time = userdate($log->time);
737 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
738 $count++;
740 $rs->close();
742 // If we have something useful to report.
743 if ($count > 0) {
744 $site = get_site();
745 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
746 // Calculate the complete body of notification (start + messages + end)
747 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
748 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
749 $messages .
750 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
752 // For each destination, send mail
753 mtrace('Emailing admins about '. $count .' failed login attempts');
754 foreach ($recip as $admin) {
755 //emailing the admins directly rather than putting these through the messaging system
756 email_to_user($admin, generate_email_supportuser(), $subject, $body);
760 // Update lastnotifyfailure with current time
761 set_config('lastnotifyfailure', time());
763 // Finally, delete all the temp records we have created in cache_flags
764 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
766 return true;