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