|
Moodle
2.2.1
http://www.collinsharper.com
|
00001 <?php 00002 // This file is part of Moodle - http://moodle.org/ 00003 // 00004 // Moodle is free software: you can redistribute it and/or modify 00005 // it under the terms of the GNU General Public License as published by 00006 // the Free Software Foundation, either version 3 of the License, or 00007 // (at your option) any later version. 00008 // 00009 // Moodle is distributed in the hope that it will be useful, 00010 // but WITHOUT ANY WARRANTY; without even the implied warranty of 00011 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00012 // GNU General Public License for more details. 00013 // 00014 // You should have received a copy of the GNU General Public License 00015 // along with Moodle. If not, see <http://www.gnu.org/licenses/>. 00016 00029 function cron_run() { 00030 global $DB, $CFG, $OUTPUT; 00031 00032 if (CLI_MAINTENANCE) { 00033 echo "CLI maintenance mode active, cron execution suspended.\n"; 00034 exit(1); 00035 } 00036 00037 if (moodle_needs_upgrading()) { 00038 echo "Moodle upgrade pending, cron execution suspended.\n"; 00039 exit(1); 00040 } 00041 00042 require_once($CFG->libdir.'/adminlib.php'); 00043 require_once($CFG->libdir.'/gradelib.php'); 00044 00045 if (!empty($CFG->showcronsql)) { 00046 $DB->set_debug(true); 00047 } 00048 if (!empty($CFG->showcrondebugging)) { 00049 $CFG->debug = DEBUG_DEVELOPER; 00050 $CFG->debugdisplay = true; 00051 } 00052 00053 set_time_limit(0); 00054 $starttime = microtime(); 00055 00056 // Increase memory limit 00057 raise_memory_limit(MEMORY_EXTRA); 00058 00059 // Emulate normal session - we use admin accoutn by default 00060 cron_setup_user(); 00061 00062 // Start output log 00063 $timenow = time(); 00064 mtrace("Server Time: ".date('r',$timenow)."\n\n"); 00065 00066 00067 // Run cleanup core cron jobs, but not every time since they aren't too important. 00068 // These don't have a timer to reduce load, so we'll use a random number 00069 // to randomly choose the percentage of times we should run these jobs. 00070 srand ((double) microtime() * 10000000); 00071 $random100 = rand(0,100); 00072 if ($random100 < 20) { // Approximately 20% of the time. 00073 mtrace("Running clean-up tasks..."); 00074 00075 // Delete users who haven't confirmed within required period 00076 if (!empty($CFG->deleteunconfirmed)) { 00077 $cuttime = $timenow - ($CFG->deleteunconfirmed * 3600); 00078 $rs = $DB->get_recordset_sql ("SELECT * 00079 FROM {user} 00080 WHERE confirmed = 0 AND firstaccess > 0 00081 AND firstaccess < ?", array($cuttime)); 00082 foreach ($rs as $user) { 00083 delete_user($user); // we MUST delete user properly first 00084 $DB->delete_records('user', array('id'=>$user->id)); // this is a bloody hack, but it might work 00085 mtrace(" Deleted unconfirmed user for ".fullname($user, true)." ($user->id)"); 00086 } 00087 $rs->close(); 00088 } 00089 00090 00091 // Delete users who haven't completed profile within required period 00092 if (!empty($CFG->deleteincompleteusers)) { 00093 $cuttime = $timenow - ($CFG->deleteincompleteusers * 3600); 00094 $rs = $DB->get_recordset_sql ("SELECT * 00095 FROM {user} 00096 WHERE confirmed = 1 AND lastaccess > 0 00097 AND lastaccess < ? AND deleted = 0 00098 AND (lastname = '' OR firstname = '' OR email = '')", 00099 array($cuttime)); 00100 foreach ($rs as $user) { 00101 delete_user($user); 00102 mtrace(" Deleted not fully setup user $user->username ($user->id)"); 00103 } 00104 $rs->close(); 00105 } 00106 00107 00108 // Delete old logs to save space (this might need a timer to slow it down...) 00109 if (!empty($CFG->loglifetime)) { // value in days 00110 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24); 00111 $DB->delete_records_select("log", "time < ?", array($loglifetime)); 00112 mtrace(" Deleted old log records"); 00113 } 00114 00115 00116 // Delete old backup_controllers and logs 00117 if (!empty($CFG->loglifetime)) { // value in days 00118 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24); 00119 // Delete child records from backup_logs 00120 $DB->execute("DELETE FROM {backup_logs} 00121 WHERE EXISTS ( 00122 SELECT 'x' 00123 FROM {backup_controllers} bc 00124 WHERE bc.backupid = {backup_logs}.backupid 00125 AND bc.timecreated < ?)", array($loglifetime)); 00126 // Delete records from backup_controllers 00127 $DB->execute("DELETE FROM {backup_controllers} 00128 WHERE timecreated < ?", array($loglifetime)); 00129 mtrace(" Deleted old backup records"); 00130 } 00131 00132 00133 // Delete old cached texts 00134 if (!empty($CFG->cachetext)) { // Defined in config.php 00135 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites 00136 $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime)); 00137 mtrace(" Deleted old cache_text records"); 00138 } 00139 00140 00141 if (!empty($CFG->usetags)) { 00142 require_once($CFG->dirroot.'/tag/lib.php'); 00143 tag_cron(); 00144 mtrace(' Executed tag cron'); 00145 } 00146 00147 00148 // Context maintenance stuff 00149 context_helper::cleanup_instances(); 00150 mtrace(' Cleaned up context instances'); 00151 context_helper::build_all_paths(false); 00152 // If you suspect that the context paths are somehow corrupt 00153 // replace the line below with: context_helper::build_all_paths(true); 00154 mtrace(' Built context paths'); 00155 00156 00157 // Remove expired cache flags 00158 gc_cache_flags(); 00159 mtrace(' Cleaned cache flags'); 00160 00161 00162 // Cleanup messaging 00163 if (!empty($CFG->messagingdeletereadnotificationsdelay)) { 00164 $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay; 00165 $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime'=>$notificationdeletetime)); 00166 mtrace(' Cleaned up read notifications'); 00167 } 00168 00169 mtrace("...finished clean-up tasks"); 00170 00171 } // End of occasional clean-up tasks 00172 00173 00174 // Send login failures notification - brute force protection in moodle is weak, 00175 // we should at least send notices early in each cron execution 00176 if (!empty($CFG->notifyloginfailures)) { 00177 notify_login_failures(); 00178 mtrace(' Notified login failured'); 00179 } 00180 00181 00182 // Make sure all context instances are properly created - they may be required in auth, enrol, etc. 00183 context_helper::create_instances(); 00184 mtrace(' Created missing context instances'); 00185 00186 00187 // Session gc 00188 session_gc(); 00189 mtrace("Cleaned up stale user sessions"); 00190 00191 00192 // Run the auth cron, if any before enrolments 00193 // because it might add users that will be needed in enrol plugins 00194 $auths = get_enabled_auth_plugins(); 00195 mtrace("Running auth crons if required..."); 00196 foreach ($auths as $auth) { 00197 $authplugin = get_auth_plugin($auth); 00198 if (method_exists($authplugin, 'cron')) { 00199 mtrace("Running cron for auth/$auth..."); 00200 $authplugin->cron(); 00201 if (!empty($authplugin->log)) { 00202 mtrace($authplugin->log); 00203 } 00204 } 00205 unset($authplugin); 00206 } 00207 // Generate new password emails for users - ppl expect these generated asap 00208 if ($DB->count_records('user_preferences', array('name'=>'create_password', 'value'=>'1'))) { 00209 mtrace('Creating passwords for new users...'); 00210 $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email, u.firstname, 00211 u.lastname, u.username, 00212 p.id as prefid 00213 FROM {user} u 00214 JOIN {user_preferences} p ON u.id=p.userid 00215 WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin'"); 00216 00217 // note: we can not send emails to suspended accounts 00218 foreach ($newusers as $newuser) { 00219 if (setnew_password_and_mail($newuser)) { 00220 unset_user_preference('create_password', $newuser); 00221 set_user_preference('auth_forcepasswordchange', 1, $newuser); 00222 } else { 00223 trigger_error("Could not create and mail new user password!"); 00224 } 00225 } 00226 $newusers->close(); 00227 } 00228 00229 00230 // It is very important to run enrol early 00231 // because other plugins depend on correct enrolment info. 00232 mtrace("Running enrol crons if required..."); 00233 $enrols = enrol_get_plugins(true); 00234 foreach($enrols as $ename=>$enrol) { 00235 // do this for all plugins, disabled plugins might want to cleanup stuff such as roles 00236 if (!$enrol->is_cron_required()) { 00237 continue; 00238 } 00239 mtrace("Running cron for enrol_$ename..."); 00240 $enrol->cron(); 00241 $enrol->set_config('lastcron', time()); 00242 } 00243 00244 00245 // Run all cron jobs for each module 00246 mtrace("Starting activity modules"); 00247 get_mailer('buffer'); 00248 if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { 00249 foreach ($mods as $mod) { 00250 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php"; 00251 if (file_exists($libfile)) { 00252 include_once($libfile); 00253 $cron_function = $mod->name."_cron"; 00254 if (function_exists($cron_function)) { 00255 mtrace("Processing module function $cron_function ...", ''); 00256 $pre_dbqueries = null; 00257 $pre_dbqueries = $DB->perf_get_queries(); 00258 $pre_time = microtime(1); 00259 if ($cron_function()) { 00260 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id)); 00261 } 00262 if (isset($pre_dbqueries)) { 00263 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); 00264 mtrace("... used " . (microtime(1) - $pre_time) . " seconds"); 00265 } 00266 // Reset possible changes by modules to time_limit. MDL-11597 00267 @set_time_limit(0); 00268 mtrace("done."); 00269 } 00270 } 00271 } 00272 } 00273 get_mailer('close'); 00274 mtrace("Finished activity modules"); 00275 00276 00277 mtrace("Starting blocks"); 00278 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { 00279 // We will need the base class. 00280 require_once($CFG->dirroot.'/blocks/moodleblock.class.php'); 00281 foreach ($blocks as $block) { 00282 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php'; 00283 if (file_exists($blockfile)) { 00284 require_once($blockfile); 00285 $classname = 'block_'.$block->name; 00286 $blockobj = new $classname; 00287 if (method_exists($blockobj,'cron')) { 00288 mtrace("Processing cron function for ".$block->name.'....',''); 00289 if ($blockobj->cron()) { 00290 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id)); 00291 } 00292 // Reset possible changes by blocks to time_limit. MDL-11597 00293 @set_time_limit(0); 00294 mtrace('done.'); 00295 } 00296 } 00297 00298 } 00299 } 00300 mtrace('Finished blocks'); 00301 00302 00303 mtrace('Starting admin reports'); 00304 cron_execute_plugin_type('report'); 00305 mtrace('Finished admin reports'); 00306 00307 00308 mtrace('Starting main gradebook job...'); 00309 grade_cron(); 00310 mtrace('done.'); 00311 00312 00313 mtrace('Starting processing the event queue...'); 00314 events_cron(); 00315 mtrace('done.'); 00316 00317 00318 if ($CFG->enablecompletion) { 00319 // Completion cron 00320 mtrace('Starting the completion cron...'); 00321 require_once($CFG->libdir . '/completion/cron.php'); 00322 completion_cron(); 00323 mtrace('done'); 00324 } 00325 00326 00327 if ($CFG->enableportfolios) { 00328 // Portfolio cron 00329 mtrace('Starting the portfolio cron...'); 00330 require_once($CFG->libdir . '/portfoliolib.php'); 00331 portfolio_cron(); 00332 mtrace('done'); 00333 } 00334 00335 00336 //now do plagiarism checks 00337 require_once($CFG->libdir.'/plagiarismlib.php'); 00338 plagiarism_cron(); 00339 00340 00341 mtrace('Starting course reports'); 00342 cron_execute_plugin_type('coursereport'); 00343 mtrace('Finished course reports'); 00344 00345 00346 // run gradebook import/export/report cron 00347 mtrace('Starting gradebook plugins'); 00348 cron_execute_plugin_type('gradeimport'); 00349 cron_execute_plugin_type('gradeexport'); 00350 cron_execute_plugin_type('gradereport'); 00351 mtrace('Finished gradebook plugins'); 00352 00353 00354 // Run external blog cron if needed 00355 if ($CFG->useexternalblogs) { 00356 require_once($CFG->dirroot . '/blog/lib.php'); 00357 mtrace("Fetching external blog entries...", ''); 00358 $sql = "timefetched < ? OR timefetched = 0"; 00359 $externalblogs = $DB->get_records_select('blog_external', $sql, array(mktime() - $CFG->externalblogcrontime)); 00360 00361 foreach ($externalblogs as $eb) { 00362 blog_sync_external_entries($eb); 00363 } 00364 mtrace('done.'); 00365 } 00366 // Run blog associations cleanup 00367 if ($CFG->useblogassociations) { 00368 require_once($CFG->dirroot . '/blog/lib.php'); 00369 // delete entries whose contextids no longer exists 00370 mtrace("Deleting blog associations linked to non-existent contexts...", ''); 00371 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})'); 00372 mtrace('done.'); 00373 } 00374 00375 00376 //Run registration updated cron 00377 mtrace(get_string('siteupdatesstart', 'hub')); 00378 require_once($CFG->dirroot . '/admin/registration/lib.php'); 00379 $registrationmanager = new registration_manager(); 00380 $registrationmanager->cron(); 00381 mtrace(get_string('siteupdatesend', 'hub')); 00382 00383 00384 //cleanup old session linked tokens 00385 //deletes the session linked tokens that are over a day old. 00386 mtrace("Deleting session linked tokens more than one day old...", ''); 00387 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', 00388 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED)); 00389 mtrace('done.'); 00390 00391 00392 // all other plugins 00393 cron_execute_plugin_type('message', 'message plugins'); 00394 cron_execute_plugin_type('filter', 'filters'); 00395 cron_execute_plugin_type('editor', 'editors'); 00396 cron_execute_plugin_type('format', 'course formats'); 00397 cron_execute_plugin_type('profilefield', 'profile fields'); 00398 cron_execute_plugin_type('webservice', 'webservices'); 00399 // TODO: Repository lib.php files are messed up (include many other files, etc), so it is 00400 // currently not possible to implement repository plugin cron using this infrastructure 00401 // cron_execute_plugin_type('repository', 'repository plugins'); 00402 cron_execute_plugin_type('qtype', 'question types'); 00403 cron_execute_plugin_type('plagiarism', 'plagiarism plugins'); 00404 cron_execute_plugin_type('theme', 'themes'); 00405 cron_execute_plugin_type('tool', 'admin tools'); 00406 00407 00408 // and finally run any local cronjobs, if any 00409 if ($locals = get_plugin_list('local')) { 00410 mtrace('Processing customized cron scripts ...', ''); 00411 // new cron functions in lib.php first 00412 cron_execute_plugin_type('local'); 00413 // legacy cron files are executed directly 00414 foreach ($locals as $local => $localdir) { 00415 if (file_exists("$localdir/cron.php")) { 00416 include("$localdir/cron.php"); 00417 } 00418 } 00419 mtrace('done.'); 00420 } 00421 00422 00423 // Run automated backups if required - these may take a long time to execute 00424 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php'); 00425 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php'); 00426 backup_cron_automated_helper::run_automated_backup(); 00427 00428 00429 // Run stats as at the end because they are known to take very long time on large sites 00430 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) { 00431 require_once($CFG->dirroot.'/lib/statslib.php'); 00432 // check we're not before our runtime 00433 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60; 00434 00435 if (time() > $timetocheck) { 00436 // process configured number of days as max (defaulting to 31) 00437 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays); 00438 if (stats_cron_daily($maxdays)) { 00439 if (stats_cron_weekly()) { 00440 if (stats_cron_monthly()) { 00441 stats_clean_old(); 00442 } 00443 } 00444 } 00445 @set_time_limit(0); 00446 } else { 00447 mtrace('Next stats run after:'. userdate($timetocheck)); 00448 } 00449 } 00450 00451 00452 // cleanup file trash - not very important 00453 $fs = get_file_storage(); 00454 $fs->cron(); 00455 00456 00457 mtrace("Cron script completed correctly"); 00458 00459 $difftime = microtime_diff($starttime, microtime()); 00460 mtrace("Execution took ".$difftime." seconds"); 00461 } 00462 00470 function cron_execute_plugin_type($plugintype, $description = null) { 00471 global $DB; 00472 00473 // Get list from plugin => function for all plugins 00474 $plugins = get_plugin_list_with_function($plugintype, 'cron'); 00475 00476 // Modify list for backward compatibility (different files/names) 00477 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins); 00478 00479 // Return if no plugins with cron function to process 00480 if (!$plugins) { 00481 return; 00482 } 00483 00484 if ($description) { 00485 mtrace('Starting '.$description); 00486 } 00487 00488 foreach ($plugins as $component=>$cronfunction) { 00489 $dir = get_component_directory($component); 00490 00491 // Get cron period if specified in version.php, otherwise assume every cron 00492 $cronperiod = 0; 00493 if (file_exists("$dir/version.php")) { 00494 $plugin = new stdClass(); 00495 include("$dir/version.php"); 00496 if (isset($plugin->cron)) { 00497 $cronperiod = $plugin->cron; 00498 } 00499 } 00500 00501 // Using last cron and cron period, don't run if it already ran recently 00502 $lastcron = get_config($component, 'lastcron'); 00503 if ($cronperiod && $lastcron) { 00504 if ($lastcron + $cronperiod > time()) { 00505 // do not execute cron yet 00506 continue; 00507 } 00508 } 00509 00510 mtrace('Processing cron function for ' . $component . '...'); 00511 $pre_dbqueries = $DB->perf_get_queries(); 00512 $pre_time = microtime(true); 00513 00514 $cronfunction(); 00515 00516 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " . 00517 round(microtime(true) - $pre_time, 2) . " seconds)"); 00518 00519 set_config('lastcron', time(), $component); 00520 @set_time_limit(0); 00521 } 00522 00523 if ($description) { 00524 mtrace('Finished ' . $description); 00525 } 00526 } 00527 00539 function cron_bc_hack_plugin_functions($plugintype, $plugins) { 00540 global $CFG; // mandatory in case it is referenced by include()d PHP script 00541 00542 if ($plugintype === 'report') { 00543 // Admin reports only - not course report because course report was 00544 // never implemented before, so doesn't need BC 00545 foreach (get_plugin_list($plugintype) as $pluginname=>$dir) { 00546 $component = $plugintype . '_' . $pluginname; 00547 if (isset($plugins[$component])) { 00548 // We already have detected the function using the new API 00549 continue; 00550 } 00551 if (!file_exists("$dir/cron.php")) { 00552 // No old style cron file present 00553 continue; 00554 } 00555 include_once("$dir/cron.php"); 00556 $cronfunction = $component . '_cron'; 00557 if (function_exists($cronfunction)) { 00558 $plugins[$component] = $cronfunction; 00559 } else { 00560 debugging("Invalid legacy cron.php detected in $component, " . 00561 "please use lib.php instead"); 00562 } 00563 } 00564 } else if (strpos($plugintype, 'grade') === 0) { 00565 // Detect old style cron function names 00566 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of 00567 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport 00568 foreach(get_plugin_list($plugintype) as $pluginname=>$dir) { 00569 $component = $plugintype.'_'.$pluginname; 00570 if (isset($plugins[$component])) { 00571 // We already have detected the function using the new API 00572 continue; 00573 } 00574 if (!file_exists("$dir/lib.php")) { 00575 continue; 00576 } 00577 include_once("$dir/lib.php"); 00578 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' . 00579 $pluginname . '_cron'; 00580 if (function_exists($cronfunction)) { 00581 $plugins[$component] = $cronfunction; 00582 } 00583 } 00584 } 00585 00586 return $plugins; 00587 } 00588 00589 00597 function notify_login_failures() { 00598 global $CFG, $DB, $OUTPUT; 00599 00600 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config'); 00601 00602 if (empty($CFG->lastnotifyfailure)) { 00603 $CFG->lastnotifyfailure=0; 00604 } 00605 00606 // we need to deal with the threshold stuff first. 00607 if (empty($CFG->notifyloginthreshold)) { 00608 $CFG->notifyloginthreshold = 10; // default to something sensible. 00609 } 00610 00611 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure 00612 // and insert them into the cache_flags temp table 00613 $sql = "SELECT ip, COUNT(*) 00614 FROM {log} 00615 WHERE module = 'login' AND action = 'error' 00616 AND time > ? 00617 GROUP BY ip 00618 HAVING COUNT(*) >= ?"; 00619 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold); 00620 $rs = $DB->get_recordset_sql($sql, $params); 00621 foreach ($rs as $iprec) { 00622 if (!empty($iprec->ip)) { 00623 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0); 00624 } 00625 } 00626 $rs->close(); 00627 00628 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure 00629 // and insert them into the cache_flags temp table 00630 $sql = "SELECT info, count(*) 00631 FROM {log} 00632 WHERE module = 'login' AND action = 'error' 00633 AND time > ? 00634 GROUP BY info 00635 HAVING count(*) >= ?"; 00636 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold); 00637 $rs = $DB->get_recordset_sql($sql, $params); 00638 foreach ($rs as $inforec) { 00639 if (!empty($inforec->info)) { 00640 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0); 00641 } 00642 } 00643 $rs->close(); 00644 00645 // Now, select all the login error logged records belonging to the ips and infos 00646 // since lastnotifyfailure, that we have stored in the cache_flags table 00647 $sql = "SELECT l.*, u.firstname, u.lastname 00648 FROM {log} l 00649 JOIN {cache_flags} cf ON l.ip = cf.name 00650 LEFT JOIN {user} u ON l.userid = u.id 00651 WHERE l.module = 'login' AND l.action = 'error' 00652 AND l.time > ? 00653 AND cf.flagtype = 'login_failure_by_ip' 00654 UNION ALL 00655 SELECT l.*, u.firstname, u.lastname 00656 FROM {log} l 00657 JOIN {cache_flags} cf ON l.info = cf.name 00658 LEFT JOIN {user} u ON l.userid = u.id 00659 WHERE l.module = 'login' AND l.action = 'error' 00660 AND l.time > ? 00661 AND cf.flagtype = 'login_failure_by_info' 00662 ORDER BY time DESC"; 00663 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure); 00664 00665 // Init some variables 00666 $count = 0; 00667 $messages = ''; 00668 // Iterate over the logs recordset 00669 $rs = $DB->get_recordset_sql($sql, $params); 00670 foreach ($rs as $log) { 00671 $log->time = userdate($log->time); 00672 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n"; 00673 $count++; 00674 } 00675 $rs->close(); 00676 00677 // If we haven't run in the last hour and 00678 // we have something useful to report and we 00679 // are actually supposed to be reporting to somebody 00680 if ((time() - HOURSECS) > $CFG->lastnotifyfailure && $count > 0 && is_array($recip) && count($recip) > 0) { 00681 $site = get_site(); 00682 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname)); 00683 // Calculate the complete body of notification (start + messages + end) 00684 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) . 00685 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" . 00686 $messages . 00687 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n"; 00688 00689 // For each destination, send mail 00690 mtrace('Emailing admins about '. $count .' failed login attempts'); 00691 foreach ($recip as $admin) { 00692 //emailing the admins directly rather than putting these through the messaging system 00693 email_to_user($admin,get_admin(), $subject, $body); 00694 } 00695 00696 // Update lastnotifyfailure with current time 00697 set_config('lastnotifyfailure', time()); 00698 } 00699 00700 // Finally, delete all the temp records we have created in cache_flags 00701 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')"); 00702 }