2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
22 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 global $DB, $CFG, $OUTPUT;
32 if (CLI_MAINTENANCE
) {
33 echo "CLI maintenance mode active, cron execution suspended.\n";
37 if (moodle_needs_upgrading()) {
38 echo "Moodle upgrade pending, cron execution suspended.\n";
42 require_once($CFG->libdir
.'/adminlib.php');
43 require_once($CFG->libdir
.'/gradelib.php');
45 if (!empty($CFG->showcronsql
)) {
48 if (!empty($CFG->showcrondebugging
)) {
49 set_debugging(DEBUG_DEVELOPER
, true);
53 $starttime = microtime();
55 // Increase memory limit
56 raise_memory_limit(MEMORY_EXTRA
);
58 // Emulate normal session - we use admin accoutn by default
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 *
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)");
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 *
96 WHERE confirmed = 1 AND lastaccess > 0
97 AND lastaccess < ? AND deleted = 0
98 AND (lastname = '' OR firstname = '' OR email = '')",
100 foreach ($rs as $user) {
101 if (isguestuser($user) or is_siteadmin($user)) {
105 mtrace(" Deleted not fully setup user $user->username ($user->id)");
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}
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');
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
163 mtrace(' Cleaned cache flags');
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 mtrace("...finished clean-up tasks");
178 } // End of occasional clean-up tasks
181 // Send login failures notification - brute force protection in moodle is weak,
182 // we should at least send notices early in each cron execution
183 if (notify_login_failures()) {
184 mtrace(' Notified login failures');
188 // Make sure all context instances are properly created - they may be required in auth, enrol, etc.
189 context_helper
::create_instances();
190 mtrace(' Created missing context instances');
195 mtrace("Cleaned up stale user sessions");
198 // Run the auth cron, if any before enrolments
199 // because it might add users that will be needed in enrol plugins
200 $auths = get_enabled_auth_plugins();
201 mtrace("Running auth crons if required...");
202 cron_trace_time_and_memory();
203 foreach ($auths as $auth) {
204 $authplugin = get_auth_plugin($auth);
205 if (method_exists($authplugin, 'cron')) {
206 mtrace("Running cron for auth/$auth...");
208 if (!empty($authplugin->log
)) {
209 mtrace($authplugin->log
);
214 // Generate new password emails for users - ppl expect these generated asap
215 if ($DB->count_records('user_preferences', array('name'=>'create_password', 'value'=>'1'))) {
216 mtrace('Creating passwords for new users...');
217 $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email, u.firstname,
218 u.lastname, u.username, u.lang,
221 JOIN {user_preferences} p ON u.id=p.userid
222 WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0");
224 // note: we can not send emails to suspended accounts
225 foreach ($newusers as $newuser) {
226 // Use a low cost factor when generating bcrypt hash otherwise
227 // hashing would be slow when emailing lots of users. Hashes
228 // will be automatically updated to a higher cost factor the first
229 // time the user logs in.
230 if (setnew_password_and_mail($newuser, true)) {
231 unset_user_preference('create_password', $newuser);
232 set_user_preference('auth_forcepasswordchange', 1, $newuser);
234 trigger_error("Could not create and mail new user password!");
241 // It is very important to run enrol early
242 // because other plugins depend on correct enrolment info.
243 mtrace("Running enrol crons if required...");
244 $enrols = enrol_get_plugins(true);
245 foreach($enrols as $ename=>$enrol) {
246 // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
247 if (!$enrol->is_cron_required()) {
250 mtrace("Running cron for enrol_$ename...");
251 cron_trace_time_and_memory();
253 $enrol->set_config('lastcron', time());
257 // Run all cron jobs for each module
258 mtrace("Starting activity modules");
259 get_mailer('buffer');
260 if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
261 foreach ($mods as $mod) {
262 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
263 if (file_exists($libfile)) {
264 include_once($libfile);
265 $cron_function = $mod->name
."_cron";
266 if (function_exists($cron_function)) {
267 mtrace("Processing module function $cron_function ...", '');
268 cron_trace_time_and_memory();
269 $pre_dbqueries = null;
270 $pre_dbqueries = $DB->perf_get_queries();
271 $pre_time = microtime(1);
272 if ($cron_function()) {
273 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id
));
275 if (isset($pre_dbqueries)) {
276 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
277 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
279 // Reset possible changes by modules to time_limit. MDL-11597
287 mtrace("Finished activity modules");
290 mtrace("Starting blocks");
291 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
292 // We will need the base class.
293 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
294 foreach ($blocks as $block) {
295 $blockfile = $CFG->dirroot
.'/blocks/'.$block->name
.'/block_'.$block->name
.'.php';
296 if (file_exists($blockfile)) {
297 require_once($blockfile);
298 $classname = 'block_'.$block->name
;
299 $blockobj = new $classname;
300 if (method_exists($blockobj,'cron')) {
301 mtrace("Processing cron function for ".$block->name
.'....','');
302 cron_trace_time_and_memory();
303 if ($blockobj->cron()) {
304 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id
));
306 // Reset possible changes by blocks to time_limit. MDL-11597
314 mtrace('Finished blocks');
317 mtrace('Starting admin reports');
318 cron_execute_plugin_type('report');
319 mtrace('Finished admin reports');
322 mtrace('Starting main gradebook job...');
323 cron_trace_time_and_memory();
328 mtrace('Starting processing the event queue...');
329 cron_trace_time_and_memory();
334 if ($CFG->enablecompletion
) {
336 mtrace('Starting the completion cron...');
337 cron_trace_time_and_memory();
338 require_once($CFG->dirroot
.'/completion/cron.php');
344 if ($CFG->enableportfolios
) {
346 mtrace('Starting the portfolio cron...');
347 cron_trace_time_and_memory();
348 require_once($CFG->libdir
. '/portfoliolib.php');
354 //now do plagiarism checks
355 require_once($CFG->libdir
.'/plagiarismlib.php');
359 mtrace('Starting course reports');
360 cron_execute_plugin_type('coursereport');
361 mtrace('Finished course reports');
364 // run gradebook import/export/report cron
365 mtrace('Starting gradebook plugins');
366 cron_execute_plugin_type('gradeimport');
367 cron_execute_plugin_type('gradeexport');
368 cron_execute_plugin_type('gradereport');
369 mtrace('Finished gradebook plugins');
372 require_once "{$CFG->dirroot}/calendar/lib.php";
375 // Run external blog cron if needed
376 if (!empty($CFG->enableblogs
) && $CFG->useexternalblogs
) {
377 require_once($CFG->dirroot
. '/blog/lib.php');
378 mtrace("Fetching external blog entries...", '');
379 cron_trace_time_and_memory();
380 $sql = "timefetched < ? OR timefetched = 0";
381 $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime
));
383 foreach ($externalblogs as $eb) {
384 blog_sync_external_entries($eb);
388 // Run blog associations cleanup
389 if (!empty($CFG->enableblogs
) && $CFG->useblogassociations
) {
390 require_once($CFG->dirroot
. '/blog/lib.php');
391 // delete entries whose contextids no longer exists
392 mtrace("Deleting blog associations linked to non-existent contexts...", '');
393 cron_trace_time_and_memory();
394 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
399 // Run question bank clean-up.
400 mtrace("Starting the question bank cron...", '');
401 cron_trace_time_and_memory();
402 require_once($CFG->libdir
. '/questionlib.php');
403 question_bank
::cron();
407 //Run registration updated cron
408 mtrace(get_string('siteupdatesstart', 'hub'));
409 cron_trace_time_and_memory();
410 require_once($CFG->dirroot
. '/' . $CFG->admin
. '/registration/lib.php');
411 $registrationmanager = new registration_manager();
412 $registrationmanager->cron();
413 mtrace(get_string('siteupdatesend', 'hub'));
415 // If enabled, fetch information about available updates and eventually notify site admins
416 if (empty($CFG->disableupdatenotifications
)) {
417 require_once($CFG->libdir
.'/pluginlib.php');
418 $updateschecker = available_update_checker
::instance();
419 $updateschecker->cron();
422 //cleanup old session linked tokens
423 //deletes the session linked tokens that are over a day old.
424 mtrace("Deleting session linked tokens more than one day old...", '');
425 cron_trace_time_and_memory();
426 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
427 array('onedayago' => time() - DAYSECS
, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED
));
432 cron_execute_plugin_type('message', 'message plugins');
433 cron_execute_plugin_type('filter', 'filters');
434 cron_execute_plugin_type('editor', 'editors');
435 cron_execute_plugin_type('format', 'course formats');
436 cron_execute_plugin_type('profilefield', 'profile fields');
437 cron_execute_plugin_type('webservice', 'webservices');
438 cron_execute_plugin_type('repository', 'repository plugins');
439 cron_execute_plugin_type('qbehaviour', 'question behaviours');
440 cron_execute_plugin_type('qformat', 'question import/export formats');
441 cron_execute_plugin_type('qtype', 'question types');
442 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
443 cron_execute_plugin_type('theme', 'themes');
444 cron_execute_plugin_type('tool', 'admin tools');
447 // and finally run any local cronjobs, if any
448 if ($locals = core_component
::get_plugin_list('local')) {
449 mtrace('Processing customized cron scripts ...', '');
450 // new cron functions in lib.php first
451 cron_execute_plugin_type('local');
452 // legacy cron files are executed directly
453 foreach ($locals as $local => $localdir) {
454 if (file_exists("$localdir/cron.php")) {
455 include("$localdir/cron.php");
461 mtrace('Running cache cron routines');
462 cache_helper
::cron();
465 // Run automated backups if required - these may take a long time to execute
466 require_once($CFG->dirroot
.'/backup/util/includes/backup_includes.php');
467 require_once($CFG->dirroot
.'/backup/util/helper/backup_cron_helper.class.php');
468 backup_cron_automated_helper
::run_automated_backup();
471 // Run stats as at the end because they are known to take very long time on large sites
472 if (!empty($CFG->enablestats
) and empty($CFG->disablestatsprocessing
)) {
473 require_once($CFG->dirroot
.'/lib/statslib.php');
474 // check we're not before our runtime
475 $timetocheck = stats_get_base_daily() +
$CFG->statsruntimestarthour
*60*60 +
$CFG->statsruntimestartminute
*60;
477 if (time() > $timetocheck) {
478 // process configured number of days as max (defaulting to 31)
479 $maxdays = empty($CFG->statsruntimedays
) ?
31 : abs($CFG->statsruntimedays
);
480 if (stats_cron_daily($maxdays)) {
481 if (stats_cron_weekly()) {
482 if (stats_cron_monthly()) {
489 mtrace('Next stats run after:'. userdate($timetocheck));
493 // Run badges review cron.
494 mtrace("Starting badges cron...");
495 require_once($CFG->dirroot
. '/badges/cron.php');
499 // cleanup file trash - not very important
500 $fs = get_file_storage();
503 mtrace("Cron script completed correctly");
506 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
507 $difftime = microtime_diff($starttime, microtime());
508 mtrace("Execution took ".$difftime." seconds");
512 * Executes cron functions for a specific type of plugin.
514 * @param string $plugintype Plugin type (e.g. 'report')
515 * @param string $description If specified, will display 'Starting (whatever)'
516 * and 'Finished (whatever)' lines, otherwise does not display
518 function cron_execute_plugin_type($plugintype, $description = null) {
521 // Get list from plugin => function for all plugins
522 $plugins = get_plugin_list_with_function($plugintype, 'cron');
524 // Modify list for backward compatibility (different files/names)
525 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
527 // Return if no plugins with cron function to process
533 mtrace('Starting '.$description);
536 foreach ($plugins as $component=>$cronfunction) {
537 $dir = core_component
::get_component_directory($component);
539 // Get cron period if specified in version.php, otherwise assume every cron
541 if (file_exists("$dir/version.php")) {
542 $plugin = new stdClass();
543 include("$dir/version.php");
544 if (isset($plugin->cron
)) {
545 $cronperiod = $plugin->cron
;
549 // Using last cron and cron period, don't run if it already ran recently
550 $lastcron = get_config($component, 'lastcron');
551 if ($cronperiod && $lastcron) {
552 if ($lastcron +
$cronperiod > time()) {
553 // do not execute cron yet
558 mtrace('Processing cron function for ' . $component . '...');
559 cron_trace_time_and_memory();
560 $pre_dbqueries = $DB->perf_get_queries();
561 $pre_time = microtime(true);
565 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
566 round(microtime(true) - $pre_time, 2) . " seconds)");
568 set_config('lastcron', time(), $component);
573 mtrace('Finished ' . $description);
578 * Used to add in old-style cron functions within plugins that have not been converted to the
579 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
580 * cron.php and some used a different name.)
582 * @param string $plugintype Plugin type e.g. 'report'
583 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
584 * 'report_frog_cron') for plugin cron functions that were already found using the new API
585 * @return array Revised version of $plugins that adds in any extra plugin functions found by
586 * looking in the older location
588 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
589 global $CFG; // mandatory in case it is referenced by include()d PHP script
591 if ($plugintype === 'report') {
592 // Admin reports only - not course report because course report was
593 // never implemented before, so doesn't need BC
594 foreach (core_component
::get_plugin_list($plugintype) as $pluginname=>$dir) {
595 $component = $plugintype . '_' . $pluginname;
596 if (isset($plugins[$component])) {
597 // We already have detected the function using the new API
600 if (!file_exists("$dir/cron.php")) {
601 // No old style cron file present
604 include_once("$dir/cron.php");
605 $cronfunction = $component . '_cron';
606 if (function_exists($cronfunction)) {
607 $plugins[$component] = $cronfunction;
609 debugging("Invalid legacy cron.php detected in $component, " .
610 "please use lib.php instead");
613 } else if (strpos($plugintype, 'grade') === 0) {
614 // Detect old style cron function names
615 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
616 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
617 foreach(core_component
::get_plugin_list($plugintype) as $pluginname=>$dir) {
618 $component = $plugintype.'_'.$pluginname;
619 if (isset($plugins[$component])) {
620 // We already have detected the function using the new API
623 if (!file_exists("$dir/lib.php")) {
626 include_once("$dir/lib.php");
627 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
628 $pluginname . '_cron';
629 if (function_exists($cronfunction)) {
630 $plugins[$component] = $cronfunction;
639 * Output some standard information during cron runs. Specifically current time
640 * and memory usage. This method also does gc_collect_cycles() (before displaying
641 * memory usage) to try to help PHP manage memory better.
643 function cron_trace_time_and_memory() {
645 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
649 * Notify admin users or admin user of any failed logins (since last notification).
651 * Note that this function must be only executed from the cron script
652 * It uses the cache_flags system to store temporary records, deleting them
653 * by name before finishing
655 * @return bool True if executed, false if not
657 function notify_login_failures() {
658 global $CFG, $DB, $OUTPUT;
660 if (empty($CFG->notifyloginfailures
)) {
664 $recip = get_users_from_config($CFG->notifyloginfailures
, 'moodle/site:config');
666 if (empty($CFG->lastnotifyfailure
)) {
667 $CFG->lastnotifyfailure
=0;
670 // If it has been less than an hour, or if there are no recipients, don't execute.
671 if (((time() - HOURSECS
) < $CFG->lastnotifyfailure
) ||
!is_array($recip) ||
count($recip) <= 0) {
675 // we need to deal with the threshold stuff first.
676 if (empty($CFG->notifyloginthreshold
)) {
677 $CFG->notifyloginthreshold
= 10; // default to something sensible.
680 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
681 // and insert them into the cache_flags temp table
682 $sql = "SELECT ip, COUNT(*)
684 WHERE module = 'login' AND action = 'error'
687 HAVING COUNT(*) >= ?";
688 $params = array($CFG->lastnotifyfailure
, $CFG->notifyloginthreshold
);
689 $rs = $DB->get_recordset_sql($sql, $params);
690 foreach ($rs as $iprec) {
691 if (!empty($iprec->ip
)) {
692 set_cache_flag('login_failure_by_ip', $iprec->ip
, '1', 0);
697 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
698 // and insert them into the cache_flags temp table
699 $sql = "SELECT info, count(*)
701 WHERE module = 'login' AND action = 'error'
704 HAVING count(*) >= ?";
705 $params = array($CFG->lastnotifyfailure
, $CFG->notifyloginthreshold
);
706 $rs = $DB->get_recordset_sql($sql, $params);
707 foreach ($rs as $inforec) {
708 if (!empty($inforec->info
)) {
709 set_cache_flag('login_failure_by_info', $inforec->info
, '1', 0);
714 // Now, select all the login error logged records belonging to the ips and infos
715 // since lastnotifyfailure, that we have stored in the cache_flags table
716 $sql = "SELECT * FROM (
717 SELECT l.*, u.firstname, u.lastname
719 JOIN {cache_flags} cf ON l.ip = cf.name
720 LEFT JOIN {user} u ON l.userid = u.id
721 WHERE l.module = 'login' AND l.action = 'error'
723 AND cf.flagtype = 'login_failure_by_ip'
725 SELECT l.*, u.firstname, u.lastname
727 JOIN {cache_flags} cf ON l.info = cf.name
728 LEFT JOIN {user} u ON l.userid = u.id
729 WHERE l.module = 'login' AND l.action = 'error'
731 AND cf.flagtype = 'login_failure_by_info') t
732 ORDER BY t.time DESC";
733 $params = array($CFG->lastnotifyfailure
, $CFG->lastnotifyfailure
);
735 // Init some variables
738 // Iterate over the logs recordset
739 $rs = $DB->get_recordset_sql($sql, $params);
740 foreach ($rs as $log) {
741 $log->time
= userdate($log->time
);
742 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
747 // If we have something useful to report.
750 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname
));
751 // Calculate the complete body of notification (start + messages + end)
752 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot
) .
753 (($CFG->lastnotifyfailure
!= 0) ?
'('.userdate($CFG->lastnotifyfailure
).')' : '')."\n\n" .
755 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot
)."\n\n";
757 // For each destination, send mail
758 mtrace('Emailing admins about '. $count .' failed login attempts');
759 foreach ($recip as $admin) {
760 //emailing the admins directly rather than putting these through the messaging system
761 email_to_user($admin, generate_email_supportuser(), $subject, $body);
765 // Update lastnotifyfailure with current time
766 set_config('lastnotifyfailure', time());
768 // Finally, delete all the temp records we have created in cache_flags
769 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
775 * Delete files and directories older than one week from directory provided by $CFG->tempdir.
777 * @exception Exception Failed reading/accessing file or directory
778 * @return bool True on successful file and directory deletion; otherwise, false on failure
780 function cron_delete_from_temp() {
783 $tmpdir = $CFG->tempdir
;
784 // Default to last weeks time.
785 $time = strtotime('-1 week');
788 $dir = new RecursiveDirectoryIterator($tmpdir);
789 // Show all child nodes prior to their parent.
790 $iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator
::CHILD_FIRST
);
792 for ($iter->rewind(); $iter->valid(); $iter->next()) {
793 $node = $iter->getPathname();
794 if (!is_readable($node)) {
797 // Check if file or directory is older than the given time.
798 if ($iter->getMTime() < $time) {
799 if ($iter->isDir() && !$iter->isDot()) {
800 if (@rmdir
($node) === false) {
801 mtrace("Failed removing directory '$node'.");
804 if ($iter->isFile()) {
805 if (@unlink
($node) === false) {
806 mtrace("Failed removing file '$node'.");
811 } catch (Exception
$e) {
812 mtrace('Failed reading/accessing file or directory.');