Merge branch 'wip-MDL-42288-master' of git://github.com/marinaglancy/moodle
[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
SH
379 $config = get_config('backup');
380 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_AUTOMATED, $userid);
381
382 try {
383
384 $settings = array(
385 'users' => 'backup_auto_users',
0d5e5644 386 'role_assignments' => 'backup_auto_role_assignments',
bac233d3
SH
387 'activities' => 'backup_auto_activities',
388 'blocks' => 'backup_auto_blocks',
389 'filters' => 'backup_auto_filters',
390 'comments' => 'backup_auto_comments',
2832093f 391 'badges' => 'backup_auto_badges',
bac233d3
SH
392 'completion_information' => 'backup_auto_userscompletion',
393 'logs' => 'backup_auto_logs',
6507aaea
DP
394 'histories' => 'backup_auto_histories',
395 'questionbank' => 'backup_auto_questionbank'
bac233d3
SH
396 );
397 foreach ($settings as $setting => $configsetting) {
398 if ($bc->get_plan()->setting_exists($setting)) {
2d2489e5
DP
399 if (isset($config->{$configsetting})) {
400 $bc->get_plan()->get_setting($setting)->set_value($config->{$configsetting});
401 }
bac233d3
SH
402 }
403 }
404
405 // Set the default filename
406 $format = $bc->get_format();
407 $type = $bc->get_type();
408 $id = $bc->get_id();
409 $users = $bc->get_plan()->get_setting('users')->get_value();
410 $anonymised = $bc->get_plan()->get_setting('anonymize')->get_value();
411 $bc->get_plan()->get_setting('filename')->set_value(backup_plan_dbops::get_default_backup_filename($format, $type, $id, $users, $anonymised));
743fff98 412
bac233d3
SH
413 $bc->set_status(backup::STATUS_AWAITING);
414
fde4c609 415 $bc->execute_plan();
bac233d3 416 $results = $bc->get_results();
05e521c9 417 $outcome = self::outcome_from_results($results);
096702f6 418 $file = $results['backup_destination']; // may be empty if file already moved to target location
bac233d3
SH
419 $dir = $config->backup_auto_destination;
420 $storage = (int)$config->backup_auto_storage;
421 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
422 $dir = null;
423 }
096702f6 424 if ($file && !empty($dir) && $storage !== 0) {
66150286 425 $filename = backup_plan_dbops::get_default_backup_filename($format, $type, $course->id, $users, $anonymised, !$config->backup_shortname);
05e521c9
FM
426 if (!$file->copy_content_to($dir.'/'.$filename)) {
427 $outcome = self::BACKUP_STATUS_ERROR;
428 }
429 if ($outcome != self::BACKUP_STATUS_ERROR && $storage === 1) {
bac233d3
SH
430 $file->delete();
431 }
432 }
433
fde4c609
EL
434 } catch (moodle_exception $e) {
435 $bc->log('backup_auto_failed_on_course', backup::LOG_ERROR, $course->shortname); // Log error header.
436 $bc->log('Exception: ' . $e->errorcode, backup::LOG_ERROR, $e->a, 1); // Log original exception problem.
437 $bc->log('Debug: ' . $e->debuginfo, backup::LOG_DEBUG, null, 1); // Log original debug information.
05e521c9 438 $outcome = self::BACKUP_STATUS_ERROR;
bac233d3
SH
439 }
440
ca1292e0
SH
441 $bc->destroy();
442 unset($bc);
443
fde4c609 444 return $outcome;
bac233d3
SH
445 }
446
05e521c9
FM
447 /**
448 * Returns the backup outcome by analysing its results.
449 *
450 * @param array $results returned by a backup
451 * @return int {@link self::BACKUP_STATUS_OK} and other constants
452 */
453 public static function outcome_from_results($results) {
454 $outcome = self::BACKUP_STATUS_OK;
455 foreach ($results as $code => $value) {
456 // Each possible error and warning code has to be specified in this switch
457 // which basically analyses the results to return the correct backup status.
458 switch ($code) {
459 case 'missing_files_in_pool':
460 $outcome = self::BACKUP_STATUS_WARNING;
461 break;
462 }
463 // If we found the highest error level, we exit the loop.
464 if ($outcome == self::BACKUP_STATUS_ERROR) {
465 break;
466 }
467 }
468 return $outcome;
469 }
470
bac233d3
SH
471 /**
472 * Removes deleted courses fromn the backup_courses table so that we don't
473 * waste time backing them up.
474 *
475 * @global moodle_database $DB
476 * @return int
477 */
478 public static function remove_deleted_courses_from_schedule() {
479 global $DB;
480 $skipped = 0;
481 $sql = "SELECT bc.courseid FROM {backup_courses} bc WHERE bc.courseid NOT IN (SELECT c.id FROM {course} c)";
482 $rs = $DB->get_recordset_sql($sql);
483 foreach ($rs as $deletedcourse) {
484 //Doesn't exist, so delete from backup tables
485 $DB->delete_records('backup_courses', array('courseid'=>$deletedcourse->courseid));
486 $skipped++;
487 }
488 $rs->close();
489 return $skipped;
490 }
491
492 /**
493 * Gets the state of the automated backup system.
494 *
495 * @global moodle_database $DB
496 * @return int One of self::STATE_*
497 */
081c914b 498 public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) {
bac233d3
SH
499 global $DB;
500
501 $config = get_config('backup');
081c914b 502 $active = (int)$config->backup_auto_active;
4d91f735
FM
503 $weekdays = (string)$config->backup_auto_weekdays;
504
505 // In case of automated backup also check that it is scheduled for at least one weekday.
506 if ($active === self::AUTO_BACKUP_DISABLED ||
507 ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL) ||
508 ($rundirective == self::RUN_ON_SCHEDULE && strpos($weekdays, '1') === false)) {
bac233d3
SH
509 return self::STATE_DISABLED;
510 } else if (!empty($config->backup_auto_running)) {
beae4a66
EL
511 // Detect if the backup_auto_running semaphore is a valid one
512 // by looking for recent activity in the backup_controllers table
513 // for backups of type backup::MODE_AUTOMATED
514 $timetosee = 60 * 90; // Time to consider in order to clean the semaphore
515 $params = array( 'purpose' => backup::MODE_AUTOMATED, 'timetolook' => (time() - $timetosee));
516 if ($DB->record_exists_select('backup_controllers',
517 "operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook", $params)) {
518 return self::STATE_RUNNING; // Recent activity found, still running
519 } else {
520 // No recent activity found, let's clean the semaphore
521 mtrace('Automated backups activity not found in last ' . (int)$timetosee/60 . ' minutes. Cleaning running status');
522 backup_cron_automated_helper::set_state_running(false);
523 }
bac233d3
SH
524 }
525 return self::STATE_OK;
526 }
527
528 /**
529 * Sets the state of the automated backup system.
530 *
531 * @param bool $running
532 * @return bool
533 */
534 public static function set_state_running($running = true) {
535 if ($running === true) {
536 if (self::get_automated_backup_state() === self::STATE_RUNNING) {
537 throw new backup_exception('backup_automated_already_running');
538 }
539 set_config('backup_auto_running', '1', 'backup');
540 } else {
541 unset_config('backup_auto_running', 'backup');
542 }
543 return true;
544 }
545
546 /**
547 * Removes excess backups from the external system and the local file system.
548 *
db6c8b82 549 * The number of backups keep comes from $config->backup_auto_keep.
bac233d3 550 *
db6c8b82 551 * @param stdClass $course object
bac233d3
SH
552 * @return bool
553 */
554 public static function remove_excess_backups($course) {
555 $config = get_config('backup');
556 $keep = (int)$config->backup_auto_keep;
557 $storage = $config->backup_auto_storage;
558 $dir = $config->backup_auto_destination;
559
dbf7784e 560 if ($keep == 0) {
db6c8b82 561 // Means keep all backup files.
dbf7784e
PS
562 return true;
563 }
564
2f1e464a 565 $backupword = str_replace(' ', '_', core_text::strtolower(get_string('backupfilename')));
bac233d3
SH
566 $backupword = trim(clean_filename($backupword), '_');
567
568 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
569 $dir = null;
570 }
571
db6c8b82 572 // Clean up excess backups in the course backup filearea.
bac233d3
SH
573 if ($storage == 0 || $storage == 2) {
574 $fs = get_file_storage();
a689cd1d 575 $context = context_course::instance($course->id);
bac233d3
SH
576 $component = 'backup';
577 $filearea = 'automated';
578 $itemid = 0;
579 $files = array();
db6c8b82 580 // Store all the matching files into timemodified => stored_file array.
bac233d3
SH
581 foreach ($fs->get_area_files($context->id, $component, $filearea, $itemid) as $file) {
582 if (strpos($file->get_filename(), $backupword) !== 0) {
583 continue;
584 }
585 $files[$file->get_timemodified()] = $file;
586 }
8afbe44f 587 if (count($files) <= $keep) {
db6c8b82 588 // There are less matching files than the desired number to keep there is nothing to clean up.
8afbe44f
EL
589 return 0;
590 }
db6c8b82 591 // Sort by keys descending (newer to older filemodified).
8afbe44f 592 krsort($files);
bac233d3
SH
593 $remove = array_splice($files, $keep);
594 foreach ($remove as $file) {
595 $file->delete();
596 }
8afbe44f 597 //mtrace('Removed '.count($remove).' old backup file(s) from the automated filearea');
bac233d3
SH
598 }
599
db6c8b82 600 // Clean up excess backups in the specified external directory.
bac233d3 601 if (!empty($dir) && ($storage == 1 || $storage == 2)) {
8afbe44f 602 // Calculate backup filename regex, ignoring the date/time/info parts that can be
db6c8b82
FM
603 // variable, depending of languages, formats and automated backup settings.
604 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $course->id . '-';
8afbe44f 605 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
bac233d3 606
db6c8b82 607 // Store all the matching files into filename => timemodified array.
bac233d3
SH
608 $files = array();
609 foreach (scandir($dir) as $file) {
db6c8b82
FM
610 // Skip files not matching the naming convention.
611 if (!preg_match($regex, $file, $matches)) {
612 continue;
613 }
614
615 // Read the information contained in the backup itself.
616 try {
617 $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file);
618 } catch (backup_helper_exception $e) {
619 mtrace('Error: ' . $file . ' does not appear to be a valid backup (' . $e->errorcode . ')');
620 continue;
621 }
622
623 // Make sure this backup concerns the course and site we are looking for.
624 if ($bcinfo->format === backup::FORMAT_MOODLE &&
625 $bcinfo->type === backup::TYPE_1COURSE &&
626 $bcinfo->original_course_id == $course->id &&
627 backup_general_helper::backup_is_samesite($bcinfo)) {
628 $files[$file] = $bcinfo->backup_date;
bac233d3
SH
629 }
630 }
631 if (count($files) <= $keep) {
db6c8b82 632 // There are less matching files than the desired number to keep there is nothing to clean up.
bac233d3
SH
633 return 0;
634 }
db6c8b82 635 // Sort by values descending (newer to older filemodified).
bac233d3
SH
636 arsort($files);
637 $remove = array_splice($files, $keep);
638 foreach (array_keys($remove) as $file) {
8afbe44f 639 unlink($dir . '/' . $file);
bac233d3
SH
640 }
641 //mtrace('Removed '.count($remove).' old backup file(s) from external directory');
642 }
643
644 return true;
645 }
02cf6919 646}