MDL-25476 messages: switched some notification emails to come from the support contac...
[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
14e2704a
EL
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.
50ed196e
PS
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));
14e2704a 127 // Delete records from backup_controllers.
50ed196e
PS
128 $DB->execute("DELETE FROM {backup_controllers}
129 WHERE timecreated < ?", array($loglifetime));
130 mtrace(" Deleted old backup records");
131 }
132
133
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 }
140
141
142 if (!empty($CFG->usetags)) {
143 require_once($CFG->dirroot.'/tag/lib.php');
144 tag_cron();
145 mtrace(' Executed tag cron');
146 }
147
148
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');
156
157
158 // Remove expired cache flags
159 gc_cache_flags();
160 mtrace(' Cleaned cache flags');
161
162
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 }
169
170 mtrace("...finished clean-up tasks");
171
172 } // End of occasional clean-up tasks
173
174
175 // Send login failures notification - brute force protection in moodle is weak,
176 // we should at least send notices early in each cron execution
192a8e13
EM
177 if (notify_login_failures()) {
178 mtrace(' Notified login failures');
50ed196e
PS
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'));
a91b4aa6 378 require_once($CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php');
28bd3d9a
PS
379 $registrationmanager = new registration_manager();
380 $registrationmanager->cron();
381 mtrace(get_string('siteupdatesend', 'hub'));
382
19d11b3b 383 // If enabled, fetch information about available updates and eventually notify site admins
fef693c8
DM
384 if (empty($CFG->disableupdatenotifications)) {
385 require_once($CFG->libdir.'/pluginlib.php');
386 $updateschecker = available_update_checker::instance();
387 $updateschecker->cron();
388 }
28bd3d9a
PS
389
390 //cleanup old session linked tokens
391 //deletes the session linked tokens that are over a day old.
392 mtrace("Deleting session linked tokens more than one day old...", '');
393 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
394 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
395 mtrace('done.');
396
50ed196e 397
b5541735
PS
398 // all other plugins
399 cron_execute_plugin_type('message', 'message plugins');
400 cron_execute_plugin_type('filter', 'filters');
e4a626b9 401 cron_execute_plugin_type('editor', 'editors');
b5541735
PS
402 cron_execute_plugin_type('format', 'course formats');
403 cron_execute_plugin_type('profilefield', 'profile fields');
404 cron_execute_plugin_type('webservice', 'webservices');
67233725 405 cron_execute_plugin_type('repository', 'repository plugins');
c2f5e2ab
TH
406 cron_execute_plugin_type('qbehaviour', 'question behaviours');
407 cron_execute_plugin_type('qformat', 'question import/export formats');
b5541735
PS
408 cron_execute_plugin_type('qtype', 'question types');
409 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
410 cron_execute_plugin_type('theme', 'themes');
67a6243a 411 cron_execute_plugin_type('tool', 'admin tools');
b5541735 412
50ed196e 413
b5541735 414 // and finally run any local cronjobs, if any
28bd3d9a
PS
415 if ($locals = get_plugin_list('local')) {
416 mtrace('Processing customized cron scripts ...', '');
b5541735
PS
417 // new cron functions in lib.php first
418 cron_execute_plugin_type('local');
419 // legacy cron files are executed directly
28bd3d9a
PS
420 foreach ($locals as $local => $localdir) {
421 if (file_exists("$localdir/cron.php")) {
422 include("$localdir/cron.php");
423 }
424 }
425 mtrace('done.');
426 }
427
50ed196e
PS
428
429 // Run automated backups if required - these may take a long time to execute
430 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
431 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
432 backup_cron_automated_helper::run_automated_backup();
433
434
435 // Run stats as at the end because they are known to take very long time on large sites
436 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
437 require_once($CFG->dirroot.'/lib/statslib.php');
438 // check we're not before our runtime
439 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
440
441 if (time() > $timetocheck) {
442 // process configured number of days as max (defaulting to 31)
443 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
444 if (stats_cron_daily($maxdays)) {
445 if (stats_cron_weekly()) {
446 if (stats_cron_monthly()) {
447 stats_clean_old();
448 }
449 }
450 }
451 @set_time_limit(0);
452 } else {
453 mtrace('Next stats run after:'. userdate($timetocheck));
454 }
455 }
456
457
458 // cleanup file trash - not very important
459 $fs = get_file_storage();
460 $fs->cron();
461
67233725
DC
462 mtrace("Clean up cached external files");
463 // 1 week
464 cache_file::cleanup(array(), 60 * 60 * 24 * 7);
50ed196e 465
28bd3d9a
PS
466 mtrace("Cron script completed correctly");
467
468 $difftime = microtime_diff($starttime, microtime());
469 mtrace("Execution took ".$difftime." seconds");
cbb9e9b8 470}
b5541735 471
e4a626b9 472/**
473 * Executes cron functions for a specific type of plugin.
50ed196e 474 *
e4a626b9 475 * @param string $plugintype Plugin type (e.g. 'report')
476 * @param string $description If specified, will display 'Starting (whatever)'
477 * and 'Finished (whatever)' lines, otherwise does not display
478 */
b5541735
PS
479function cron_execute_plugin_type($plugintype, $description = null) {
480 global $DB;
481
e4a626b9 482 // Get list from plugin => function for all plugins
483 $plugins = get_plugin_list_with_function($plugintype, 'cron');
484
485 // Modify list for backward compatibility (different files/names)
486 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
b5541735 487
e4a626b9 488 // Return if no plugins with cron function to process
b5541735
PS
489 if (!$plugins) {
490 return;
491 }
492
493 if ($description) {
494 mtrace('Starting '.$description);
495 }
496
497 foreach ($plugins as $component=>$cronfunction) {
cd092ece 498 $dir = get_component_directory($component);
e4a626b9 499
500 // Get cron period if specified in version.php, otherwise assume every cron
b5541735
PS
501 $cronperiod = 0;
502 if (file_exists("$dir/version.php")) {
503 $plugin = new stdClass();
504 include("$dir/version.php");
505 if (isset($plugin->cron)) {
506 $cronperiod = $plugin->cron;
507 }
508 }
509
e4a626b9 510 // Using last cron and cron period, don't run if it already ran recently
b5541735 511 $lastcron = get_config($component, 'lastcron');
e4a626b9 512 if ($cronperiod && $lastcron) {
b5541735
PS
513 if ($lastcron + $cronperiod > time()) {
514 // do not execute cron yet
515 continue;
516 }
517 }
518
e4a626b9 519 mtrace('Processing cron function for ' . $component . '...');
b5541735 520 $pre_dbqueries = $DB->perf_get_queries();
e4a626b9 521 $pre_time = microtime(true);
b5541735
PS
522
523 $cronfunction();
524
e4a626b9 525 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
526 round(microtime(true) - $pre_time, 2) . " seconds)");
b5541735
PS
527
528 set_config('lastcron', time(), $component);
4332cc46 529 @set_time_limit(0);
b5541735
PS
530 }
531
532 if ($description) {
e4a626b9 533 mtrace('Finished ' . $description);
b5541735
PS
534 }
535}
536
e4a626b9 537/**
538 * Used to add in old-style cron functions within plugins that have not been converted to the
539 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
540 * cron.php and some used a different name.)
50ed196e 541 *
e4a626b9 542 * @param string $plugintype Plugin type e.g. 'report'
543 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
544 * 'report_frog_cron') for plugin cron functions that were already found using the new API
545 * @return array Revised version of $plugins that adds in any extra plugin functions found by
546 * looking in the older location
547 */
548function cron_bc_hack_plugin_functions($plugintype, $plugins) {
549 global $CFG; // mandatory in case it is referenced by include()d PHP script
550
551 if ($plugintype === 'report') {
552 // Admin reports only - not course report because course report was
553 // never implemented before, so doesn't need BC
554 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
555 $component = $plugintype . '_' . $pluginname;
b5541735 556 if (isset($plugins[$component])) {
e4a626b9 557 // We already have detected the function using the new API
b5541735
PS
558 continue;
559 }
560 if (!file_exists("$dir/cron.php")) {
e4a626b9 561 // No old style cron file present
b5541735
PS
562 continue;
563 }
564 include_once("$dir/cron.php");
e4a626b9 565 $cronfunction = $component . '_cron';
b5541735
PS
566 if (function_exists($cronfunction)) {
567 $plugins[$component] = $cronfunction;
568 } else {
e4a626b9 569 debugging("Invalid legacy cron.php detected in $component, " .
570 "please use lib.php instead");
b5541735
PS
571 }
572 }
b5541735 573 } else if (strpos($plugintype, 'grade') === 0) {
e4a626b9 574 // Detect old style cron function names
575 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
576 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
b5541735
PS
577 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
578 $component = $plugintype.'_'.$pluginname;
579 if (isset($plugins[$component])) {
e4a626b9 580 // We already have detected the function using the new API
b5541735
PS
581 continue;
582 }
583 if (!file_exists("$dir/lib.php")) {
584 continue;
585 }
586 include_once("$dir/lib.php");
e4a626b9 587 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
588 $pluginname . '_cron';
b5541735
PS
589 if (function_exists($cronfunction)) {
590 $plugins[$component] = $cronfunction;
591 }
592 }
593 }
594
595 return $plugins;
50ed196e
PS
596}
597
598
599/**
600 * Notify admin users or admin user of any failed logins (since last notification).
601 *
602 * Note that this function must be only executed from the cron script
603 * It uses the cache_flags system to store temporary records, deleting them
604 * by name before finishing
192a8e13
EM
605 *
606 * @return bool True if executed, false if not
50ed196e
PS
607 */
608function notify_login_failures() {
609 global $CFG, $DB, $OUTPUT;
610
192a8e13
EM
611 if (empty($CFG->notifyloginfailures)) {
612 return false;
613 }
614
50ed196e
PS
615 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
616
aa12ec98
EL
617 if (empty($CFG->lastnotifyfailure)) {
618 $CFG->lastnotifyfailure=0;
619 }
620
192a8e13
EM
621 // If it has been less than an hour, or if there are no recipients, don't execute.
622 if (((time() - HOURSECS) < $CFG->lastnotifyfailure) || !is_array($recip) || count($recip) <= 0) {
623 return false;
624 }
625
50ed196e
PS
626 // we need to deal with the threshold stuff first.
627 if (empty($CFG->notifyloginthreshold)) {
628 $CFG->notifyloginthreshold = 10; // default to something sensible.
629 }
630
631 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
632 // and insert them into the cache_flags temp table
633 $sql = "SELECT ip, COUNT(*)
634 FROM {log}
635 WHERE module = 'login' AND action = 'error'
636 AND time > ?
637 GROUP BY ip
638 HAVING COUNT(*) >= ?";
639 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
640 $rs = $DB->get_recordset_sql($sql, $params);
641 foreach ($rs as $iprec) {
642 if (!empty($iprec->ip)) {
643 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
644 }
645 }
646 $rs->close();
647
648 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
649 // and insert them into the cache_flags temp table
650 $sql = "SELECT info, count(*)
651 FROM {log}
652 WHERE module = 'login' AND action = 'error'
653 AND time > ?
654 GROUP BY info
655 HAVING count(*) >= ?";
656 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
657 $rs = $DB->get_recordset_sql($sql, $params);
658 foreach ($rs as $inforec) {
659 if (!empty($inforec->info)) {
660 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
661 }
662 }
663 $rs->close();
664
665 // Now, select all the login error logged records belonging to the ips and infos
666 // since lastnotifyfailure, that we have stored in the cache_flags table
a415ecc2
RT
667 $sql = "SELECT * FROM (
668 SELECT l.*, u.firstname, u.lastname
50ed196e
PS
669 FROM {log} l
670 JOIN {cache_flags} cf ON l.ip = cf.name
671 LEFT JOIN {user} u ON l.userid = u.id
672 WHERE l.module = 'login' AND l.action = 'error'
673 AND l.time > ?
674 AND cf.flagtype = 'login_failure_by_ip'
675 UNION ALL
676 SELECT l.*, u.firstname, u.lastname
677 FROM {log} l
678 JOIN {cache_flags} cf ON l.info = cf.name
679 LEFT JOIN {user} u ON l.userid = u.id
680 WHERE l.module = 'login' AND l.action = 'error'
681 AND l.time > ?
a415ecc2
RT
682 AND cf.flagtype = 'login_failure_by_info') t
683 ORDER BY t.time DESC";
50ed196e
PS
684 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
685
686 // Init some variables
687 $count = 0;
688 $messages = '';
689 // Iterate over the logs recordset
690 $rs = $DB->get_recordset_sql($sql, $params);
691 foreach ($rs as $log) {
692 $log->time = userdate($log->time);
693 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
694 $count++;
695 }
696 $rs->close();
697
192a8e13
EM
698 // If we have something useful to report.
699 if ($count > 0) {
50ed196e
PS
700 $site = get_site();
701 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
702 // Calculate the complete body of notification (start + messages + end)
703 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
704 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
705 $messages .
706 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
707
708 // For each destination, send mail
709 mtrace('Emailing admins about '. $count .' failed login attempts');
710 foreach ($recip as $admin) {
711 //emailing the admins directly rather than putting these through the messaging system
6737eda4 712 email_to_user($admin, generate_email_supportuser(), $subject, $body);
50ed196e 713 }
50ed196e
PS
714 }
715
54c2756c
EM
716 // Update lastnotifyfailure with current time
717 set_config('lastnotifyfailure', time());
718
50ed196e
PS
719 // Finally, delete all the temp records we have created in cache_flags
720 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
192a8e13
EM
721
722 return true;
50ed196e 723}