Merge branch 'MDL-38570-master' of https://github.com/timgus/moodle
[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)) {
96f81ea3 49 set_debugging(DEBUG_DEVELOPER, true);
28bd3d9a
PS
50 }
51
52 set_time_limit(0);
53 $starttime = microtime();
54
50ed196e 55 // Increase memory limit
346c5887 56 raise_memory_limit(MEMORY_EXTRA);
28bd3d9a 57
50ed196e 58 // Emulate normal session - we use admin accoutn by default
28bd3d9a
PS
59 cron_setup_user();
60
50ed196e 61 // Start output log
28bd3d9a 62 $timenow = time();
658b9372 63 mtrace("Server Time: ".date('r', $timenow)."\n\n");
28bd3d9a
PS
64
65
50ed196e
PS
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...");
658b9372 73 cron_trace_time_and_memory();
50ed196e
PS
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) {
98aa8746
PS
101 if (isguestuser($user) or is_siteadmin($user)) {
102 continue;
103 }
50ed196e
PS
104 delete_user($user);
105 mtrace(" Deleted not fully setup user $user->username ($user->id)");
106 }
107 $rs->close();
108 }
109
110
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");
116 }
117
118
14e2704a
EL
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.
50ed196e
PS
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));
14e2704a 130 // Delete records from backup_controllers.
50ed196e
PS
131 $DB->execute("DELETE FROM {backup_controllers}
132 WHERE timecreated < ?", array($loglifetime));
133 mtrace(" Deleted old backup records");
134 }
135
136
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");
142 }
143
144
145 if (!empty($CFG->usetags)) {
146 require_once($CFG->dirroot.'/tag/lib.php');
147 tag_cron();
148 mtrace(' Executed tag cron');
149 }
150
151
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');
159
160
161 // Remove expired cache flags
162 gc_cache_flags();
163 mtrace(' Cleaned cache flags');
164
165
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');
171 }
172
179961e8
TG
173 mtrace(' Deleting temporary files...');
174 cron_delete_from_temp();
175
50ed196e
PS
176 mtrace("...finished clean-up tasks");
177
178 } // End of occasional clean-up tasks
179
180
181 // Send login failures notification - brute force protection in moodle is weak,
182 // we should at least send notices early in each cron execution
192a8e13
EM
183 if (notify_login_failures()) {
184 mtrace(' Notified login failures');
50ed196e
PS
185 }
186
187
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');
191
28bd3d9a 192
50ed196e 193 // Session gc
28bd3d9a 194 session_gc();
50ed196e 195 mtrace("Cleaned up stale user sessions");
28bd3d9a 196
28bd3d9a 197
50ed196e
PS
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...");
658b9372 202 cron_trace_time_and_memory();
50ed196e
PS
203 foreach ($auths as $auth) {
204 $authplugin = get_auth_plugin($auth);
205 if (method_exists($authplugin, 'cron')) {
206 mtrace("Running cron for auth/$auth...");
207 $authplugin->cron();
208 if (!empty($authplugin->log)) {
209 mtrace($authplugin->log);
210 }
211 }
212 unset($authplugin);
213 }
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,
3cbad151 218 u.lastname, u.username, u.lang,
50ed196e
PS
219 p.id as prefid
220 FROM {user} u
221 JOIN {user_preferences} p ON u.id=p.userid
8205498f 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");
50ed196e 223
daa8b1ac 224 // note: we can not send emails to suspended accounts
50ed196e 225 foreach ($newusers as $newuser) {
ec2d8ceb
SC
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)) {
50ed196e
PS
231 unset_user_preference('create_password', $newuser);
232 set_user_preference('auth_forcepasswordchange', 1, $newuser);
233 } else {
234 trigger_error("Could not create and mail new user password!");
235 }
236 }
237 $newusers->close();
238 }
239
240
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()) {
248 continue;
249 }
250 mtrace("Running cron for enrol_$ename...");
658b9372 251 cron_trace_time_and_memory();
50ed196e
PS
252 $enrol->cron();
253 $enrol->set_config('lastcron', time());
254 }
255
256
257 // Run all cron jobs for each module
28bd3d9a
PS
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 ...", '');
658b9372 268 cron_trace_time_and_memory();
28bd3d9a
PS
269 $pre_dbqueries = null;
270 $pre_dbqueries = $DB->perf_get_queries();
271 $pre_time = microtime(1);
272 if ($cron_function()) {
f685e830 273 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id));
28bd3d9a
PS
274 }
275 if (isset($pre_dbqueries)) {
276 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
277 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
278 }
50ed196e 279 // Reset possible changes by modules to time_limit. MDL-11597
28bd3d9a
PS
280 @set_time_limit(0);
281 mtrace("done.");
282 }
283 }
284 }
285 }
286 get_mailer('close');
287 mtrace("Finished activity modules");
288
50ed196e 289
28bd3d9a
PS
290 mtrace("Starting blocks");
291 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
50ed196e 292 // We will need the base class.
28bd3d9a
PS
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.'....','');
658b9372 302 cron_trace_time_and_memory();
28bd3d9a 303 if ($blockobj->cron()) {
f685e830 304 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id));
28bd3d9a 305 }
50ed196e 306 // Reset possible changes by blocks to time_limit. MDL-11597
28bd3d9a
PS
307 @set_time_limit(0);
308 mtrace('done.');
309 }
310 }
311
312 }
313 }
314 mtrace('Finished blocks');
315
50ed196e 316
b5541735
PS
317 mtrace('Starting admin reports');
318 cron_execute_plugin_type('report');
319 mtrace('Finished admin reports');
320
50ed196e
PS
321
322 mtrace('Starting main gradebook job...');
658b9372 323 cron_trace_time_and_memory();
28bd3d9a
PS
324 grade_cron();
325 mtrace('done.');
326
327
328 mtrace('Starting processing the event queue...');
658b9372 329 cron_trace_time_and_memory();
28bd3d9a
PS
330 events_cron();
331 mtrace('done.');
332
333
334 if ($CFG->enablecompletion) {
335 // Completion cron
336 mtrace('Starting the completion cron...');
658b9372 337 cron_trace_time_and_memory();
75342343 338 require_once($CFG->dirroot.'/completion/cron.php');
28bd3d9a
PS
339 completion_cron();
340 mtrace('done');
341 }
342
343
344 if ($CFG->enableportfolios) {
345 // Portfolio cron
346 mtrace('Starting the portfolio cron...');
658b9372 347 cron_trace_time_and_memory();
28bd3d9a
PS
348 require_once($CFG->libdir . '/portfoliolib.php');
349 portfolio_cron();
350 mtrace('done');
351 }
352
50ed196e 353
8cf1862c
DM
354 //now do plagiarism checks
355 require_once($CFG->libdir.'/plagiarismlib.php');
356 plagiarism_cron();
357
28bd3d9a 358
b5541735
PS
359 mtrace('Starting course reports');
360 cron_execute_plugin_type('coursereport');
361 mtrace('Finished course reports');
28bd3d9a 362
50ed196e 363
b5541735
PS
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');
28bd3d9a 370
b5a52acd
JH
371 // run calendar cron
372 require_once "{$CFG->dirroot}/calendar/lib.php";
373 calendar_cron();
50ed196e 374
28bd3d9a 375 // Run external blog cron if needed
850d2db8 376 if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
28bd3d9a
PS
377 require_once($CFG->dirroot . '/blog/lib.php');
378 mtrace("Fetching external blog entries...", '');
658b9372 379 cron_trace_time_and_memory();
28bd3d9a 380 $sql = "timefetched < ? OR timefetched = 0";
e2bb3c92 381 $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
28bd3d9a
PS
382
383 foreach ($externalblogs as $eb) {
384 blog_sync_external_entries($eb);
385 }
b5541735 386 mtrace('done.');
28bd3d9a 387 }
28bd3d9a 388 // Run blog associations cleanup
850d2db8 389 if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
28bd3d9a
PS
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...", '');
658b9372 393 cron_trace_time_and_memory();
28bd3d9a 394 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
b5541735 395 mtrace('done.');
28bd3d9a
PS
396 }
397
50ed196e 398
2ec325c2
TH
399 // Run question bank clean-up.
400 mtrace("Starting the question bank cron...", '');
658b9372 401 cron_trace_time_and_memory();
2ec325c2
TH
402 require_once($CFG->libdir . '/questionlib.php');
403 question_bank::cron();
404 mtrace('done.');
405
406
28bd3d9a
PS
407 //Run registration updated cron
408 mtrace(get_string('siteupdatesstart', 'hub'));
658b9372 409 cron_trace_time_and_memory();
a91b4aa6 410 require_once($CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php');
28bd3d9a
PS
411 $registrationmanager = new registration_manager();
412 $registrationmanager->cron();
413 mtrace(get_string('siteupdatesend', 'hub'));
414
19d11b3b 415 // If enabled, fetch information about available updates and eventually notify site admins
fef693c8
DM
416 if (empty($CFG->disableupdatenotifications)) {
417 require_once($CFG->libdir.'/pluginlib.php');
418 $updateschecker = available_update_checker::instance();
419 $updateschecker->cron();
420 }
28bd3d9a
PS
421
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...", '');
658b9372 425 cron_trace_time_and_memory();
28bd3d9a
PS
426 $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
427 array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
428 mtrace('done.');
429
50ed196e 430
b5541735
PS
431 // all other plugins
432 cron_execute_plugin_type('message', 'message plugins');
433 cron_execute_plugin_type('filter', 'filters');
e4a626b9 434 cron_execute_plugin_type('editor', 'editors');
b5541735
PS
435 cron_execute_plugin_type('format', 'course formats');
436 cron_execute_plugin_type('profilefield', 'profile fields');
437 cron_execute_plugin_type('webservice', 'webservices');
67233725 438 cron_execute_plugin_type('repository', 'repository plugins');
c2f5e2ab
TH
439 cron_execute_plugin_type('qbehaviour', 'question behaviours');
440 cron_execute_plugin_type('qformat', 'question import/export formats');
b5541735
PS
441 cron_execute_plugin_type('qtype', 'question types');
442 cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
443 cron_execute_plugin_type('theme', 'themes');
67a6243a 444 cron_execute_plugin_type('tool', 'admin tools');
b5541735 445
50ed196e 446
b5541735 447 // and finally run any local cronjobs, if any
bd3b3bba 448 if ($locals = core_component::get_plugin_list('local')) {
28bd3d9a 449 mtrace('Processing customized cron scripts ...', '');
b5541735
PS
450 // new cron functions in lib.php first
451 cron_execute_plugin_type('local');
452 // legacy cron files are executed directly
28bd3d9a
PS
453 foreach ($locals as $local => $localdir) {
454 if (file_exists("$localdir/cron.php")) {
455 include("$localdir/cron.php");
456 }
457 }
458 mtrace('done.');
459 }
460
059102e7
SH
461 mtrace('Running cache cron routines');
462 cache_helper::cron();
463 mtrace('done.');
50ed196e
PS
464
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();
469
470
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;
476
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()) {
483 stats_clean_old();
484 }
485 }
486 }
487 @set_time_limit(0);
488 } else {
489 mtrace('Next stats run after:'. userdate($timetocheck));
490 }
491 }
492
27806552
YB
493 // Run badges review cron.
494 mtrace("Starting badges cron...");
495 require_once($CFG->dirroot . '/badges/cron.php');
496 badge_cron();
497 mtrace('done.');
50ed196e
PS
498
499 // cleanup file trash - not very important
500 $fs = get_file_storage();
501 $fs->cron();
502
28bd3d9a
PS
503 mtrace("Cron script completed correctly");
504
658b9372
TH
505 gc_collect_cycles();
506 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
28bd3d9a
PS
507 $difftime = microtime_diff($starttime, microtime());
508 mtrace("Execution took ".$difftime." seconds");
cbb9e9b8 509}
b5541735 510
e4a626b9 511/**
512 * Executes cron functions for a specific type of plugin.
50ed196e 513 *
e4a626b9 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
517 */
b5541735
PS
518function cron_execute_plugin_type($plugintype, $description = null) {
519 global $DB;
520
e4a626b9 521 // Get list from plugin => function for all plugins
522 $plugins = get_plugin_list_with_function($plugintype, 'cron');
523
524 // Modify list for backward compatibility (different files/names)
525 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
b5541735 526
e4a626b9 527 // Return if no plugins with cron function to process
b5541735
PS
528 if (!$plugins) {
529 return;
530 }
531
532 if ($description) {
533 mtrace('Starting '.$description);
534 }
535
536 foreach ($plugins as $component=>$cronfunction) {
b0d1d941 537 $dir = core_component::get_component_directory($component);
e4a626b9 538
539 // Get cron period if specified in version.php, otherwise assume every cron
b5541735
PS
540 $cronperiod = 0;
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;
546 }
547 }
548
e4a626b9 549 // Using last cron and cron period, don't run if it already ran recently
b5541735 550 $lastcron = get_config($component, 'lastcron');
e4a626b9 551 if ($cronperiod && $lastcron) {
b5541735
PS
552 if ($lastcron + $cronperiod > time()) {
553 // do not execute cron yet
554 continue;
555 }
556 }
557
e4a626b9 558 mtrace('Processing cron function for ' . $component . '...');
658b9372 559 cron_trace_time_and_memory();
b5541735 560 $pre_dbqueries = $DB->perf_get_queries();
e4a626b9 561 $pre_time = microtime(true);
b5541735
PS
562
563 $cronfunction();
564
e4a626b9 565 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
566 round(microtime(true) - $pre_time, 2) . " seconds)");
b5541735
PS
567
568 set_config('lastcron', time(), $component);
4332cc46 569 @set_time_limit(0);
b5541735
PS
570 }
571
572 if ($description) {
e4a626b9 573 mtrace('Finished ' . $description);
b5541735
PS
574 }
575}
576
e4a626b9 577/**
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.)
50ed196e 581 *
e4a626b9 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
587 */
588function cron_bc_hack_plugin_functions($plugintype, $plugins) {
589 global $CFG; // mandatory in case it is referenced by include()d PHP script
590
591 if ($plugintype === 'report') {
592 // Admin reports only - not course report because course report was
593 // never implemented before, so doesn't need BC
bd3b3bba 594 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
e4a626b9 595 $component = $plugintype . '_' . $pluginname;
b5541735 596 if (isset($plugins[$component])) {
e4a626b9 597 // We already have detected the function using the new API
b5541735
PS
598 continue;
599 }
600 if (!file_exists("$dir/cron.php")) {
e4a626b9 601 // No old style cron file present
b5541735
PS
602 continue;
603 }
604 include_once("$dir/cron.php");
e4a626b9 605 $cronfunction = $component . '_cron';
b5541735
PS
606 if (function_exists($cronfunction)) {
607 $plugins[$component] = $cronfunction;
608 } else {
e4a626b9 609 debugging("Invalid legacy cron.php detected in $component, " .
610 "please use lib.php instead");
b5541735
PS
611 }
612 }
b5541735 613 } else if (strpos($plugintype, 'grade') === 0) {
e4a626b9 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
bd3b3bba 617 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
b5541735
PS
618 $component = $plugintype.'_'.$pluginname;
619 if (isset($plugins[$component])) {
e4a626b9 620 // We already have detected the function using the new API
b5541735
PS
621 continue;
622 }
623 if (!file_exists("$dir/lib.php")) {
624 continue;
625 }
626 include_once("$dir/lib.php");
e4a626b9 627 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
628 $pluginname . '_cron';
b5541735
PS
629 if (function_exists($cronfunction)) {
630 $plugins[$component] = $cronfunction;
631 }
632 }
633 }
634
635 return $plugins;
50ed196e
PS
636}
637
658b9372
TH
638/**
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.
642 */
643function cron_trace_time_and_memory() {
644 gc_collect_cycles();
645 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
646}
50ed196e
PS
647
648/**
649 * Notify admin users or admin user of any failed logins (since last notification).
650 *
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
192a8e13
EM
654 *
655 * @return bool True if executed, false if not
50ed196e
PS
656 */
657function notify_login_failures() {
658 global $CFG, $DB, $OUTPUT;
659
192a8e13
EM
660 if (empty($CFG->notifyloginfailures)) {
661 return false;
662 }
663
50ed196e
PS
664 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
665
aa12ec98
EL
666 if (empty($CFG->lastnotifyfailure)) {
667 $CFG->lastnotifyfailure=0;
668 }
669
192a8e13
EM
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) {
672 return false;
673 }
674
50ed196e
PS
675 // we need to deal with the threshold stuff first.
676 if (empty($CFG->notifyloginthreshold)) {
677 $CFG->notifyloginthreshold = 10; // default to something sensible.
678 }
679
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(*)
683 FROM {log}
684 WHERE module = 'login' AND action = 'error'
685 AND time > ?
686 GROUP BY ip
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);
693 }
694 }
695 $rs->close();
696
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(*)
700 FROM {log}
701 WHERE module = 'login' AND action = 'error'
702 AND time > ?
703 GROUP BY info
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);
710 }
711 }
712 $rs->close();
713
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
a415ecc2
RT
716 $sql = "SELECT * FROM (
717 SELECT l.*, u.firstname, u.lastname
50ed196e
PS
718 FROM {log} l
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'
722 AND l.time > ?
723 AND cf.flagtype = 'login_failure_by_ip'
724 UNION ALL
725 SELECT l.*, u.firstname, u.lastname
726 FROM {log} l
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'
730 AND l.time > ?
a415ecc2
RT
731 AND cf.flagtype = 'login_failure_by_info') t
732 ORDER BY t.time DESC";
50ed196e
PS
733 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
734
735 // Init some variables
736 $count = 0;
737 $messages = '';
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";
743 $count++;
744 }
745 $rs->close();
746
192a8e13
EM
747 // If we have something useful to report.
748 if ($count > 0) {
50ed196e
PS
749 $site = get_site();
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" .
754 $messages .
755 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
756
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
c968c1b7 761 email_to_user($admin, generate_email_supportuser(), $subject, $body);
50ed196e 762 }
50ed196e
PS
763 }
764
54c2756c
EM
765 // Update lastnotifyfailure with current time
766 set_config('lastnotifyfailure', time());
767
50ed196e
PS
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')");
192a8e13
EM
770
771 return true;
50ed196e 772}
179961e8
TG
773
774/**
775 * Delete files and directories older than one week from directory provided by $CFG->tempdir.
776 *
777 * @exception Exception Failed reading/accessing file or directory
778 * @return bool True on successful file and directory deletion; otherwise, false on failure
779 */
780function cron_delete_from_temp() {
781 global $CFG;
782
783 $tmpdir = $CFG->tempdir;
784 // Default to last weeks time.
785 $time = strtotime('-1 week');
786
787 try {
788 $dir = new RecursiveDirectoryIterator($tmpdir);
789 // Show all child nodes prior to their parent.
790 $iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
791
792 for ($iter->rewind(); $iter->valid(); $iter->next()) {
793 $node = $iter->getPathname();
794 if (!is_readable($node)) {
795 continue;
796 }
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'.");
802 }
803 }
804 if ($iter->isFile()) {
805 if (@unlink($node) === false) {
806 mtrace("Failed removing file '$node'.");
807 }
808 }
809 }
810 }
811 } catch (Exception $e) {
812 mtrace('Failed reading/accessing file or directory.');
813 return false;
814 }
815
816 return true;
817}