MDL-30051 cron: login error sql is now cross db
[moodle.git] / lib / cronlib.php
CommitLineData
28bd3d9a 1<?php
28bd3d9a
PS
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/>.
16
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 */
25
50ed196e
PS
26/**
27 * Execute cron tasks
28 */
28bd3d9a
PS
29function cron_run() {
30 global $DB, $CFG, $OUTPUT;
31
9957af68
PS
32 if (CLI_MAINTENANCE) {
33 echo "CLI maintenance mode active, cron execution suspended.\n";
34 exit(1);
35 }
36
4c56c7bf
PS
37 if (moodle_needs_upgrading()) {
38 echo "Moodle upgrade pending, cron execution suspended.\n";
39 exit(1);
40 }
41
28bd3d9a
PS
42 require_once($CFG->libdir.'/adminlib.php');
43 require_once($CFG->libdir.'/gradelib.php');
44
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 }
52
53 set_time_limit(0);
54 $starttime = microtime();
55
50ed196e 56 // Increase memory limit
346c5887 57 raise_memory_limit(MEMORY_EXTRA);
28bd3d9a 58
50ed196e 59 // Emulate normal session - we use admin accoutn by default
28bd3d9a
PS
60 cron_setup_user();
61
50ed196e 62 // Start output log
28bd3d9a 63 $timenow = time();
28bd3d9a
PS
64 mtrace("Server Time: ".date('r',$timenow)."\n\n");
65
66
50ed196e
PS
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
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 }
89
90
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 }
106
107
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 }
114
115
116 // Delete old backup_controllers and logs
117 if (!empty($CFG->loglifetime)) { // value in days
118 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
119 // Delete child records from backup_logs
120 $DB->execute("DELETE FROM {backup_logs}
121 WHERE EXISTS (
122 SELECT 'x'
123 FROM {backup_controllers} bc
124 WHERE bc.backupid = {backup_logs}.backupid
125 AND bc.timecreated < ?)", array($loglifetime));
126 // Delete records from backup_controllers
127 $DB->execute("DELETE FROM {backup_controllers}
128 WHERE timecreated < ?", array($loglifetime));
129 mtrace(" Deleted old backup records");
130 }
131
132
133 // Delete old cached texts
134 if (!empty($CFG->cachetext)) { // Defined in config.php
135 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
136 $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
137 mtrace(" Deleted old cache_text records");
138 }
139
140
141 if (!empty($CFG->usetags)) {
142 require_once($CFG->dirroot.'/tag/lib.php');
143 tag_cron();
144 mtrace(' Executed tag cron');
145 }
146
147
148 // Context maintenance stuff
149 context_helper::cleanup_instances();
150 mtrace(' Cleaned up context instances');
151 context_helper::build_all_paths(false);
152 // If you suspect that the context paths are somehow corrupt
153 // replace the line below with: context_helper::build_all_paths(true);
154 mtrace(' Built context paths');
155
156
157 // Remove expired cache flags
158 gc_cache_flags();
159 mtrace(' Cleaned cache flags');
160
161
162 // Cleanup messaging
163 if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
164 $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
165 $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime'=>$notificationdeletetime));
166 mtrace(' Cleaned up read notifications');
167 }
168
169 mtrace("...finished clean-up tasks");
170
171 } // End of occasional clean-up tasks
172
173
174 // Send login failures notification - brute force protection in moodle is weak,
175 // we should at least send notices early in each cron execution
176 if (!empty($CFG->notifyloginfailures)) {
177 notify_login_failures();
178 mtrace(' Notified login failured');
179 }
180
181
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');
185
28bd3d9a 186
50ed196e 187 // Session gc
28bd3d9a 188 session_gc();
50ed196e 189 mtrace("Cleaned up stale user sessions");
28bd3d9a 190
28bd3d9a 191
50ed196e
PS
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);
203 }
204 }
205 unset($authplugin);
206 }
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,
212 p.id as prefid
213 FROM {user} u
214 JOIN {user_preferences} p ON u.id=p.userid
daa8b1ac 215 WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin'");
50ed196e 216
daa8b1ac 217 // note: we can not send emails to suspended accounts
50ed196e
PS
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!");
224 }
225 }
226 $newusers->close();
227 }
228
229
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;
238 }
239 mtrace("Running cron for enrol_$ename...");
240 $enrol->cron();
241 $enrol->set_config('lastcron', time());
242 }
243
244
245 // Run all cron jobs for each module
28bd3d9a
PS
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()) {
f685e830 260 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id));
28bd3d9a
PS
261 }
262 if (isset($pre_dbqueries)) {
263 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
264 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
265 }
50ed196e 266 // Reset possible changes by modules to time_limit. MDL-11597
28bd3d9a
PS
267 @set_time_limit(0);
268 mtrace("done.");
269 }
270 }
271 }
272 }
273 get_mailer('close');
274 mtrace("Finished activity modules");
275
50ed196e 276
28bd3d9a
PS
277 mtrace("Starting blocks");
278 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
50ed196e 279 // We will need the base class.
28bd3d9a
PS
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()) {
f685e830 290 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id));
28bd3d9a 291 }
50ed196e 292 // Reset possible changes by blocks to time_limit. MDL-11597
28bd3d9a
PS
293 @set_time_limit(0);
294 mtrace('done.');
295 }
296 }
297
298 }
299 }
300 mtrace('Finished blocks');
301
50ed196e 302
b5541735
PS
303 mtrace('Starting admin reports');
304 cron_execute_plugin_type('report');
305 mtrace('Finished admin reports');
306
50ed196e
PS
307
308 mtrace('Starting main gradebook job...');
28bd3d9a
PS
309 grade_cron();
310 mtrace('done.');
311
312
313 mtrace('Starting processing the event queue...');
314 events_cron();
315 mtrace('done.');
316
317
318 if ($CFG->enablecompletion) {
319 // Completion cron
320 mtrace('Starting the completion cron...');
321 require_once($CFG->libdir . '/completion/cron.php');
322 completion_cron();
323 mtrace('done');
324 }
325
326
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');
333 }
334
50ed196e 335
8cf1862c
DM
336 //now do plagiarism checks
337 require_once($CFG->libdir.'/plagiarismlib.php');
338 plagiarism_cron();
339
28bd3d9a 340
b5541735
PS
341 mtrace('Starting course reports');
342 cron_execute_plugin_type('coursereport');
343 mtrace('Finished course reports');
28bd3d9a 344
50ed196e 345
b5541735
PS
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');
28bd3d9a 352
50ed196e 353
28bd3d9a
PS
354 // Run external blog cron if needed
355 if ($CFG->useexternalblogs) {
356 require_once($CFG->dirroot . '/blog/lib.php');
357 mtrace("Fetching external blog entries...", '');
358 $sql = "timefetched < ? OR timefetched = 0";
e2bb3c92 359 $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
28bd3d9a
PS
360
361 foreach ($externalblogs as $eb) {
362 blog_sync_external_entries($eb);
363 }
b5541735 364 mtrace('done.');
28bd3d9a 365 }
28bd3d9a
PS
366 // Run blog associations cleanup
367 if ($CFG->useblogassociations) {
368 require_once($CFG->dirroot . '/blog/lib.php');
369 // delete entries whose contextids no longer exists
370 mtrace("Deleting blog associations linked to non-existent contexts...", '');
371 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
b5541735 372 mtrace('done.');
28bd3d9a
PS
373 }
374
50ed196e 375
28bd3d9a
PS
376 //Run registration updated cron
377 mtrace(get_string('siteupdatesstart', 'hub'));
378 require_once($CFG->dirroot . '/admin/registration/lib.php');
379 $registrationmanager = new registration_manager();
380 $registrationmanager->cron();
381 mtrace(get_string('siteupdatesend', 'hub'));
382
28bd3d9a
PS
383
384 //cleanup old session linked tokens
385 //deletes the session linked tokens that are over a day old.
386 mtrace("Deleting session linked tokens more than one day old...", '');
387 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
388 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
389 mtrace('done.');
390
50ed196e 391
b5541735
PS
392 // all other plugins
393 cron_execute_plugin_type('message', 'message plugins');
394 cron_execute_plugin_type('filter', 'filters');
e4a626b9 395 cron_execute_plugin_type('editor', 'editors');
b5541735
PS
396 cron_execute_plugin_type('format', 'course formats');
397 cron_execute_plugin_type('profilefield', 'profile fields');
398 cron_execute_plugin_type('webservice', 'webservices');
e4a626b9 399 // TODO: Repository lib.php files are messed up (include many other files, etc), so it is
400 // currently not possible to implement repository plugin cron using this infrastructure
cd092ece 401 // cron_execute_plugin_type('repository', 'repository plugins');
c2f5e2ab
TH
402 cron_execute_plugin_type('qbehaviour', 'question behaviours');
403 cron_execute_plugin_type('qformat', 'question import/export formats');
b5541735
PS
404 cron_execute_plugin_type('qtype', 'question types');
405 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
406 cron_execute_plugin_type('theme', 'themes');
67a6243a 407 cron_execute_plugin_type('tool', 'admin tools');
b5541735 408
50ed196e 409
b5541735 410 // and finally run any local cronjobs, if any
28bd3d9a
PS
411 if ($locals = get_plugin_list('local')) {
412 mtrace('Processing customized cron scripts ...', '');
b5541735
PS
413 // new cron functions in lib.php first
414 cron_execute_plugin_type('local');
415 // legacy cron files are executed directly
28bd3d9a
PS
416 foreach ($locals as $local => $localdir) {
417 if (file_exists("$localdir/cron.php")) {
418 include("$localdir/cron.php");
419 }
420 }
421 mtrace('done.');
422 }
423
50ed196e
PS
424
425 // Run automated backups if required - these may take a long time to execute
426 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
427 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
428 backup_cron_automated_helper::run_automated_backup();
429
430
431 // Run stats as at the end because they are known to take very long time on large sites
432 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
433 require_once($CFG->dirroot.'/lib/statslib.php');
434 // check we're not before our runtime
435 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
436
437 if (time() > $timetocheck) {
438 // process configured number of days as max (defaulting to 31)
439 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
440 if (stats_cron_daily($maxdays)) {
441 if (stats_cron_weekly()) {
442 if (stats_cron_monthly()) {
443 stats_clean_old();
444 }
445 }
446 }
447 @set_time_limit(0);
448 } else {
449 mtrace('Next stats run after:'. userdate($timetocheck));
450 }
451 }
452
453
454 // cleanup file trash - not very important
455 $fs = get_file_storage();
456 $fs->cron();
457
458
28bd3d9a
PS
459 mtrace("Cron script completed correctly");
460
461 $difftime = microtime_diff($starttime, microtime());
462 mtrace("Execution took ".$difftime." seconds");
cbb9e9b8 463}
b5541735 464
e4a626b9 465/**
466 * Executes cron functions for a specific type of plugin.
50ed196e 467 *
e4a626b9 468 * @param string $plugintype Plugin type (e.g. 'report')
469 * @param string $description If specified, will display 'Starting (whatever)'
470 * and 'Finished (whatever)' lines, otherwise does not display
471 */
b5541735
PS
472function cron_execute_plugin_type($plugintype, $description = null) {
473 global $DB;
474
e4a626b9 475 // Get list from plugin => function for all plugins
476 $plugins = get_plugin_list_with_function($plugintype, 'cron');
477
478 // Modify list for backward compatibility (different files/names)
479 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
b5541735 480
e4a626b9 481 // Return if no plugins with cron function to process
b5541735
PS
482 if (!$plugins) {
483 return;
484 }
485
486 if ($description) {
487 mtrace('Starting '.$description);
488 }
489
490 foreach ($plugins as $component=>$cronfunction) {
cd092ece 491 $dir = get_component_directory($component);
e4a626b9 492
493 // Get cron period if specified in version.php, otherwise assume every cron
b5541735
PS
494 $cronperiod = 0;
495 if (file_exists("$dir/version.php")) {
496 $plugin = new stdClass();
497 include("$dir/version.php");
498 if (isset($plugin->cron)) {
499 $cronperiod = $plugin->cron;
500 }
501 }
502
e4a626b9 503 // Using last cron and cron period, don't run if it already ran recently
b5541735 504 $lastcron = get_config($component, 'lastcron');
e4a626b9 505 if ($cronperiod && $lastcron) {
b5541735
PS
506 if ($lastcron + $cronperiod > time()) {
507 // do not execute cron yet
508 continue;
509 }
510 }
511
e4a626b9 512 mtrace('Processing cron function for ' . $component . '...');
b5541735 513 $pre_dbqueries = $DB->perf_get_queries();
e4a626b9 514 $pre_time = microtime(true);
b5541735
PS
515
516 $cronfunction();
517
e4a626b9 518 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
519 round(microtime(true) - $pre_time, 2) . " seconds)");
b5541735
PS
520
521 set_config('lastcron', time(), $component);
4332cc46 522 @set_time_limit(0);
b5541735
PS
523 }
524
525 if ($description) {
e4a626b9 526 mtrace('Finished ' . $description);
b5541735
PS
527 }
528}
529
e4a626b9 530/**
531 * Used to add in old-style cron functions within plugins that have not been converted to the
532 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
533 * cron.php and some used a different name.)
50ed196e 534 *
e4a626b9 535 * @param string $plugintype Plugin type e.g. 'report'
536 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
537 * 'report_frog_cron') for plugin cron functions that were already found using the new API
538 * @return array Revised version of $plugins that adds in any extra plugin functions found by
539 * looking in the older location
540 */
541function cron_bc_hack_plugin_functions($plugintype, $plugins) {
542 global $CFG; // mandatory in case it is referenced by include()d PHP script
543
544 if ($plugintype === 'report') {
545 // Admin reports only - not course report because course report was
546 // never implemented before, so doesn't need BC
547 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
548 $component = $plugintype . '_' . $pluginname;
b5541735 549 if (isset($plugins[$component])) {
e4a626b9 550 // We already have detected the function using the new API
b5541735
PS
551 continue;
552 }
553 if (!file_exists("$dir/cron.php")) {
e4a626b9 554 // No old style cron file present
b5541735
PS
555 continue;
556 }
557 include_once("$dir/cron.php");
e4a626b9 558 $cronfunction = $component . '_cron';
b5541735
PS
559 if (function_exists($cronfunction)) {
560 $plugins[$component] = $cronfunction;
561 } else {
e4a626b9 562 debugging("Invalid legacy cron.php detected in $component, " .
563 "please use lib.php instead");
b5541735
PS
564 }
565 }
b5541735 566 } else if (strpos($plugintype, 'grade') === 0) {
e4a626b9 567 // Detect old style cron function names
568 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
569 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
b5541735
PS
570 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
571 $component = $plugintype.'_'.$pluginname;
572 if (isset($plugins[$component])) {
e4a626b9 573 // We already have detected the function using the new API
b5541735
PS
574 continue;
575 }
576 if (!file_exists("$dir/lib.php")) {
577 continue;
578 }
579 include_once("$dir/lib.php");
e4a626b9 580 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
581 $pluginname . '_cron';
b5541735
PS
582 if (function_exists($cronfunction)) {
583 $plugins[$component] = $cronfunction;
584 }
585 }
586 }
587
588 return $plugins;
50ed196e
PS
589}
590
591
592/**
593 * Notify admin users or admin user of any failed logins (since last notification).
594 *
595 * Note that this function must be only executed from the cron script
596 * It uses the cache_flags system to store temporary records, deleting them
597 * by name before finishing
598 */
599function notify_login_failures() {
600 global $CFG, $DB, $OUTPUT;
601
602 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
603
604 if (empty($CFG->lastnotifyfailure)) {
605 $CFG->lastnotifyfailure=0;
606 }
607
608 // we need to deal with the threshold stuff first.
609 if (empty($CFG->notifyloginthreshold)) {
610 $CFG->notifyloginthreshold = 10; // default to something sensible.
611 }
612
613 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
614 // and insert them into the cache_flags temp table
615 $sql = "SELECT ip, COUNT(*)
616 FROM {log}
617 WHERE module = 'login' AND action = 'error'
618 AND time > ?
619 GROUP BY ip
620 HAVING COUNT(*) >= ?";
621 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
622 $rs = $DB->get_recordset_sql($sql, $params);
623 foreach ($rs as $iprec) {
624 if (!empty($iprec->ip)) {
625 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
626 }
627 }
628 $rs->close();
629
630 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
631 // and insert them into the cache_flags temp table
632 $sql = "SELECT info, count(*)
633 FROM {log}
634 WHERE module = 'login' AND action = 'error'
635 AND time > ?
636 GROUP BY info
637 HAVING count(*) >= ?";
638 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
639 $rs = $DB->get_recordset_sql($sql, $params);
640 foreach ($rs as $inforec) {
641 if (!empty($inforec->info)) {
642 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
643 }
644 }
645 $rs->close();
646
647 // Now, select all the login error logged records belonging to the ips and infos
648 // since lastnotifyfailure, that we have stored in the cache_flags table
a415ecc2
RT
649 $sql = "SELECT * FROM (
650 SELECT l.*, u.firstname, u.lastname
50ed196e
PS
651 FROM {log} l
652 JOIN {cache_flags} cf ON l.ip = cf.name
653 LEFT JOIN {user} u ON l.userid = u.id
654 WHERE l.module = 'login' AND l.action = 'error'
655 AND l.time > ?
656 AND cf.flagtype = 'login_failure_by_ip'
657 UNION ALL
658 SELECT l.*, u.firstname, u.lastname
659 FROM {log} l
660 JOIN {cache_flags} cf ON l.info = 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 > ?
a415ecc2
RT
664 AND cf.flagtype = 'login_failure_by_info') t
665 ORDER BY t.time DESC";
50ed196e
PS
666 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
667
668 // Init some variables
669 $count = 0;
670 $messages = '';
671 // Iterate over the logs recordset
672 $rs = $DB->get_recordset_sql($sql, $params);
673 foreach ($rs as $log) {
674 $log->time = userdate($log->time);
675 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
676 $count++;
677 }
678 $rs->close();
679
680 // If we haven't run in the last hour and
681 // we have something useful to report and we
682 // are actually supposed to be reporting to somebody
683 if ((time() - HOURSECS) > $CFG->lastnotifyfailure && $count > 0 && is_array($recip) && count($recip) > 0) {
684 $site = get_site();
685 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
686 // Calculate the complete body of notification (start + messages + end)
687 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
688 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
689 $messages .
690 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
691
692 // For each destination, send mail
693 mtrace('Emailing admins about '. $count .' failed login attempts');
694 foreach ($recip as $admin) {
695 //emailing the admins directly rather than putting these through the messaging system
696 email_to_user($admin,get_admin(), $subject, $body);
697 }
698
699 // Update lastnotifyfailure with current time
700 set_config('lastnotifyfailure', time());
701 }
702
703 // Finally, delete all the temp records we have created in cache_flags
704 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
705}