MDL-33318 lib : code style fix
[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
177 if (!empty($CFG->notifyloginfailures)) {
178 notify_login_failures();
179 mtrace(' Notified login failured');
180 }
181
182
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');
186
28bd3d9a 187
50ed196e 188 // Session gc
28bd3d9a 189 session_gc();
50ed196e 190 mtrace("Cleaned up stale user sessions");
28bd3d9a 191
28bd3d9a 192
50ed196e
PS
193 // Run the auth cron, if any before enrolments
194 // because it might add users that will be needed in enrol plugins
195 $auths = get_enabled_auth_plugins();
196 mtrace("Running auth crons if required...");
197 foreach ($auths as $auth) {
198 $authplugin = get_auth_plugin($auth);
199 if (method_exists($authplugin, 'cron')) {
200 mtrace("Running cron for auth/$auth...");
201 $authplugin->cron();
202 if (!empty($authplugin->log)) {
203 mtrace($authplugin->log);
204 }
205 }
206 unset($authplugin);
207 }
208 // Generate new password emails for users - ppl expect these generated asap
209 if ($DB->count_records('user_preferences', array('name'=>'create_password', 'value'=>'1'))) {
210 mtrace('Creating passwords for new users...');
211 $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email, u.firstname,
212 u.lastname, u.username,
213 p.id as prefid
214 FROM {user} u
215 JOIN {user_preferences} p ON u.id=p.userid
daa8b1ac 216 WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin'");
50ed196e 217
daa8b1ac 218 // note: we can not send emails to suspended accounts
50ed196e
PS
219 foreach ($newusers as $newuser) {
220 if (setnew_password_and_mail($newuser)) {
221 unset_user_preference('create_password', $newuser);
222 set_user_preference('auth_forcepasswordchange', 1, $newuser);
223 } else {
224 trigger_error("Could not create and mail new user password!");
225 }
226 }
227 $newusers->close();
228 }
229
230
231 // It is very important to run enrol early
232 // because other plugins depend on correct enrolment info.
233 mtrace("Running enrol crons if required...");
234 $enrols = enrol_get_plugins(true);
235 foreach($enrols as $ename=>$enrol) {
236 // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
237 if (!$enrol->is_cron_required()) {
238 continue;
239 }
240 mtrace("Running cron for enrol_$ename...");
241 $enrol->cron();
242 $enrol->set_config('lastcron', time());
243 }
244
245
246 // Run all cron jobs for each module
28bd3d9a
PS
247 mtrace("Starting activity modules");
248 get_mailer('buffer');
249 if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
250 foreach ($mods as $mod) {
251 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
252 if (file_exists($libfile)) {
253 include_once($libfile);
254 $cron_function = $mod->name."_cron";
255 if (function_exists($cron_function)) {
256 mtrace("Processing module function $cron_function ...", '');
257 $pre_dbqueries = null;
258 $pre_dbqueries = $DB->perf_get_queries();
259 $pre_time = microtime(1);
260 if ($cron_function()) {
f685e830 261 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id));
28bd3d9a
PS
262 }
263 if (isset($pre_dbqueries)) {
264 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
265 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
266 }
50ed196e 267 // Reset possible changes by modules to time_limit. MDL-11597
28bd3d9a
PS
268 @set_time_limit(0);
269 mtrace("done.");
270 }
271 }
272 }
273 }
274 get_mailer('close');
275 mtrace("Finished activity modules");
276
50ed196e 277
28bd3d9a
PS
278 mtrace("Starting blocks");
279 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
50ed196e 280 // We will need the base class.
28bd3d9a
PS
281 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
282 foreach ($blocks as $block) {
283 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
284 if (file_exists($blockfile)) {
285 require_once($blockfile);
286 $classname = 'block_'.$block->name;
287 $blockobj = new $classname;
288 if (method_exists($blockobj,'cron')) {
289 mtrace("Processing cron function for ".$block->name.'....','');
290 if ($blockobj->cron()) {
f685e830 291 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id));
28bd3d9a 292 }
50ed196e 293 // Reset possible changes by blocks to time_limit. MDL-11597
28bd3d9a
PS
294 @set_time_limit(0);
295 mtrace('done.');
296 }
297 }
298
299 }
300 }
301 mtrace('Finished blocks');
302
50ed196e 303
b5541735
PS
304 mtrace('Starting admin reports');
305 cron_execute_plugin_type('report');
306 mtrace('Finished admin reports');
307
50ed196e
PS
308
309 mtrace('Starting main gradebook job...');
28bd3d9a
PS
310 grade_cron();
311 mtrace('done.');
312
313
314 mtrace('Starting processing the event queue...');
315 events_cron();
316 mtrace('done.');
317
318
319 if ($CFG->enablecompletion) {
320 // Completion cron
321 mtrace('Starting the completion cron...');
322 require_once($CFG->libdir . '/completion/cron.php');
323 completion_cron();
324 mtrace('done');
325 }
326
327
328 if ($CFG->enableportfolios) {
329 // Portfolio cron
330 mtrace('Starting the portfolio cron...');
331 require_once($CFG->libdir . '/portfoliolib.php');
332 portfolio_cron();
333 mtrace('done');
334 }
335
50ed196e 336
8cf1862c
DM
337 //now do plagiarism checks
338 require_once($CFG->libdir.'/plagiarismlib.php');
339 plagiarism_cron();
340
28bd3d9a 341
b5541735
PS
342 mtrace('Starting course reports');
343 cron_execute_plugin_type('coursereport');
344 mtrace('Finished course reports');
28bd3d9a 345
50ed196e 346
b5541735
PS
347 // run gradebook import/export/report cron
348 mtrace('Starting gradebook plugins');
349 cron_execute_plugin_type('gradeimport');
350 cron_execute_plugin_type('gradeexport');
351 cron_execute_plugin_type('gradereport');
352 mtrace('Finished gradebook plugins');
28bd3d9a 353
50ed196e 354
28bd3d9a
PS
355 // Run external blog cron if needed
356 if ($CFG->useexternalblogs) {
357 require_once($CFG->dirroot . '/blog/lib.php');
358 mtrace("Fetching external blog entries...", '');
359 $sql = "timefetched < ? OR timefetched = 0";
e2bb3c92 360 $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
28bd3d9a
PS
361
362 foreach ($externalblogs as $eb) {
363 blog_sync_external_entries($eb);
364 }
b5541735 365 mtrace('done.');
28bd3d9a 366 }
28bd3d9a
PS
367 // Run blog associations cleanup
368 if ($CFG->useblogassociations) {
369 require_once($CFG->dirroot . '/blog/lib.php');
370 // delete entries whose contextids no longer exists
371 mtrace("Deleting blog associations linked to non-existent contexts...", '');
372 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
b5541735 373 mtrace('done.');
28bd3d9a
PS
374 }
375
50ed196e 376
28bd3d9a
PS
377 //Run registration updated cron
378 mtrace(get_string('siteupdatesstart', 'hub'));
a91b4aa6 379 require_once($CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php');
28bd3d9a
PS
380 $registrationmanager = new registration_manager();
381 $registrationmanager->cron();
382 mtrace(get_string('siteupdatesend', 'hub'));
383
19d11b3b 384 // If enabled, fetch information about available updates and eventually notify site admins
fef693c8
DM
385 if (empty($CFG->disableupdatenotifications)) {
386 require_once($CFG->libdir.'/pluginlib.php');
387 $updateschecker = available_update_checker::instance();
388 $updateschecker->cron();
389 }
28bd3d9a
PS
390
391 //cleanup old session linked tokens
392 //deletes the session linked tokens that are over a day old.
393 mtrace("Deleting session linked tokens more than one day old...", '');
394 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
395 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
396 mtrace('done.');
397
50ed196e 398
b5541735
PS
399 // all other plugins
400 cron_execute_plugin_type('message', 'message plugins');
401 cron_execute_plugin_type('filter', 'filters');
e4a626b9 402 cron_execute_plugin_type('editor', 'editors');
b5541735
PS
403 cron_execute_plugin_type('format', 'course formats');
404 cron_execute_plugin_type('profilefield', 'profile fields');
405 cron_execute_plugin_type('webservice', 'webservices');
67233725 406 cron_execute_plugin_type('repository', 'repository plugins');
c2f5e2ab
TH
407 cron_execute_plugin_type('qbehaviour', 'question behaviours');
408 cron_execute_plugin_type('qformat', 'question import/export formats');
b5541735
PS
409 cron_execute_plugin_type('qtype', 'question types');
410 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
411 cron_execute_plugin_type('theme', 'themes');
67a6243a 412 cron_execute_plugin_type('tool', 'admin tools');
b5541735 413
50ed196e 414
b5541735 415 // and finally run any local cronjobs, if any
28bd3d9a
PS
416 if ($locals = get_plugin_list('local')) {
417 mtrace('Processing customized cron scripts ...', '');
b5541735
PS
418 // new cron functions in lib.php first
419 cron_execute_plugin_type('local');
420 // legacy cron files are executed directly
28bd3d9a
PS
421 foreach ($locals as $local => $localdir) {
422 if (file_exists("$localdir/cron.php")) {
423 include("$localdir/cron.php");
424 }
425 }
426 mtrace('done.');
427 }
428
50ed196e
PS
429
430 // Run automated backups if required - these may take a long time to execute
431 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
432 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
433 backup_cron_automated_helper::run_automated_backup();
434
435
436 // Run stats as at the end because they are known to take very long time on large sites
437 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
438 require_once($CFG->dirroot.'/lib/statslib.php');
439 // check we're not before our runtime
440 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
441
442 if (time() > $timetocheck) {
443 // process configured number of days as max (defaulting to 31)
444 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
445 if (stats_cron_daily($maxdays)) {
446 if (stats_cron_weekly()) {
447 if (stats_cron_monthly()) {
448 stats_clean_old();
449 }
450 }
451 }
452 @set_time_limit(0);
453 } else {
454 mtrace('Next stats run after:'. userdate($timetocheck));
455 }
456 }
457
458
459 // cleanup file trash - not very important
460 $fs = get_file_storage();
461 $fs->cron();
462
67233725
DC
463 mtrace("Clean up cached external files");
464 // 1 week
465 cache_file::cleanup(array(), 60 * 60 * 24 * 7);
50ed196e 466
28bd3d9a
PS
467 mtrace("Cron script completed correctly");
468
469 $difftime = microtime_diff($starttime, microtime());
470 mtrace("Execution took ".$difftime." seconds");
cbb9e9b8 471}
b5541735 472
e4a626b9 473/**
474 * Executes cron functions for a specific type of plugin.
50ed196e 475 *
e4a626b9 476 * @param string $plugintype Plugin type (e.g. 'report')
477 * @param string $description If specified, will display 'Starting (whatever)'
478 * and 'Finished (whatever)' lines, otherwise does not display
479 */
b5541735
PS
480function cron_execute_plugin_type($plugintype, $description = null) {
481 global $DB;
482
e4a626b9 483 // Get list from plugin => function for all plugins
484 $plugins = get_plugin_list_with_function($plugintype, 'cron');
485
486 // Modify list for backward compatibility (different files/names)
487 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
b5541735 488
e4a626b9 489 // Return if no plugins with cron function to process
b5541735
PS
490 if (!$plugins) {
491 return;
492 }
493
494 if ($description) {
495 mtrace('Starting '.$description);
496 }
497
498 foreach ($plugins as $component=>$cronfunction) {
cd092ece 499 $dir = get_component_directory($component);
e4a626b9 500
501 // Get cron period if specified in version.php, otherwise assume every cron
b5541735
PS
502 $cronperiod = 0;
503 if (file_exists("$dir/version.php")) {
504 $plugin = new stdClass();
505 include("$dir/version.php");
506 if (isset($plugin->cron)) {
507 $cronperiod = $plugin->cron;
508 }
509 }
510
e4a626b9 511 // Using last cron and cron period, don't run if it already ran recently
b5541735 512 $lastcron = get_config($component, 'lastcron');
e4a626b9 513 if ($cronperiod && $lastcron) {
b5541735
PS
514 if ($lastcron + $cronperiod > time()) {
515 // do not execute cron yet
516 continue;
517 }
518 }
519
e4a626b9 520 mtrace('Processing cron function for ' . $component . '...');
b5541735 521 $pre_dbqueries = $DB->perf_get_queries();
e4a626b9 522 $pre_time = microtime(true);
b5541735
PS
523
524 $cronfunction();
525
e4a626b9 526 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
527 round(microtime(true) - $pre_time, 2) . " seconds)");
b5541735
PS
528
529 set_config('lastcron', time(), $component);
4332cc46 530 @set_time_limit(0);
b5541735
PS
531 }
532
533 if ($description) {
e4a626b9 534 mtrace('Finished ' . $description);
b5541735
PS
535 }
536}
537
e4a626b9 538/**
539 * Used to add in old-style cron functions within plugins that have not been converted to the
540 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
541 * cron.php and some used a different name.)
50ed196e 542 *
e4a626b9 543 * @param string $plugintype Plugin type e.g. 'report'
544 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
545 * 'report_frog_cron') for plugin cron functions that were already found using the new API
546 * @return array Revised version of $plugins that adds in any extra plugin functions found by
547 * looking in the older location
548 */
549function cron_bc_hack_plugin_functions($plugintype, $plugins) {
550 global $CFG; // mandatory in case it is referenced by include()d PHP script
551
552 if ($plugintype === 'report') {
553 // Admin reports only - not course report because course report was
554 // never implemented before, so doesn't need BC
555 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) {
556 $component = $plugintype . '_' . $pluginname;
b5541735 557 if (isset($plugins[$component])) {
e4a626b9 558 // We already have detected the function using the new API
b5541735
PS
559 continue;
560 }
561 if (!file_exists("$dir/cron.php")) {
e4a626b9 562 // No old style cron file present
b5541735
PS
563 continue;
564 }
565 include_once("$dir/cron.php");
e4a626b9 566 $cronfunction = $component . '_cron';
b5541735
PS
567 if (function_exists($cronfunction)) {
568 $plugins[$component] = $cronfunction;
569 } else {
e4a626b9 570 debugging("Invalid legacy cron.php detected in $component, " .
571 "please use lib.php instead");
b5541735
PS
572 }
573 }
b5541735 574 } else if (strpos($plugintype, 'grade') === 0) {
e4a626b9 575 // Detect old style cron function names
576 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
577 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
b5541735
PS
578 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) {
579 $component = $plugintype.'_'.$pluginname;
580 if (isset($plugins[$component])) {
e4a626b9 581 // We already have detected the function using the new API
b5541735
PS
582 continue;
583 }
584 if (!file_exists("$dir/lib.php")) {
585 continue;
586 }
587 include_once("$dir/lib.php");
e4a626b9 588 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
589 $pluginname . '_cron';
b5541735
PS
590 if (function_exists($cronfunction)) {
591 $plugins[$component] = $cronfunction;
592 }
593 }
594 }
595
596 return $plugins;
50ed196e
PS
597}
598
599
600/**
601 * Notify admin users or admin user of any failed logins (since last notification).
602 *
603 * Note that this function must be only executed from the cron script
604 * It uses the cache_flags system to store temporary records, deleting them
605 * by name before finishing
606 */
607function notify_login_failures() {
608 global $CFG, $DB, $OUTPUT;
609
610 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
611
612 if (empty($CFG->lastnotifyfailure)) {
613 $CFG->lastnotifyfailure=0;
614 }
615
616 // we need to deal with the threshold stuff first.
617 if (empty($CFG->notifyloginthreshold)) {
618 $CFG->notifyloginthreshold = 10; // default to something sensible.
619 }
620
621 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
622 // and insert them into the cache_flags temp table
623 $sql = "SELECT ip, COUNT(*)
624 FROM {log}
625 WHERE module = 'login' AND action = 'error'
626 AND time > ?
627 GROUP BY ip
628 HAVING COUNT(*) >= ?";
629 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
630 $rs = $DB->get_recordset_sql($sql, $params);
631 foreach ($rs as $iprec) {
632 if (!empty($iprec->ip)) {
633 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
634 }
635 }
636 $rs->close();
637
638 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
639 // and insert them into the cache_flags temp table
640 $sql = "SELECT info, count(*)
641 FROM {log}
642 WHERE module = 'login' AND action = 'error'
643 AND time > ?
644 GROUP BY info
645 HAVING count(*) >= ?";
646 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
647 $rs = $DB->get_recordset_sql($sql, $params);
648 foreach ($rs as $inforec) {
649 if (!empty($inforec->info)) {
650 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
651 }
652 }
653 $rs->close();
654
655 // Now, select all the login error logged records belonging to the ips and infos
656 // since lastnotifyfailure, that we have stored in the cache_flags table
a415ecc2
RT
657 $sql = "SELECT * FROM (
658 SELECT l.*, u.firstname, u.lastname
50ed196e
PS
659 FROM {log} l
660 JOIN {cache_flags} cf ON l.ip = cf.name
661 LEFT JOIN {user} u ON l.userid = u.id
662 WHERE l.module = 'login' AND l.action = 'error'
663 AND l.time > ?
664 AND cf.flagtype = 'login_failure_by_ip'
665 UNION ALL
666 SELECT l.*, u.firstname, u.lastname
667 FROM {log} l
668 JOIN {cache_flags} cf ON l.info = cf.name
669 LEFT JOIN {user} u ON l.userid = u.id
670 WHERE l.module = 'login' AND l.action = 'error'
671 AND l.time > ?
a415ecc2
RT
672 AND cf.flagtype = 'login_failure_by_info') t
673 ORDER BY t.time DESC";
50ed196e
PS
674 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
675
676 // Init some variables
677 $count = 0;
678 $messages = '';
679 // Iterate over the logs recordset
680 $rs = $DB->get_recordset_sql($sql, $params);
681 foreach ($rs as $log) {
682 $log->time = userdate($log->time);
683 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
684 $count++;
685 }
686 $rs->close();
687
688 // If we haven't run in the last hour and
689 // we have something useful to report and we
690 // are actually supposed to be reporting to somebody
691 if ((time() - HOURSECS) > $CFG->lastnotifyfailure && $count > 0 && is_array($recip) && count($recip) > 0) {
692 $site = get_site();
693 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
694 // Calculate the complete body of notification (start + messages + end)
695 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
696 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
697 $messages .
698 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
699
700 // For each destination, send mail
701 mtrace('Emailing admins about '. $count .' failed login attempts');
702 foreach ($recip as $admin) {
703 //emailing the admins directly rather than putting these through the messaging system
704 email_to_user($admin,get_admin(), $subject, $body);
705 }
706
707 // Update lastnotifyfailure with current time
708 set_config('lastnotifyfailure', time());
709 }
710
711 // Finally, delete all the temp records we have created in cache_flags
712 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
713}