weekly release 3.0dev
[moodle.git] / backup / util / helper / backup_cron_helper.class.php
CommitLineData
bac233d3
SH
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
bac233d3
SH
18/**
19 * Utility helper for automated backups run through cron.
20 *
21 * @package core
22 * @subpackage backup
23 * @copyright 2010 Sam Hemelryk
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
db6c8b82
FM
27defined('MOODLE_INTERNAL') || die();
28
bac233d3
SH
29/**
30 * This class is an abstract class with methods that can be called to aid the
31 * running of automated backups over cron.
32 */
33abstract class backup_cron_automated_helper {
34
70f210c0 35 /** Automated backups are active and ready to run */
bac233d3 36 const STATE_OK = 0;
70f210c0 37 /** Automated backups are disabled and will not be run */
bac233d3 38 const STATE_DISABLED = 1;
70f210c0 39 /** Automated backups are all ready running! */
bac233d3
SH
40 const STATE_RUNNING = 2;
41
42 /** Course automated backup completed successfully */
43 const BACKUP_STATUS_OK = 1;
44 /** Course automated backup errored */
45 const BACKUP_STATUS_ERROR = 0;
46 /** Course automated backup never finished */
47 const BACKUP_STATUS_UNFINISHED = 2;
48 /** Course automated backup was skipped */
49 const BACKUP_STATUS_SKIPPED = 3;
05e521c9
FM
50 /** Course automated backup had warnings */
51 const BACKUP_STATUS_WARNING = 4;
70f210c0
MN
52 /** Course automated backup has yet to be run */
53 const BACKUP_STATUS_NOTYETRUN = 5;
bac233d3 54
081c914b
SH
55 /** Run if required by the schedule set in config. Default. **/
56 const RUN_ON_SCHEDULE = 0;
743fff98
PS
57 /** Run immediately. **/
58 const RUN_IMMEDIATELY = 1;
081c914b
SH
59
60 const AUTO_BACKUP_DISABLED = 0;
61 const AUTO_BACKUP_ENABLED = 1;
62 const AUTO_BACKUP_MANUAL = 2;
bac233d3
SH
63
64 /**
65 * Runs the automated backups if required
66 *
67 * @global moodle_database $DB
68 */
081c914b 69 public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE) {
bac233d3
SH
70 global $CFG, $DB;
71
72 $status = true;
73 $emailpending = false;
74 $now = time();
914442ae 75 $config = get_config('backup');
bac233d3
SH
76
77 mtrace("Checking automated backup status",'...');
081c914b 78 $state = backup_cron_automated_helper::get_automated_backup_state($rundirective);
bac233d3
SH
79 if ($state === backup_cron_automated_helper::STATE_DISABLED) {
80 mtrace('INACTIVE');
081c914b 81 return $state;
bac233d3
SH
82 } else if ($state === backup_cron_automated_helper::STATE_RUNNING) {
83 mtrace('RUNNING');
743fff98 84 if ($rundirective == self::RUN_IMMEDIATELY) {
beae4a66 85 mtrace('Automated backups are already running. If this script is being run by cron this constitues an error. You will need to increase the time between executions within cron.');
081c914b
SH
86 } else {
87 mtrace("automated backup are already running. Execution delayed");
88 }
89 return $state;
bac233d3
SH
90 } else {
91 mtrace('OK');
92 }
93 backup_cron_automated_helper::set_state_running();
94
95 mtrace("Getting admin info");
96 $admin = get_admin();
97 if (!$admin) {
98 mtrace("Error: No admin account was found");
99 $state = false;
100 }
101
102 if ($status) {
103 mtrace("Checking courses");
104 mtrace("Skipping deleted courses", '...');
105 mtrace(sprintf("%d courses", backup_cron_automated_helper::remove_deleted_courses_from_schedule()));
106 }
107
108 if ($status) {
109
110 mtrace('Running required automated backups...');
658b9372 111 cron_trace_time_and_memory();
bac233d3
SH
112
113 // This could take a while!
3ef7279f 114 core_php_time_limit::raise();
bac233d3
SH
115 raise_memory_limit(MEMORY_EXTRA);
116
d6e7a63d 117 $nextstarttime = backup_cron_automated_helper::calculate_next_automated_backup(null, $now);
bac233d3
SH
118 $showtime = "undefined";
119 if ($nextstarttime > 0) {
4d91f735 120 $showtime = date('r', $nextstarttime);
bac233d3
SH
121 }
122
123 $rs = $DB->get_recordset('course');
124 foreach ($rs as $course) {
70f210c0 125 $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
bac233d3
SH
126 if (!$backupcourse) {
127 $backupcourse = new stdClass;
128 $backupcourse->courseid = $course->id;
70f210c0
MN
129 $backupcourse->laststatus = self::BACKUP_STATUS_NOTYETRUN;
130 $DB->insert_record('backup_courses', $backupcourse);
131 $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
bac233d3
SH
132 }
133
1c1ae7a7 134 // The last backup is considered as successful when OK or SKIPPED.
d3ea1327
JPG
135 $lastbackupwassuccessful = ($backupcourse->laststatus == self::BACKUP_STATUS_SKIPPED ||
136 $backupcourse->laststatus == self::BACKUP_STATUS_OK) && (
137 $backupcourse->laststarttime > 0 && $backupcourse->lastendtime > 0);
1c1ae7a7 138
5043bcfa
MN
139 // Assume that we are not skipping anything.
140 $skipped = false;
141 $skippedmessage = '';
142
143 // Check if we are going to be running the backup now.
144 $shouldrunnow = (($backupcourse->nextstarttime > 0 && $backupcourse->nextstarttime < $now)
145 || $rundirective == self::RUN_IMMEDIATELY);
4d91f735 146
1c1ae7a7 147 // If config backup_auto_skip_hidden is set to true, skip courses that are not visible.
5043bcfa 148 if ($shouldrunnow && $config->backup_auto_skip_hidden) {
914442ae
JPG
149 $skipped = ($config->backup_auto_skip_hidden && !$course->visible);
150 $skippedmessage = 'Not visible';
4d91f735
FM
151 }
152
1c1ae7a7
FM
153 // If config backup_auto_skip_modif_days is set to true, skip courses
154 // that have not been modified since the number of days defined.
5043bcfa 155 if ($shouldrunnow && !$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_days) {
1c1ae7a7
FM
156 $timenotmodifsincedays = $now - ($config->backup_auto_skip_modif_days * DAYSECS);
157 // Check log if there were any modifications to the course content.
25239798 158 $logexists = self::is_course_modified($course->id, $timenotmodifsincedays);
1c1ae7a7 159 $skipped = ($course->timemodified <= $timenotmodifsincedays && !$logexists);
58e03319 160 $skippedmessage = 'Not modified in the past '.$config->backup_auto_skip_modif_days.' days';
e2558cd3 161 }
4d91f735 162
1c1ae7a7
FM
163 // If config backup_auto_skip_modif_prev is set to true, skip courses
164 // that have not been modified since previous backup.
5043bcfa 165 if ($shouldrunnow && !$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_prev) {
1c1ae7a7 166 // Check log if there were any modifications to the course content.
25239798 167 $logexists = self::is_course_modified($course->id, $backupcourse->laststarttime);
1c1ae7a7
FM
168 $skipped = ($course->timemodified <= $backupcourse->laststarttime && !$logexists);
169 $skippedmessage = 'Not modified since previous backup';
e2558cd3 170 }
4d91f735 171
5043bcfa
MN
172 // Check if the course is not scheduled to run right now.
173 if (!$shouldrunnow) {
174 $backupcourse->nextstarttime = $nextstarttime;
175 $DB->update_record('backup_courses', $backupcourse);
176 mtrace('Skipping ' . $course->fullname . ' (Not scheduled for backup until ' . $showtime . ')');
177 } else if ($skipped) { // Must have been skipped for a reason.
914442ae
JPG
178 $backupcourse->laststatus = self::BACKUP_STATUS_SKIPPED;
179 $backupcourse->nextstarttime = $nextstarttime;
180 $DB->update_record('backup_courses', $backupcourse);
5043bcfa
MN
181 mtrace('Skipping ' . $course->fullname . ' (' . $skippedmessage . ')');
182 mtrace('Backup of \'' . $course->fullname . '\' is scheduled on ' . $showtime);
1c1ae7a7
FM
183 } else {
184 // Backup every non-skipped courses.
4d91f735 185 mtrace('Backing up '.$course->fullname.'...');
bac233d3 186
1c1ae7a7 187 // We have to send an email because we have included at least one backup.
bac233d3 188 $emailpending = true;
743fff98 189
1c1ae7a7 190 // Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error).
914442ae 191 if ($backupcourse->laststatus != self::BACKUP_STATUS_UNFINISHED) {
1c1ae7a7 192 // Set laststarttime.
bac233d3
SH
193 $starttime = time();
194
195 $backupcourse->laststarttime = time();
05e521c9 196 $backupcourse->laststatus = self::BACKUP_STATUS_UNFINISHED;
bac233d3
SH
197 $DB->update_record('backup_courses', $backupcourse);
198
199 $backupcourse->laststatus = backup_cron_automated_helper::launch_automated_backup($course, $backupcourse->laststarttime, $admin->id);
200 $backupcourse->lastendtime = time();
201 $backupcourse->nextstarttime = $nextstarttime;
202
203 $DB->update_record('backup_courses', $backupcourse);
204
05e521c9 205 if ($backupcourse->laststatus === self::BACKUP_STATUS_OK) {
bac233d3
SH
206 // Clean up any excess course backups now that we have
207 // taken a successful backup.
208 $removedcount = backup_cron_automated_helper::remove_excess_backups($course);
209 }
210 }
211
212 mtrace("complete - next execution: $showtime");
213 }
214 }
215 $rs->close();
216 }
217
218 //Send email to admin if necessary
219 if ($emailpending) {
220 mtrace("Sending email to admin");
221 $message = "";
222
223 $count = backup_cron_automated_helper::get_backup_status_array();
05e521c9 224 $haserrors = ($count[self::BACKUP_STATUS_ERROR] != 0 || $count[self::BACKUP_STATUS_UNFINISHED] != 0);
bac233d3 225
70f210c0
MN
226 // Build the message text.
227 // Summary.
228 $message .= get_string('summary') . "\n";
bac233d3 229 $message .= "==================================================\n";
70f210c0
MN
230 $message .= ' ' . get_string('courses') . '; ' . array_sum($count) . "\n";
231 $message .= ' ' . get_string('ok') . '; ' . $count[self::BACKUP_STATUS_OK] . "\n";
232 $message .= ' ' . get_string('skipped') . '; ' . $count[self::BACKUP_STATUS_SKIPPED] . "\n";
233 $message .= ' ' . get_string('error') . '; ' . $count[self::BACKUP_STATUS_ERROR] . "\n";
234 $message .= ' ' . get_string('unfinished') . '; ' . $count[self::BACKUP_STATUS_UNFINISHED] . "\n";
235 $message .= ' ' . get_string('warning') . '; ' . $count[self::BACKUP_STATUS_WARNING] . "\n";
236 $message .= ' ' . get_string('backupnotyetrun') . '; ' . $count[self::BACKUP_STATUS_NOTYETRUN]."\n\n";
bac233d3
SH
237
238 //Reference
239 if ($haserrors) {
240 $message .= " ".get_string('backupfailed')."\n\n";
daca599f 241 $dest_url = "$CFG->wwwroot/report/backups/index.php";
bac233d3
SH
242 $message .= " ".get_string('backuptakealook','',$dest_url)."\n\n";
243 //Set message priority
244 $admin->priority = 1;
245 //Reset unfinished to error
246 $DB->set_field('backup_courses','laststatus','0', array('laststatus'=>'2'));
247 } else {
248 $message .= " ".get_string('backupfinished')."\n";
249 }
250
251 //Build the message subject
252 $site = get_site();
a689cd1d 253 $prefix = format_string($site->shortname, true, array('context' => context_course::instance(SITEID))).": ";
bac233d3
SH
254 if ($haserrors) {
255 $prefix .= "[".strtoupper(get_string('error'))."] ";
256 }
257 $subject = $prefix.get_string('automatedbackupstatus', 'backup');
258
259 //Send the message
260 $eventdata = new stdClass();
261 $eventdata->modulename = 'moodle';
262 $eventdata->userfrom = $admin;
263 $eventdata->userto = $admin;
264 $eventdata->subject = $subject;
265 $eventdata->fullmessage = $message;
266 $eventdata->fullmessageformat = FORMAT_PLAIN;
267 $eventdata->fullmessagehtml = '';
268 $eventdata->smallmessage = '';
269
270 $eventdata->component = 'moodle';
271 $eventdata->name = 'backup';
272
273 message_send($eventdata);
274 }
275
276 //Everything is finished stop backup_auto_running
277 backup_cron_automated_helper::set_state_running(false);
278
279 mtrace('Automated backups complete.');
280
281 return $status;
282 }
283
284 /**
285 * Gets the results from the last automated backup that was run based upon
286 * the statuses of the courses that were looked at.
287 *
288 * @global moodle_database $DB
289 * @return array
290 */
291 public static function get_backup_status_array() {
292 global $DB;
293
294 $result = array(
295 self::BACKUP_STATUS_ERROR => 0,
296 self::BACKUP_STATUS_OK => 0,
297 self::BACKUP_STATUS_UNFINISHED => 0,
298 self::BACKUP_STATUS_SKIPPED => 0,
70f210c0
MN
299 self::BACKUP_STATUS_WARNING => 0,
300 self::BACKUP_STATUS_NOTYETRUN => 0
bac233d3
SH
301 );
302
4cb18cb0 303 $statuses = $DB->get_records_sql('SELECT DISTINCT bc.laststatus, COUNT(bc.courseid) AS statuscount FROM {backup_courses} bc GROUP BY bc.laststatus');
bac233d3
SH
304
305 foreach ($statuses as $status) {
306 if (empty($status->statuscount)) {
307 $status->statuscount = 0;
308 }
309 $result[(int)$status->laststatus] += $status->statuscount;
310 }
311
312 return $result;
313 }
314
315 /**
316 * Works out the next time the automated backup should be run.
317 *
e49cb057 318 * @param mixed $ignoredtimezone all settings are in server timezone!
4d91f735
FM
319 * @param int $now timestamp, should not be in the past, most likely time()
320 * @return int timestamp of the next execution at server time
bac233d3 321 */
e49cb057 322 public static function calculate_next_automated_backup($ignoredtimezone, $now) {
bac233d3 323
bac233d3 324 $config = get_config('backup');
4d91f735 325
d6e7a63d
PS
326 $backuptime = new DateTime('@' . $now);
327 $backuptime->setTimezone(core_date::get_server_timezone_object());
328 $backuptime->setTime($config->backup_auto_hour, $config->backup_auto_minute);
743fff98 329
d6e7a63d
PS
330 while ($backuptime->getTimestamp() < $now) {
331 $backuptime->add(new DateInterval('P1D'));
332 }
333
334 // Get number of days from backup date to execute backups.
335 $automateddays = substr($config->backup_auto_weekdays, $backuptime->format('w')) . $config->backup_auto_weekdays;
4d91f735 336 $daysfromnow = strpos($automateddays, "1");
d4a49ba2 337
4d91f735
FM
338 // Error, there are no days to schedule the backup for.
339 if ($daysfromnow === false) {
340 return 0;
bac233d3
SH
341 }
342
d6e7a63d
PS
343 if ($daysfromnow > 0) {
344 $backuptime->add(new DateInterval('P' . $daysfromnow . 'D'));
bac233d3
SH
345 }
346
d6e7a63d 347 return $backuptime->getTimestamp();
bac233d3
SH
348 }
349
350 /**
351 * Launches a automated backup routine for the given course
352 *
353 * @param stdClass $course
354 * @param int $starttime
355 * @param int $userid
356 * @return bool
357 */
358 public static function launch_automated_backup($course, $starttime, $userid) {
359
05e521c9 360 $outcome = self::BACKUP_STATUS_OK;
bac233d3 361 $config = get_config('backup');
b2e791d1
AA
362 $dir = $config->backup_auto_destination;
363 $storage = (int)$config->backup_auto_storage;
364
365 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO,
366 backup::MODE_AUTOMATED, $userid);
bac233d3
SH
367
368 try {
369
b2e791d1 370 // Set the default filename.
bac233d3
SH
371 $format = $bc->get_format();
372 $type = $bc->get_type();
373 $id = $bc->get_id();
374 $users = $bc->get_plan()->get_setting('users')->get_value();
375 $anonymised = $bc->get_plan()->get_setting('anonymize')->get_value();
b2e791d1
AA
376 $bc->get_plan()->get_setting('filename')->set_value(backup_plan_dbops::get_default_backup_filename($format, $type,
377 $id, $users, $anonymised));
743fff98 378
bac233d3
SH
379 $bc->set_status(backup::STATUS_AWAITING);
380
fde4c609 381 $bc->execute_plan();
bac233d3 382 $results = $bc->get_results();
05e521c9 383 $outcome = self::outcome_from_results($results);
b2e791d1 384 $file = $results['backup_destination']; // May be empty if file already moved to target location.
80a1dfe5 385
94b8c636
FM
386 // If we need to copy the backup file to an external dir and it is not writable, change status to error.
387 // This is a feature to prevent moodledata to be filled up and break a site when the admin misconfigured
388 // the automated backups storage type and destination directory.
389 if ($storage !== 0 && (empty($dir) || !file_exists($dir) || !is_dir($dir) || !is_writable($dir))) {
390 $bc->log('Specified backup directory is not writable - ', backup::LOG_ERROR, $dir);
bac233d3 391 $dir = null;
80a1dfe5 392 $outcome = self::BACKUP_STATUS_ERROR;
bac233d3 393 }
80a1dfe5 394
b2e791d1
AA
395 // Copy file only if there was no error.
396 if ($file && !empty($dir) && $storage !== 0 && $outcome != self::BACKUP_STATUS_ERROR) {
397 $filename = backup_plan_dbops::get_default_backup_filename($format, $type, $course->id, $users, $anonymised,
398 !$config->backup_shortname);
05e521c9 399 if (!$file->copy_content_to($dir.'/'.$filename)) {
80a1dfe5
AA
400 $bc->log('Attempt to copy backup file to the specified directory failed - ',
401 backup::LOG_ERROR, $dir);
05e521c9
FM
402 $outcome = self::BACKUP_STATUS_ERROR;
403 }
404 if ($outcome != self::BACKUP_STATUS_ERROR && $storage === 1) {
80a1dfe5
AA
405 if (!$file->delete()) {
406 $outcome = self::BACKUP_STATUS_WARNING;
407 $bc->log('Attempt to delete the backup file from course automated backup area failed - ',
408 backup::LOG_WARNING, $file->get_filename());
409 }
bac233d3
SH
410 }
411 }
412
fde4c609
EL
413 } catch (moodle_exception $e) {
414 $bc->log('backup_auto_failed_on_course', backup::LOG_ERROR, $course->shortname); // Log error header.
415 $bc->log('Exception: ' . $e->errorcode, backup::LOG_ERROR, $e->a, 1); // Log original exception problem.
416 $bc->log('Debug: ' . $e->debuginfo, backup::LOG_DEBUG, null, 1); // Log original debug information.
05e521c9 417 $outcome = self::BACKUP_STATUS_ERROR;
bac233d3
SH
418 }
419
b2e791d1
AA
420 // Delete the backup file immediately if something went wrong.
421 if ($outcome === self::BACKUP_STATUS_ERROR) {
422
423 // Delete the file from file area if exists.
424 if (!empty($file)) {
425 $file->delete();
426 }
427
428 // Delete file from external storage if exists.
429 if ($storage !== 0 && !empty($filename) && file_exists($dir.'/'.$filename)) {
430 @unlink($dir.'/'.$filename);
431 }
432 }
433
ca1292e0
SH
434 $bc->destroy();
435 unset($bc);
436
fde4c609 437 return $outcome;
bac233d3
SH
438 }
439
05e521c9
FM
440 /**
441 * Returns the backup outcome by analysing its results.
442 *
443 * @param array $results returned by a backup
444 * @return int {@link self::BACKUP_STATUS_OK} and other constants
445 */
446 public static function outcome_from_results($results) {
447 $outcome = self::BACKUP_STATUS_OK;
448 foreach ($results as $code => $value) {
449 // Each possible error and warning code has to be specified in this switch
450 // which basically analyses the results to return the correct backup status.
451 switch ($code) {
452 case 'missing_files_in_pool':
453 $outcome = self::BACKUP_STATUS_WARNING;
454 break;
455 }
456 // If we found the highest error level, we exit the loop.
457 if ($outcome == self::BACKUP_STATUS_ERROR) {
458 break;
459 }
460 }
461 return $outcome;
462 }
463
bac233d3
SH
464 /**
465 * Removes deleted courses fromn the backup_courses table so that we don't
466 * waste time backing them up.
467 *
468 * @global moodle_database $DB
469 * @return int
470 */
471 public static function remove_deleted_courses_from_schedule() {
472 global $DB;
473 $skipped = 0;
474 $sql = "SELECT bc.courseid FROM {backup_courses} bc WHERE bc.courseid NOT IN (SELECT c.id FROM {course} c)";
475 $rs = $DB->get_recordset_sql($sql);
476 foreach ($rs as $deletedcourse) {
477 //Doesn't exist, so delete from backup tables
478 $DB->delete_records('backup_courses', array('courseid'=>$deletedcourse->courseid));
479 $skipped++;
480 }
481 $rs->close();
482 return $skipped;
483 }
484
485 /**
486 * Gets the state of the automated backup system.
487 *
488 * @global moodle_database $DB
489 * @return int One of self::STATE_*
490 */
081c914b 491 public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) {
bac233d3
SH
492 global $DB;
493
494 $config = get_config('backup');
081c914b 495 $active = (int)$config->backup_auto_active;
4d91f735
FM
496 $weekdays = (string)$config->backup_auto_weekdays;
497
498 // In case of automated backup also check that it is scheduled for at least one weekday.
499 if ($active === self::AUTO_BACKUP_DISABLED ||
500 ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL) ||
501 ($rundirective == self::RUN_ON_SCHEDULE && strpos($weekdays, '1') === false)) {
bac233d3
SH
502 return self::STATE_DISABLED;
503 } else if (!empty($config->backup_auto_running)) {
beae4a66
EL
504 // Detect if the backup_auto_running semaphore is a valid one
505 // by looking for recent activity in the backup_controllers table
506 // for backups of type backup::MODE_AUTOMATED
507 $timetosee = 60 * 90; // Time to consider in order to clean the semaphore
508 $params = array( 'purpose' => backup::MODE_AUTOMATED, 'timetolook' => (time() - $timetosee));
509 if ($DB->record_exists_select('backup_controllers',
510 "operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook", $params)) {
511 return self::STATE_RUNNING; // Recent activity found, still running
512 } else {
513 // No recent activity found, let's clean the semaphore
514 mtrace('Automated backups activity not found in last ' . (int)$timetosee/60 . ' minutes. Cleaning running status');
515 backup_cron_automated_helper::set_state_running(false);
516 }
bac233d3
SH
517 }
518 return self::STATE_OK;
519 }
520
521 /**
522 * Sets the state of the automated backup system.
523 *
524 * @param bool $running
525 * @return bool
526 */
527 public static function set_state_running($running = true) {
528 if ($running === true) {
529 if (self::get_automated_backup_state() === self::STATE_RUNNING) {
932f54e9 530 throw new backup_helper_exception('backup_automated_already_running');
bac233d3
SH
531 }
532 set_config('backup_auto_running', '1', 'backup');
533 } else {
534 unset_config('backup_auto_running', 'backup');
535 }
536 return true;
537 }
538
539 /**
540 * Removes excess backups from the external system and the local file system.
541 *
db6c8b82 542 * The number of backups keep comes from $config->backup_auto_keep.
bac233d3 543 *
db6c8b82 544 * @param stdClass $course object
bac233d3
SH
545 * @return bool
546 */
547 public static function remove_excess_backups($course) {
548 $config = get_config('backup');
549 $keep = (int)$config->backup_auto_keep;
550 $storage = $config->backup_auto_storage;
551 $dir = $config->backup_auto_destination;
552
dbf7784e 553 if ($keep == 0) {
db6c8b82 554 // Means keep all backup files.
dbf7784e
PS
555 return true;
556 }
557
bac233d3
SH
558 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
559 $dir = null;
560 }
561
db6c8b82 562 // Clean up excess backups in the course backup filearea.
bac233d3
SH
563 if ($storage == 0 || $storage == 2) {
564 $fs = get_file_storage();
a689cd1d 565 $context = context_course::instance($course->id);
bac233d3
SH
566 $component = 'backup';
567 $filearea = 'automated';
568 $itemid = 0;
569 $files = array();
db6c8b82 570 // Store all the matching files into timemodified => stored_file array.
bac233d3 571 foreach ($fs->get_area_files($context->id, $component, $filearea, $itemid) as $file) {
bac233d3
SH
572 $files[$file->get_timemodified()] = $file;
573 }
8afbe44f 574 if (count($files) <= $keep) {
db6c8b82 575 // There are less matching files than the desired number to keep there is nothing to clean up.
8afbe44f
EL
576 return 0;
577 }
db6c8b82 578 // Sort by keys descending (newer to older filemodified).
8afbe44f 579 krsort($files);
bac233d3
SH
580 $remove = array_splice($files, $keep);
581 foreach ($remove as $file) {
582 $file->delete();
583 }
8afbe44f 584 //mtrace('Removed '.count($remove).' old backup file(s) from the automated filearea');
bac233d3
SH
585 }
586
db6c8b82 587 // Clean up excess backups in the specified external directory.
bac233d3 588 if (!empty($dir) && ($storage == 1 || $storage == 2)) {
8afbe44f 589 // Calculate backup filename regex, ignoring the date/time/info parts that can be
db6c8b82 590 // variable, depending of languages, formats and automated backup settings.
425dc0ed
MN
591 $filename = backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $course->id . '-';
592 $regex = '#' . preg_quote($filename, '#') . '.*\.mbz$#';
bac233d3 593
db6c8b82 594 // Store all the matching files into filename => timemodified array.
bac233d3
SH
595 $files = array();
596 foreach (scandir($dir) as $file) {
db6c8b82
FM
597 // Skip files not matching the naming convention.
598 if (!preg_match($regex, $file, $matches)) {
599 continue;
600 }
601
602 // Read the information contained in the backup itself.
603 try {
604 $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file);
605 } catch (backup_helper_exception $e) {
606 mtrace('Error: ' . $file . ' does not appear to be a valid backup (' . $e->errorcode . ')');
607 continue;
608 }
609
610 // Make sure this backup concerns the course and site we are looking for.
611 if ($bcinfo->format === backup::FORMAT_MOODLE &&
612 $bcinfo->type === backup::TYPE_1COURSE &&
613 $bcinfo->original_course_id == $course->id &&
614 backup_general_helper::backup_is_samesite($bcinfo)) {
615 $files[$file] = $bcinfo->backup_date;
bac233d3
SH
616 }
617 }
618 if (count($files) <= $keep) {
db6c8b82 619 // There are less matching files than the desired number to keep there is nothing to clean up.
bac233d3
SH
620 return 0;
621 }
db6c8b82 622 // Sort by values descending (newer to older filemodified).
bac233d3
SH
623 arsort($files);
624 $remove = array_splice($files, $keep);
625 foreach (array_keys($remove) as $file) {
8afbe44f 626 unlink($dir . '/' . $file);
bac233d3
SH
627 }
628 //mtrace('Removed '.count($remove).' old backup file(s) from external directory');
629 }
630
631 return true;
632 }
25239798
AA
633
634 /**
635 * Check logs to find out if a course was modified since the given time.
636 *
637 * @param int $courseid course id to check
638 * @param int $since timestamp, from which to check
639 *
640 * @return bool true if the course was modified, false otherwise. This also returns false if no readers are enabled. This is
641 * intentional, since we cannot reliably determine if any modification was made or not.
642 */
643 protected static function is_course_modified($courseid, $since) {
644 $logmang = get_log_manager();
59aebbed 645 $readers = $logmang->get_readers('core\log\sql_reader');
25239798
AA
646 $where = "courseid = :courseid and timecreated > :since and crud <> 'r'";
647 $params = array('courseid' => $courseid, 'since' => $since);
648 foreach ($readers as $reader) {
649 if ($reader->get_events_select_count($where, $params)) {
650 return true;
651 }
652 }
653 return false;
654 }
02cf6919 655}