MDL-42754 Messages: Show noreply user notifications
[moodle.git] / lib / cronlib.php
blob552398be4b76d8421f37875873e8254ab6ed5d8e
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 set_debugging(DEBUG_DEVELOPER, true);
52 set_time_limit(0);
53 $starttime = microtime();
55 // Increase memory limit
56 raise_memory_limit(MEMORY_EXTRA);
58 // Emulate normal session - we use admin accoutn by default
59 cron_setup_user();
61 // Start output log
62 $timenow = time();
63 mtrace("Server Time: ".date('r', $timenow)."\n\n");
66 // Run cleanup core cron jobs, but not every time since they aren't too important.
67 // These don't have a timer to reduce load, so we'll use a random number
68 // to randomly choose the percentage of times we should run these jobs.
69 srand ((double) microtime() * 10000000);
70 $random100 = rand(0,100);
71 if ($random100 < 20) { // Approximately 20% of the time.
72 mtrace("Running clean-up tasks...");
73 cron_trace_time_and_memory();
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)");
87 $rs->close();
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 if (isguestuser($user) or is_siteadmin($user)) {
102 continue;
104 delete_user($user);
105 mtrace(" Deleted not fully setup user $user->username ($user->id)");
107 $rs->close();
111 // Delete old logs to save space (this might need a timer to slow it down...)
112 if (!empty($CFG->loglifetime)) { // value in days
113 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
114 $DB->delete_records_select("log", "time < ?", array($loglifetime));
115 mtrace(" Deleted old log records");
119 // Delete old backup_controllers and logs.
120 $loglifetime = get_config('backup', 'loglifetime');
121 if (!empty($loglifetime)) { // Value in days.
122 $loglifetime = $timenow - ($loglifetime * 3600 * 24);
123 // Delete child records from backup_logs.
124 $DB->execute("DELETE FROM {backup_logs}
125 WHERE EXISTS (
126 SELECT 'x'
127 FROM {backup_controllers} bc
128 WHERE bc.backupid = {backup_logs}.backupid
129 AND bc.timecreated < ?)", array($loglifetime));
130 // Delete records from backup_controllers.
131 $DB->execute("DELETE FROM {backup_controllers}
132 WHERE timecreated < ?", array($loglifetime));
133 mtrace(" Deleted old backup records");
137 // Delete old cached texts
138 if (!empty($CFG->cachetext)) { // Defined in config.php
139 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
140 $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
141 mtrace(" Deleted old cache_text records");
145 if (!empty($CFG->usetags)) {
146 require_once($CFG->dirroot.'/tag/lib.php');
147 tag_cron();
148 mtrace(' Executed tag cron');
152 // Context maintenance stuff
153 context_helper::cleanup_instances();
154 mtrace(' Cleaned up context instances');
155 context_helper::build_all_paths(false);
156 // If you suspect that the context paths are somehow corrupt
157 // replace the line below with: context_helper::build_all_paths(true);
158 mtrace(' Built context paths');
161 // Remove expired cache flags
162 gc_cache_flags();
163 mtrace(' Cleaned cache flags');
166 // Cleanup messaging
167 if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
168 $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
169 $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime'=>$notificationdeletetime));
170 mtrace(' Cleaned up read notifications');
173 mtrace(' Deleting temporary files...');
174 cron_delete_from_temp();
176 // Cleanup user password reset records
177 // Delete any reset request records which are expired by more than a day.
178 // (We keep recently expired requests around so we can give a different error msg to users who
179 // are trying to user a recently expired reset attempt).
180 $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
181 $earliestvalid = time() - $pwresettime - DAYSECS;
182 $DB->delete_records_select('user_password_resets', "timerequested < ?", array($earliestvalid));
183 mtrace(' Cleaned up old password reset records');
185 mtrace("...finished clean-up tasks");
187 } // End of occasional clean-up tasks
190 // Send login failures notification - brute force protection in moodle is weak,
191 // we should at least send notices early in each cron execution
192 if (notify_login_failures()) {
193 mtrace(' Notified login failures');
197 // Make sure all context instances are properly created - they may be required in auth, enrol, etc.
198 context_helper::create_instances();
199 mtrace(' Created missing context instances');
202 // Session gc.
203 mtrace("Running session gc tasks...");
204 \core\session\manager::gc();
205 mtrace("...finished stale session cleanup");
208 // Run the auth cron, if any before enrolments
209 // because it might add users that will be needed in enrol plugins
210 $auths = get_enabled_auth_plugins();
211 mtrace("Running auth crons if required...");
212 cron_trace_time_and_memory();
213 foreach ($auths as $auth) {
214 $authplugin = get_auth_plugin($auth);
215 if (method_exists($authplugin, 'cron')) {
216 mtrace("Running cron for auth/$auth...");
217 $authplugin->cron();
218 if (!empty($authplugin->log)) {
219 mtrace($authplugin->log);
222 unset($authplugin);
224 // Generate new password emails for users - ppl expect these generated asap
225 if ($DB->count_records('user_preferences', array('name'=>'create_password', 'value'=>'1'))) {
226 mtrace('Creating passwords for new users...');
227 $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email, u.firstname,
228 u.lastname, u.username, u.lang,
229 p.id as prefid
230 FROM {user} u
231 JOIN {user_preferences} p ON u.id=p.userid
232 WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0");
234 // note: we can not send emails to suspended accounts
235 foreach ($newusers as $newuser) {
236 // Use a low cost factor when generating bcrypt hash otherwise
237 // hashing would be slow when emailing lots of users. Hashes
238 // will be automatically updated to a higher cost factor the first
239 // time the user logs in.
240 if (setnew_password_and_mail($newuser, true)) {
241 unset_user_preference('create_password', $newuser);
242 set_user_preference('auth_forcepasswordchange', 1, $newuser);
243 } else {
244 trigger_error("Could not create and mail new user password!");
247 $newusers->close();
251 // It is very important to run enrol early
252 // because other plugins depend on correct enrolment info.
253 mtrace("Running enrol crons if required...");
254 $enrols = enrol_get_plugins(true);
255 foreach($enrols as $ename=>$enrol) {
256 // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
257 if (!$enrol->is_cron_required()) {
258 continue;
260 mtrace("Running cron for enrol_$ename...");
261 cron_trace_time_and_memory();
262 $enrol->cron();
263 $enrol->set_config('lastcron', time());
267 // Run all cron jobs for each module
268 mtrace("Starting activity modules");
269 get_mailer('buffer');
270 if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
271 foreach ($mods as $mod) {
272 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
273 if (file_exists($libfile)) {
274 include_once($libfile);
275 $cron_function = $mod->name."_cron";
276 if (function_exists($cron_function)) {
277 mtrace("Processing module function $cron_function ...", '');
278 cron_trace_time_and_memory();
279 $pre_dbqueries = null;
280 $pre_dbqueries = $DB->perf_get_queries();
281 $pre_time = microtime(1);
282 if ($cron_function()) {
283 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id));
285 if (isset($pre_dbqueries)) {
286 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
287 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
289 // Reset possible changes by modules to time_limit. MDL-11597
290 @set_time_limit(0);
291 mtrace("done.");
296 get_mailer('close');
297 mtrace("Finished activity modules");
300 mtrace("Starting blocks");
301 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
302 // We will need the base class.
303 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
304 foreach ($blocks as $block) {
305 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
306 if (file_exists($blockfile)) {
307 require_once($blockfile);
308 $classname = 'block_'.$block->name;
309 $blockobj = new $classname;
310 if (method_exists($blockobj,'cron')) {
311 mtrace("Processing cron function for ".$block->name.'....','');
312 cron_trace_time_and_memory();
313 if ($blockobj->cron()) {
314 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id));
316 // Reset possible changes by blocks to time_limit. MDL-11597
317 @set_time_limit(0);
318 mtrace('done.');
324 mtrace('Finished blocks');
327 mtrace('Starting admin reports');
328 cron_execute_plugin_type('report');
329 mtrace('Finished admin reports');
332 mtrace('Starting main gradebook job...');
333 cron_trace_time_and_memory();
334 grade_cron();
335 mtrace('done.');
338 mtrace('Starting processing the event queue...');
339 cron_trace_time_and_memory();
340 events_cron();
341 mtrace('done.');
344 if ($CFG->enablecompletion) {
345 // Completion cron
346 mtrace('Starting the completion cron...');
347 cron_trace_time_and_memory();
348 require_once($CFG->dirroot.'/completion/cron.php');
349 completion_cron();
350 mtrace('done');
354 if ($CFG->enableportfolios) {
355 // Portfolio cron
356 mtrace('Starting the portfolio cron...');
357 cron_trace_time_and_memory();
358 require_once($CFG->libdir . '/portfoliolib.php');
359 portfolio_cron();
360 mtrace('done');
364 //now do plagiarism checks
365 require_once($CFG->libdir.'/plagiarismlib.php');
366 plagiarism_cron();
369 mtrace('Starting course reports');
370 cron_execute_plugin_type('coursereport');
371 mtrace('Finished course reports');
374 // run gradebook import/export/report cron
375 mtrace('Starting gradebook plugins');
376 cron_execute_plugin_type('gradeimport');
377 cron_execute_plugin_type('gradeexport');
378 cron_execute_plugin_type('gradereport');
379 mtrace('Finished gradebook plugins');
381 // run calendar cron
382 require_once "{$CFG->dirroot}/calendar/lib.php";
383 calendar_cron();
385 // Run external blog cron if needed
386 if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
387 require_once($CFG->dirroot . '/blog/lib.php');
388 mtrace("Fetching external blog entries...", '');
389 cron_trace_time_and_memory();
390 $sql = "timefetched < ? OR timefetched = 0";
391 $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
393 foreach ($externalblogs as $eb) {
394 blog_sync_external_entries($eb);
396 mtrace('done.');
398 // Run blog associations cleanup
399 if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
400 require_once($CFG->dirroot . '/blog/lib.php');
401 // delete entries whose contextids no longer exists
402 mtrace("Deleting blog associations linked to non-existent contexts...", '');
403 cron_trace_time_and_memory();
404 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
405 mtrace('done.');
409 // Run question bank clean-up.
410 mtrace("Starting the question bank cron...", '');
411 cron_trace_time_and_memory();
412 require_once($CFG->libdir . '/questionlib.php');
413 question_bank::cron();
414 mtrace('done.');
417 //Run registration updated cron
418 mtrace(get_string('siteupdatesstart', 'hub'));
419 cron_trace_time_and_memory();
420 require_once($CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php');
421 $registrationmanager = new registration_manager();
422 $registrationmanager->cron();
423 mtrace(get_string('siteupdatesend', 'hub'));
425 // If enabled, fetch information about available updates and eventually notify site admins
426 if (empty($CFG->disableupdatenotifications)) {
427 $updateschecker = \core\update\checker::instance();
428 $updateschecker->cron();
431 //cleanup old session linked tokens
432 //deletes the session linked tokens that are over a day old.
433 mtrace("Deleting session linked tokens more than one day old...", '');
434 cron_trace_time_and_memory();
435 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
436 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
437 mtrace('done.');
440 // all other plugins
441 cron_execute_plugin_type('message', 'message plugins');
442 cron_execute_plugin_type('filter', 'filters');
443 cron_execute_plugin_type('editor', 'editors');
444 cron_execute_plugin_type('format', 'course formats');
445 cron_execute_plugin_type('profilefield', 'profile fields');
446 cron_execute_plugin_type('webservice', 'webservices');
447 cron_execute_plugin_type('repository', 'repository plugins');
448 cron_execute_plugin_type('qbehaviour', 'question behaviours');
449 cron_execute_plugin_type('qformat', 'question import/export formats');
450 cron_execute_plugin_type('qtype', 'question types');
451 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
452 cron_execute_plugin_type('theme', 'themes');
453 cron_execute_plugin_type('tool', 'admin tools');
456 // and finally run any local cronjobs, if any
457 if ($locals = core_component::get_plugin_list('local')) {
458 mtrace('Processing customized cron scripts ...', '');
459 // new cron functions in lib.php first
460 cron_execute_plugin_type('local');
461 // legacy cron files are executed directly
462 foreach ($locals as $local => $localdir) {
463 if (file_exists("$localdir/cron.php")) {
464 include("$localdir/cron.php");
467 mtrace('done.');
470 mtrace('Running cache cron routines');
471 cache_helper::cron();
472 mtrace('done.');
474 // Run automated backups if required - these may take a long time to execute
475 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
476 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
477 backup_cron_automated_helper::run_automated_backup();
480 // Run stats as at the end because they are known to take very long time on large sites
481 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
482 require_once($CFG->dirroot.'/lib/statslib.php');
483 // check we're not before our runtime
484 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
486 if (time() > $timetocheck) {
487 // process configured number of days as max (defaulting to 31)
488 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
489 if (stats_cron_daily($maxdays)) {
490 if (stats_cron_weekly()) {
491 if (stats_cron_monthly()) {
492 stats_clean_old();
496 @set_time_limit(0);
497 } else {
498 mtrace('Next stats run after:'. userdate($timetocheck));
502 // Run badges review cron.
503 mtrace("Starting badges cron...");
504 require_once($CFG->dirroot . '/badges/cron.php');
505 badge_cron();
506 mtrace('done.');
508 // cleanup file trash - not very important
509 $fs = get_file_storage();
510 $fs->cron();
512 mtrace("Cron script completed correctly");
514 gc_collect_cycles();
515 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
516 $difftime = microtime_diff($starttime, microtime());
517 mtrace("Execution took ".$difftime." seconds");
521 * Executes cron functions for a specific type of plugin.
523 * @param string $plugintype Plugin type (e.g. 'report')
524 * @param string $description If specified, will display 'Starting (whatever)'
525 * and 'Finished (whatever)' lines, otherwise does not display
527 function cron_execute_plugin_type($plugintype, $description = null) {
528 global $DB;
530 // Get list from plugin => function for all plugins
531 $plugins = get_plugin_list_with_function($plugintype, 'cron');
533 // Modify list for backward compatibility (different files/names)
534 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
536 // Return if no plugins with cron function to process
537 if (!$plugins) {
538 return;
541 if ($description) {
542 mtrace('Starting '.$description);
545 foreach ($plugins as $component=>$cronfunction) {
546 $dir = core_component::get_component_directory($component);
548 // Get cron period if specified in version.php, otherwise assume every cron
549 $cronperiod = 0;
550 if (file_exists("$dir/version.php")) {
551 $plugin = new stdClass();
552 include("$dir/version.php");
553 if (isset($plugin->cron)) {
554 $cronperiod = $plugin->cron;
558 // Using last cron and cron period, don't run if it already ran recently
559 $lastcron = get_config($component, 'lastcron');
560 if ($cronperiod && $lastcron) {
561 if ($lastcron + $cronperiod > time()) {
562 // do not execute cron yet
563 continue;
567 mtrace('Processing cron function for ' . $component . '...');
568 cron_trace_time_and_memory();
569 $pre_dbqueries = $DB->perf_get_queries();
570 $pre_time = microtime(true);
572 $cronfunction();
574 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
575 round(microtime(true) - $pre_time, 2) . " seconds)");
577 set_config('lastcron', time(), $component);
578 @set_time_limit(0);
581 if ($description) {
582 mtrace('Finished ' . $description);
587 * Used to add in old-style cron functions within plugins that have not been converted to the
588 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
589 * cron.php and some used a different name.)
591 * @param string $plugintype Plugin type e.g. 'report'
592 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
593 * 'report_frog_cron') for plugin cron functions that were already found using the new API
594 * @return array Revised version of $plugins that adds in any extra plugin functions found by
595 * looking in the older location
597 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
598 global $CFG; // mandatory in case it is referenced by include()d PHP script
600 if ($plugintype === 'report') {
601 // Admin reports only - not course report because course report was
602 // never implemented before, so doesn't need BC
603 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
604 $component = $plugintype . '_' . $pluginname;
605 if (isset($plugins[$component])) {
606 // We already have detected the function using the new API
607 continue;
609 if (!file_exists("$dir/cron.php")) {
610 // No old style cron file present
611 continue;
613 include_once("$dir/cron.php");
614 $cronfunction = $component . '_cron';
615 if (function_exists($cronfunction)) {
616 $plugins[$component] = $cronfunction;
617 } else {
618 debugging("Invalid legacy cron.php detected in $component, " .
619 "please use lib.php instead");
622 } else if (strpos($plugintype, 'grade') === 0) {
623 // Detect old style cron function names
624 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
625 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
626 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
627 $component = $plugintype.'_'.$pluginname;
628 if (isset($plugins[$component])) {
629 // We already have detected the function using the new API
630 continue;
632 if (!file_exists("$dir/lib.php")) {
633 continue;
635 include_once("$dir/lib.php");
636 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
637 $pluginname . '_cron';
638 if (function_exists($cronfunction)) {
639 $plugins[$component] = $cronfunction;
644 return $plugins;
648 * Output some standard information during cron runs. Specifically current time
649 * and memory usage. This method also does gc_collect_cycles() (before displaying
650 * memory usage) to try to help PHP manage memory better.
652 function cron_trace_time_and_memory() {
653 gc_collect_cycles();
654 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
658 * Notify admin users or admin user of any failed logins (since last notification).
660 * Note that this function must be only executed from the cron script
661 * It uses the cache_flags system to store temporary records, deleting them
662 * by name before finishing
664 * @return bool True if executed, false if not
666 function notify_login_failures() {
667 global $CFG, $DB, $OUTPUT;
669 if (empty($CFG->notifyloginfailures)) {
670 return false;
673 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
675 if (empty($CFG->lastnotifyfailure)) {
676 $CFG->lastnotifyfailure=0;
679 // If it has been less than an hour, or if there are no recipients, don't execute.
680 if (((time() - HOURSECS) < $CFG->lastnotifyfailure) || !is_array($recip) || count($recip) <= 0) {
681 return false;
684 // we need to deal with the threshold stuff first.
685 if (empty($CFG->notifyloginthreshold)) {
686 $CFG->notifyloginthreshold = 10; // default to something sensible.
689 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
690 // and insert them into the cache_flags temp table
691 $sql = "SELECT ip, COUNT(*)
692 FROM {log}
693 WHERE module = 'login' AND action = 'error'
694 AND time > ?
695 GROUP BY ip
696 HAVING COUNT(*) >= ?";
697 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
698 $rs = $DB->get_recordset_sql($sql, $params);
699 foreach ($rs as $iprec) {
700 if (!empty($iprec->ip)) {
701 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
704 $rs->close();
706 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
707 // and insert them into the cache_flags temp table
708 $sql = "SELECT info, count(*)
709 FROM {log}
710 WHERE module = 'login' AND action = 'error'
711 AND time > ?
712 GROUP BY info
713 HAVING count(*) >= ?";
714 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
715 $rs = $DB->get_recordset_sql($sql, $params);
716 foreach ($rs as $inforec) {
717 if (!empty($inforec->info)) {
718 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
721 $rs->close();
723 // Now, select all the login error logged records belonging to the ips and infos
724 // since lastnotifyfailure, that we have stored in the cache_flags table
725 $sql = "SELECT * FROM (
726 SELECT l.*, u.firstname, u.lastname
727 FROM {log} l
728 JOIN {cache_flags} cf ON l.ip = cf.name
729 LEFT JOIN {user} u ON l.userid = u.id
730 WHERE l.module = 'login' AND l.action = 'error'
731 AND l.time > ?
732 AND cf.flagtype = 'login_failure_by_ip'
733 UNION ALL
734 SELECT l.*, u.firstname, u.lastname
735 FROM {log} l
736 JOIN {cache_flags} cf ON l.info = cf.name
737 LEFT JOIN {user} u ON l.userid = u.id
738 WHERE l.module = 'login' AND l.action = 'error'
739 AND l.time > ?
740 AND cf.flagtype = 'login_failure_by_info') t
741 ORDER BY t.time DESC";
742 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
744 // Init some variables
745 $count = 0;
746 $messages = '';
747 // Iterate over the logs recordset
748 $rs = $DB->get_recordset_sql($sql, $params);
749 foreach ($rs as $log) {
750 $log->time = userdate($log->time);
751 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
752 $count++;
754 $rs->close();
756 // If we have something useful to report.
757 if ($count > 0) {
758 $site = get_site();
759 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
760 // Calculate the complete body of notification (start + messages + end)
761 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
762 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
763 $messages .
764 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
766 // For each destination, send mail
767 mtrace('Emailing admins about '. $count .' failed login attempts');
768 foreach ($recip as $admin) {
769 //emailing the admins directly rather than putting these through the messaging system
770 email_to_user($admin, core_user::get_support_user(), $subject, $body);
774 // Update lastnotifyfailure with current time
775 set_config('lastnotifyfailure', time());
777 // Finally, delete all the temp records we have created in cache_flags
778 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
780 return true;
784 * Delete files and directories older than one week from directory provided by $CFG->tempdir.
786 * @exception Exception Failed reading/accessing file or directory
787 * @return bool True on successful file and directory deletion; otherwise, false on failure
789 function cron_delete_from_temp() {
790 global $CFG;
792 $tmpdir = $CFG->tempdir;
793 // Default to last weeks time.
794 $time = strtotime('-1 week');
796 try {
797 $dir = new RecursiveDirectoryIterator($tmpdir);
798 // Show all child nodes prior to their parent.
799 $iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
801 for ($iter->rewind(); $iter->valid(); $iter->next()) {
802 $node = $iter->getRealPath();
803 if (!is_readable($node)) {
804 continue;
806 // Check if file or directory is older than the given time.
807 if ($iter->getMTime() < $time) {
808 if ($iter->isDir() && !$iter->isDot()) {
809 if (@rmdir($node) === false) {
810 mtrace("Failed removing directory '$node'.");
813 if ($iter->isFile()) {
814 if (@unlink($node) === false) {
815 mtrace("Failed removing file '$node'.");
820 } catch (Exception $e) {
821 mtrace('Failed reading/accessing file or directory.');
822 return false;
825 return true;