MDL-43723 Blocks drag and drop: Javascript cleanup
[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
3ef7279f 52 core_php_time_limit::raise();
28bd3d9a
PS
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.
50ed196e
PS
69 $random100 = rand(0,100);
70 if ($random100 < 20) { // Approximately 20% of the time.
71 mtrace("Running clean-up tasks...");
658b9372 72 cron_trace_time_and_memory();
50ed196e
PS
73
74 // Delete users who haven't confirmed within required period
75 if (!empty($CFG->deleteunconfirmed)) {
76 $cuttime = $timenow - ($CFG->deleteunconfirmed * 3600);
77 $rs = $DB->get_recordset_sql ("SELECT *
78 FROM {user}
79 WHERE confirmed = 0 AND firstaccess > 0
80 AND firstaccess < ?", array($cuttime));
81 foreach ($rs as $user) {
82 delete_user($user); // we MUST delete user properly first
83 $DB->delete_records('user', array('id'=>$user->id)); // this is a bloody hack, but it might work
84 mtrace(" Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
85 }
86 $rs->close();
87 }
88
89
90 // Delete users who haven't completed profile within required period
91 if (!empty($CFG->deleteincompleteusers)) {
92 $cuttime = $timenow - ($CFG->deleteincompleteusers * 3600);
93 $rs = $DB->get_recordset_sql ("SELECT *
94 FROM {user}
95 WHERE confirmed = 1 AND lastaccess > 0
96 AND lastaccess < ? AND deleted = 0
97 AND (lastname = '' OR firstname = '' OR email = '')",
98 array($cuttime));
99 foreach ($rs as $user) {
98aa8746
PS
100 if (isguestuser($user) or is_siteadmin($user)) {
101 continue;
102 }
50ed196e
PS
103 delete_user($user);
104 mtrace(" Deleted not fully setup user $user->username ($user->id)");
105 }
106 $rs->close();
107 }
108
109
110 // Delete old logs to save space (this might need a timer to slow it down...)
111 if (!empty($CFG->loglifetime)) { // value in days
112 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
113 $DB->delete_records_select("log", "time < ?", array($loglifetime));
114 mtrace(" Deleted old log records");
115 }
116
117
14e2704a
EL
118 // Delete old backup_controllers and logs.
119 $loglifetime = get_config('backup', 'loglifetime');
120 if (!empty($loglifetime)) { // Value in days.
121 $loglifetime = $timenow - ($loglifetime * 3600 * 24);
122 // Delete child records from backup_logs.
50ed196e
PS
123 $DB->execute("DELETE FROM {backup_logs}
124 WHERE EXISTS (
125 SELECT 'x'
126 FROM {backup_controllers} bc
127 WHERE bc.backupid = {backup_logs}.backupid
128 AND bc.timecreated < ?)", array($loglifetime));
14e2704a 129 // Delete records from backup_controllers.
50ed196e
PS
130 $DB->execute("DELETE FROM {backup_controllers}
131 WHERE timecreated < ?", array($loglifetime));
132 mtrace(" Deleted old backup records");
50ed196e
PS
133 }
134
135
136 if (!empty($CFG->usetags)) {
137 require_once($CFG->dirroot.'/tag/lib.php');
138 tag_cron();
139 mtrace(' Executed tag cron');
140 }
141
142
143 // Context maintenance stuff
144 context_helper::cleanup_instances();
145 mtrace(' Cleaned up context instances');
146 context_helper::build_all_paths(false);
147 // If you suspect that the context paths are somehow corrupt
148 // replace the line below with: context_helper::build_all_paths(true);
149 mtrace(' Built context paths');
150
151
152 // Remove expired cache flags
153 gc_cache_flags();
154 mtrace(' Cleaned cache flags');
155
156
157 // Cleanup messaging
158 if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
159 $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
160 $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime'=>$notificationdeletetime));
161 mtrace(' Cleaned up read notifications');
162 }
163
179961e8
TG
164 mtrace(' Deleting temporary files...');
165 cron_delete_from_temp();
166
92de749f
PB
167 // Cleanup user password reset records
168 // Delete any reset request records which are expired by more than a day.
169 // (We keep recently expired requests around so we can give a different error msg to users who
170 // are trying to user a recently expired reset attempt).
171 $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
172 $earliestvalid = time() - $pwresettime - DAYSECS;
173 $DB->delete_records_select('user_password_resets', "timerequested < ?", array($earliestvalid));
174 mtrace(' Cleaned up old password reset records');
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
d79d5ac2
PS
193 // Session gc.
194 mtrace("Running session gc tasks...");
195 \core\session\manager::gc();
196 mtrace("...finished stale session cleanup");
28bd3d9a 197
28bd3d9a 198
50ed196e
PS
199 // Run the auth cron, if any before enrolments
200 // because it might add users that will be needed in enrol plugins
201 $auths = get_enabled_auth_plugins();
202 mtrace("Running auth crons if required...");
658b9372 203 cron_trace_time_and_memory();
50ed196e
PS
204 foreach ($auths as $auth) {
205 $authplugin = get_auth_plugin($auth);
206 if (method_exists($authplugin, 'cron')) {
207 mtrace("Running cron for auth/$auth...");
208 $authplugin->cron();
209 if (!empty($authplugin->log)) {
210 mtrace($authplugin->log);
211 }
212 }
213 unset($authplugin);
214 }
215 // Generate new password emails for users - ppl expect these generated asap
216 if ($DB->count_records('user_preferences', array('name'=>'create_password', 'value'=>'1'))) {
217 mtrace('Creating passwords for new users...');
fd2dcaa6
AN
218 $usernamefields = get_all_user_name_fields(true, 'u');
219 $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email,
220 $usernamefields, u.username, u.lang,
50ed196e
PS
221 p.id as prefid
222 FROM {user} u
223 JOIN {user_preferences} p ON u.id=p.userid
8205498f 224 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 225
daa8b1ac 226 // note: we can not send emails to suspended accounts
50ed196e 227 foreach ($newusers as $newuser) {
ec2d8ceb
SC
228 // Use a low cost factor when generating bcrypt hash otherwise
229 // hashing would be slow when emailing lots of users. Hashes
230 // will be automatically updated to a higher cost factor the first
231 // time the user logs in.
232 if (setnew_password_and_mail($newuser, true)) {
50ed196e
PS
233 unset_user_preference('create_password', $newuser);
234 set_user_preference('auth_forcepasswordchange', 1, $newuser);
235 } else {
236 trigger_error("Could not create and mail new user password!");
237 }
238 }
239 $newusers->close();
240 }
241
242
243 // It is very important to run enrol early
244 // because other plugins depend on correct enrolment info.
245 mtrace("Running enrol crons if required...");
246 $enrols = enrol_get_plugins(true);
247 foreach($enrols as $ename=>$enrol) {
248 // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
249 if (!$enrol->is_cron_required()) {
250 continue;
251 }
252 mtrace("Running cron for enrol_$ename...");
658b9372 253 cron_trace_time_and_memory();
50ed196e
PS
254 $enrol->cron();
255 $enrol->set_config('lastcron', time());
256 }
257
258
259 // Run all cron jobs for each module
28bd3d9a
PS
260 mtrace("Starting activity modules");
261 get_mailer('buffer');
262 if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
263 foreach ($mods as $mod) {
264 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
265 if (file_exists($libfile)) {
266 include_once($libfile);
267 $cron_function = $mod->name."_cron";
268 if (function_exists($cron_function)) {
269 mtrace("Processing module function $cron_function ...", '');
658b9372 270 cron_trace_time_and_memory();
28bd3d9a
PS
271 $pre_dbqueries = null;
272 $pre_dbqueries = $DB->perf_get_queries();
273 $pre_time = microtime(1);
274 if ($cron_function()) {
f685e830 275 $DB->set_field("modules", "lastcron", $timenow, array("id"=>$mod->id));
28bd3d9a
PS
276 }
277 if (isset($pre_dbqueries)) {
278 mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
279 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
280 }
50ed196e 281 // Reset possible changes by modules to time_limit. MDL-11597
3ef7279f 282 core_php_time_limit::raise();
28bd3d9a
PS
283 mtrace("done.");
284 }
285 }
286 }
287 }
288 get_mailer('close');
289 mtrace("Finished activity modules");
290
50ed196e 291
28bd3d9a
PS
292 mtrace("Starting blocks");
293 if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
50ed196e 294 // We will need the base class.
28bd3d9a
PS
295 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
296 foreach ($blocks as $block) {
297 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
298 if (file_exists($blockfile)) {
299 require_once($blockfile);
300 $classname = 'block_'.$block->name;
301 $blockobj = new $classname;
302 if (method_exists($blockobj,'cron')) {
303 mtrace("Processing cron function for ".$block->name.'....','');
658b9372 304 cron_trace_time_and_memory();
28bd3d9a 305 if ($blockobj->cron()) {
f685e830 306 $DB->set_field('block', 'lastcron', $timenow, array('id'=>$block->id));
28bd3d9a 307 }
50ed196e 308 // Reset possible changes by blocks to time_limit. MDL-11597
3ef7279f 309 core_php_time_limit::raise();
28bd3d9a
PS
310 mtrace('done.');
311 }
312 }
313
314 }
315 }
316 mtrace('Finished blocks');
317
50ed196e 318
b5541735
PS
319 mtrace('Starting admin reports');
320 cron_execute_plugin_type('report');
321 mtrace('Finished admin reports');
322
50ed196e
PS
323
324 mtrace('Starting main gradebook job...');
658b9372 325 cron_trace_time_and_memory();
28bd3d9a
PS
326 grade_cron();
327 mtrace('done.');
328
329
330 mtrace('Starting processing the event queue...');
658b9372 331 cron_trace_time_and_memory();
28bd3d9a
PS
332 events_cron();
333 mtrace('done.');
334
335
336 if ($CFG->enablecompletion) {
337 // Completion cron
338 mtrace('Starting the completion cron...');
658b9372 339 cron_trace_time_and_memory();
75342343 340 require_once($CFG->dirroot.'/completion/cron.php');
28bd3d9a
PS
341 completion_cron();
342 mtrace('done');
343 }
344
8cf1862c
DM
345 //now do plagiarism checks
346 require_once($CFG->libdir.'/plagiarismlib.php');
347 plagiarism_cron();
348
28bd3d9a 349
b5541735
PS
350 mtrace('Starting course reports');
351 cron_execute_plugin_type('coursereport');
352 mtrace('Finished course reports');
28bd3d9a 353
50ed196e 354
b5541735
PS
355 // run gradebook import/export/report cron
356 mtrace('Starting gradebook plugins');
357 cron_execute_plugin_type('gradeimport');
358 cron_execute_plugin_type('gradeexport');
359 cron_execute_plugin_type('gradereport');
360 mtrace('Finished gradebook plugins');
28bd3d9a 361
b5a52acd
JH
362 // run calendar cron
363 require_once "{$CFG->dirroot}/calendar/lib.php";
364 calendar_cron();
50ed196e 365
28bd3d9a 366 // Run external blog cron if needed
850d2db8 367 if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
28bd3d9a
PS
368 require_once($CFG->dirroot . '/blog/lib.php');
369 mtrace("Fetching external blog entries...", '');
658b9372 370 cron_trace_time_and_memory();
28bd3d9a 371 $sql = "timefetched < ? OR timefetched = 0";
e2bb3c92 372 $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
28bd3d9a
PS
373
374 foreach ($externalblogs as $eb) {
375 blog_sync_external_entries($eb);
376 }
b5541735 377 mtrace('done.');
28bd3d9a 378 }
28bd3d9a 379 // Run blog associations cleanup
850d2db8 380 if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
28bd3d9a
PS
381 require_once($CFG->dirroot . '/blog/lib.php');
382 // delete entries whose contextids no longer exists
383 mtrace("Deleting blog associations linked to non-existent contexts...", '');
658b9372 384 cron_trace_time_and_memory();
28bd3d9a 385 $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
b5541735 386 mtrace('done.');
28bd3d9a
PS
387 }
388
50ed196e 389
2ec325c2
TH
390 // Run question bank clean-up.
391 mtrace("Starting the question bank cron...", '');
658b9372 392 cron_trace_time_and_memory();
2ec325c2
TH
393 require_once($CFG->libdir . '/questionlib.php');
394 question_bank::cron();
395 mtrace('done.');
396
397
28bd3d9a
PS
398 //Run registration updated cron
399 mtrace(get_string('siteupdatesstart', 'hub'));
658b9372 400 cron_trace_time_and_memory();
a91b4aa6 401 require_once($CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php');
28bd3d9a
PS
402 $registrationmanager = new registration_manager();
403 $registrationmanager->cron();
404 mtrace(get_string('siteupdatesend', 'hub'));
405
19d11b3b 406 // If enabled, fetch information about available updates and eventually notify site admins
fef693c8 407 if (empty($CFG->disableupdatenotifications)) {
e87214bd 408 $updateschecker = \core\update\checker::instance();
fef693c8
DM
409 $updateschecker->cron();
410 }
28bd3d9a
PS
411
412 //cleanup old session linked tokens
413 //deletes the session linked tokens that are over a day old.
414 mtrace("Deleting session linked tokens more than one day old...", '');
658b9372 415 cron_trace_time_and_memory();
28bd3d9a
PS
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');
67233725 428 cron_execute_plugin_type('repository', 'repository plugins');
c2f5e2ab
TH
429 cron_execute_plugin_type('qbehaviour', 'question behaviours');
430 cron_execute_plugin_type('qformat', 'question import/export formats');
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
bd3b3bba 438 if ($locals = core_component::get_plugin_list('local')) {
28bd3d9a 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
059102e7
SH
451 mtrace('Running cache cron routines');
452 cache_helper::cron();
453 mtrace('done.');
50ed196e 454
fd0e0192
455 // Portfolio cron - this needs to be close to the end because it may take a long time.
456 if ($CFG->enableportfolios) {
457 mtrace('Starting the portfolio cron...');
458 cron_trace_time_and_memory();
459 require_once($CFG->libdir . '/portfoliolib.php');
460 portfolio_cron();
461 mtrace('done');
462 }
463
50ed196e
PS
464 // Run automated backups if required - these may take a long time to execute
465 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
466 require_once($CFG->dirroot.'/backup/util/helper/backup_cron_helper.class.php');
467 backup_cron_automated_helper::run_automated_backup();
468
469
470 // Run stats as at the end because they are known to take very long time on large sites
471 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
472 require_once($CFG->dirroot.'/lib/statslib.php');
473 // check we're not before our runtime
474 $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour*60*60 + $CFG->statsruntimestartminute*60;
475
476 if (time() > $timetocheck) {
477 // process configured number of days as max (defaulting to 31)
478 $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
479 if (stats_cron_daily($maxdays)) {
480 if (stats_cron_weekly()) {
481 if (stats_cron_monthly()) {
482 stats_clean_old();
483 }
484 }
485 }
3ef7279f 486 core_php_time_limit::raise();
50ed196e
PS
487 } else {
488 mtrace('Next stats run after:'. userdate($timetocheck));
489 }
490 }
491
27806552
YB
492 // Run badges review cron.
493 mtrace("Starting badges cron...");
494 require_once($CFG->dirroot . '/badges/cron.php');
495 badge_cron();
496 mtrace('done.');
50ed196e
PS
497
498 // cleanup file trash - not very important
499 $fs = get_file_storage();
500 $fs->cron();
501
28bd3d9a
PS
502 mtrace("Cron script completed correctly");
503
658b9372
TH
504 gc_collect_cycles();
505 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
28bd3d9a
PS
506 $difftime = microtime_diff($starttime, microtime());
507 mtrace("Execution took ".$difftime." seconds");
cbb9e9b8 508}
b5541735 509
e4a626b9 510/**
511 * Executes cron functions for a specific type of plugin.
50ed196e 512 *
e4a626b9 513 * @param string $plugintype Plugin type (e.g. 'report')
514 * @param string $description If specified, will display 'Starting (whatever)'
515 * and 'Finished (whatever)' lines, otherwise does not display
516 */
b5541735
PS
517function cron_execute_plugin_type($plugintype, $description = null) {
518 global $DB;
519
e4a626b9 520 // Get list from plugin => function for all plugins
521 $plugins = get_plugin_list_with_function($plugintype, 'cron');
522
523 // Modify list for backward compatibility (different files/names)
524 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
b5541735 525
e4a626b9 526 // Return if no plugins with cron function to process
b5541735
PS
527 if (!$plugins) {
528 return;
529 }
530
531 if ($description) {
532 mtrace('Starting '.$description);
533 }
534
535 foreach ($plugins as $component=>$cronfunction) {
b0d1d941 536 $dir = core_component::get_component_directory($component);
e4a626b9 537
538 // Get cron period if specified in version.php, otherwise assume every cron
b5541735
PS
539 $cronperiod = 0;
540 if (file_exists("$dir/version.php")) {
541 $plugin = new stdClass();
542 include("$dir/version.php");
543 if (isset($plugin->cron)) {
544 $cronperiod = $plugin->cron;
545 }
546 }
547
e4a626b9 548 // Using last cron and cron period, don't run if it already ran recently
b5541735 549 $lastcron = get_config($component, 'lastcron');
e4a626b9 550 if ($cronperiod && $lastcron) {
b5541735
PS
551 if ($lastcron + $cronperiod > time()) {
552 // do not execute cron yet
553 continue;
554 }
555 }
556
e4a626b9 557 mtrace('Processing cron function for ' . $component . '...');
658b9372 558 cron_trace_time_and_memory();
b5541735 559 $pre_dbqueries = $DB->perf_get_queries();
e4a626b9 560 $pre_time = microtime(true);
b5541735
PS
561
562 $cronfunction();
563
e4a626b9 564 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
565 round(microtime(true) - $pre_time, 2) . " seconds)");
b5541735
PS
566
567 set_config('lastcron', time(), $component);
3ef7279f 568 core_php_time_limit::raise();
b5541735
PS
569 }
570
571 if ($description) {
e4a626b9 572 mtrace('Finished ' . $description);
b5541735
PS
573 }
574}
575
e4a626b9 576/**
577 * Used to add in old-style cron functions within plugins that have not been converted to the
578 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
579 * cron.php and some used a different name.)
50ed196e 580 *
e4a626b9 581 * @param string $plugintype Plugin type e.g. 'report'
582 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
583 * 'report_frog_cron') for plugin cron functions that were already found using the new API
584 * @return array Revised version of $plugins that adds in any extra plugin functions found by
585 * looking in the older location
586 */
587function cron_bc_hack_plugin_functions($plugintype, $plugins) {
588 global $CFG; // mandatory in case it is referenced by include()d PHP script
589
590 if ($plugintype === 'report') {
591 // Admin reports only - not course report because course report was
592 // never implemented before, so doesn't need BC
bd3b3bba 593 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
e4a626b9 594 $component = $plugintype . '_' . $pluginname;
b5541735 595 if (isset($plugins[$component])) {
e4a626b9 596 // We already have detected the function using the new API
b5541735
PS
597 continue;
598 }
599 if (!file_exists("$dir/cron.php")) {
e4a626b9 600 // No old style cron file present
b5541735
PS
601 continue;
602 }
603 include_once("$dir/cron.php");
e4a626b9 604 $cronfunction = $component . '_cron';
b5541735
PS
605 if (function_exists($cronfunction)) {
606 $plugins[$component] = $cronfunction;
607 } else {
e4a626b9 608 debugging("Invalid legacy cron.php detected in $component, " .
609 "please use lib.php instead");
b5541735
PS
610 }
611 }
b5541735 612 } else if (strpos($plugintype, 'grade') === 0) {
e4a626b9 613 // Detect old style cron function names
614 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
615 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
bd3b3bba 616 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
b5541735
PS
617 $component = $plugintype.'_'.$pluginname;
618 if (isset($plugins[$component])) {
e4a626b9 619 // We already have detected the function using the new API
b5541735
PS
620 continue;
621 }
622 if (!file_exists("$dir/lib.php")) {
623 continue;
624 }
625 include_once("$dir/lib.php");
e4a626b9 626 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
627 $pluginname . '_cron';
b5541735
PS
628 if (function_exists($cronfunction)) {
629 $plugins[$component] = $cronfunction;
630 }
631 }
632 }
633
634 return $plugins;
50ed196e
PS
635}
636
658b9372
TH
637/**
638 * Output some standard information during cron runs. Specifically current time
639 * and memory usage. This method also does gc_collect_cycles() (before displaying
640 * memory usage) to try to help PHP manage memory better.
641 */
642function cron_trace_time_and_memory() {
643 gc_collect_cycles();
644 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
645}
50ed196e
PS
646
647/**
648 * Notify admin users or admin user of any failed logins (since last notification).
649 *
650 * Note that this function must be only executed from the cron script
651 * It uses the cache_flags system to store temporary records, deleting them
652 * by name before finishing
192a8e13
EM
653 *
654 * @return bool True if executed, false if not
50ed196e
PS
655 */
656function notify_login_failures() {
657 global $CFG, $DB, $OUTPUT;
658
192a8e13
EM
659 if (empty($CFG->notifyloginfailures)) {
660 return false;
661 }
662
50ed196e
PS
663 $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
664
aa12ec98
EL
665 if (empty($CFG->lastnotifyfailure)) {
666 $CFG->lastnotifyfailure=0;
667 }
668
192a8e13
EM
669 // If it has been less than an hour, or if there are no recipients, don't execute.
670 if (((time() - HOURSECS) < $CFG->lastnotifyfailure) || !is_array($recip) || count($recip) <= 0) {
671 return false;
672 }
673
50ed196e
PS
674 // we need to deal with the threshold stuff first.
675 if (empty($CFG->notifyloginthreshold)) {
676 $CFG->notifyloginthreshold = 10; // default to something sensible.
677 }
678
679 // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
680 // and insert them into the cache_flags temp table
681 $sql = "SELECT ip, COUNT(*)
682 FROM {log}
683 WHERE module = 'login' AND action = 'error'
684 AND time > ?
685 GROUP BY ip
686 HAVING COUNT(*) >= ?";
687 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
688 $rs = $DB->get_recordset_sql($sql, $params);
689 foreach ($rs as $iprec) {
690 if (!empty($iprec->ip)) {
691 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
692 }
693 }
694 $rs->close();
695
696 // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
697 // and insert them into the cache_flags temp table
698 $sql = "SELECT info, count(*)
699 FROM {log}
700 WHERE module = 'login' AND action = 'error'
701 AND time > ?
702 GROUP BY info
703 HAVING count(*) >= ?";
704 $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
705 $rs = $DB->get_recordset_sql($sql, $params);
706 foreach ($rs as $inforec) {
707 if (!empty($inforec->info)) {
708 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
709 }
710 }
711 $rs->close();
712
713 // Now, select all the login error logged records belonging to the ips and infos
714 // since lastnotifyfailure, that we have stored in the cache_flags table
a415ecc2
RT
715 $sql = "SELECT * FROM (
716 SELECT l.*, u.firstname, u.lastname
50ed196e
PS
717 FROM {log} l
718 JOIN {cache_flags} cf ON l.ip = cf.name
719 LEFT JOIN {user} u ON l.userid = u.id
720 WHERE l.module = 'login' AND l.action = 'error'
721 AND l.time > ?
722 AND cf.flagtype = 'login_failure_by_ip'
723 UNION ALL
724 SELECT l.*, u.firstname, u.lastname
725 FROM {log} l
726 JOIN {cache_flags} cf ON l.info = cf.name
727 LEFT JOIN {user} u ON l.userid = u.id
728 WHERE l.module = 'login' AND l.action = 'error'
729 AND l.time > ?
a415ecc2
RT
730 AND cf.flagtype = 'login_failure_by_info') t
731 ORDER BY t.time DESC";
50ed196e
PS
732 $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
733
734 // Init some variables
735 $count = 0;
736 $messages = '';
737 // Iterate over the logs recordset
738 $rs = $DB->get_recordset_sql($sql, $params);
739 foreach ($rs as $log) {
740 $log->time = userdate($log->time);
741 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
742 $count++;
743 }
744 $rs->close();
745
192a8e13
EM
746 // If we have something useful to report.
747 if ($count > 0) {
50ed196e
PS
748 $site = get_site();
749 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
750 // Calculate the complete body of notification (start + messages + end)
751 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
752 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
753 $messages .
754 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
755
756 // For each destination, send mail
757 mtrace('Emailing admins about '. $count .' failed login attempts');
758 foreach ($recip as $admin) {
759 //emailing the admins directly rather than putting these through the messaging system
2b503e40 760 email_to_user($admin, core_user::get_support_user(), $subject, $body);
50ed196e 761 }
50ed196e
PS
762 }
763
54c2756c
EM
764 // Update lastnotifyfailure with current time
765 set_config('lastnotifyfailure', time());
766
50ed196e
PS
767 // Finally, delete all the temp records we have created in cache_flags
768 $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
192a8e13
EM
769
770 return true;
50ed196e 771}
179961e8
TG
772
773/**
774 * Delete files and directories older than one week from directory provided by $CFG->tempdir.
775 *
2ef8ff9e 776 * @throws Exception Failed reading/accessing file or directory
179961e8
TG
777 * @return bool True on successful file and directory deletion; otherwise, false on failure
778 */
779function cron_delete_from_temp() {
780 global $CFG;
781
782 $tmpdir = $CFG->tempdir;
783 // Default to last weeks time.
784 $time = strtotime('-1 week');
785
786 try {
787 $dir = new RecursiveDirectoryIterator($tmpdir);
788 // Show all child nodes prior to their parent.
789 $iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
790
791 for ($iter->rewind(); $iter->valid(); $iter->next()) {
c4012e7e 792 $node = $iter->getRealPath();
179961e8
TG
793 if (!is_readable($node)) {
794 continue;
795 }
796 // Check if file or directory is older than the given time.
797 if ($iter->getMTime() < $time) {
798 if ($iter->isDir() && !$iter->isDot()) {
799 if (@rmdir($node) === false) {
800 mtrace("Failed removing directory '$node'.");
801 }
802 }
803 if ($iter->isFile()) {
804 if (@unlink($node) === false) {
805 mtrace("Failed removing file '$node'.");
806 }
807 }
808 }
809 }
810 } catch (Exception $e) {
811 mtrace('Failed reading/accessing file or directory.');
812 return false;
813 }
814
815 return true;
816}