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