weekly release 2.6dev
[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
FM
135
136 // Skip courses that do not yet need backup.
4d91f735 137 $skipped = !(($backupcourse->nextstarttime > 0 && $backupcourse->nextstarttime < $now) || $rundirective == self::RUN_IMMEDIATELY);
58e03319 138 $skippedmessage = 'Does not require backup';
4d91f735 139
1c1ae7a7
FM
140 // If config backup_auto_skip_hidden is set to true, skip courses that are not visible.
141 if (!$skipped && $config->backup_auto_skip_hidden) {
914442ae
JPG
142 $skipped = ($config->backup_auto_skip_hidden && !$course->visible);
143 $skippedmessage = 'Not visible';
4d91f735
FM
144 }
145
1c1ae7a7
FM
146 // If config backup_auto_skip_modif_days is set to true, skip courses
147 // that have not been modified since the number of days defined.
148 if (!$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_days) {
149 $sqlwhere = "course=:courseid AND time>:time AND ".$DB->sql_like('action', ':action', false, true, true);
150 $timenotmodifsincedays = $now - ($config->backup_auto_skip_modif_days * DAYSECS);
151 // Check log if there were any modifications to the course content.
152 $params = array('courseid' => $course->id,
153 'time' => $timenotmodifsincedays,
154 'action' => '%view%');
a6c124f5 155 $logexists = $DB->record_exists_select('log', $sqlwhere, $params);
1c1ae7a7
FM
156
157 $skipped = ($course->timemodified <= $timenotmodifsincedays && !$logexists);
58e03319 158 $skippedmessage = 'Not modified in the past '.$config->backup_auto_skip_modif_days.' days';
e2558cd3 159 }
4d91f735 160
1c1ae7a7
FM
161 // If config backup_auto_skip_modif_prev is set to true, skip courses
162 // that have not been modified since previous backup.
163 if (!$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_prev) {
164 // Check log if there were any modifications to the course content.
165 $params = array('courseid' => $course->id,
166 'time' => $backupcourse->laststarttime,
167 'action' => '%view%');
168 $logexists = $DB->record_exists_select('log', $sqlwhere, $params);
169
170 $skipped = ($course->timemodified <= $backupcourse->laststarttime && !$logexists);
171 $skippedmessage = 'Not modified since previous backup';
e2558cd3 172 }
4d91f735 173
914442ae
JPG
174 // Skip courses not needed for backup.
175 if ($skipped) {
1c1ae7a7
FM
176 // Output the next execution time when it has been updated.
177 if ($backupcourse->nextstarttime != $nextstarttime) {
178 mtrace('Backup of \'' . $course->fullname . '\' is scheduled on ' . $showtime);
179 }
914442ae
JPG
180 $backupcourse->laststatus = self::BACKUP_STATUS_SKIPPED;
181 $backupcourse->nextstarttime = $nextstarttime;
182 $DB->update_record('backup_courses', $backupcourse);
183 mtrace('Skipping '.$course->fullname.' ('.$skippedmessage.')');
1c1ae7a7
FM
184 } else {
185 // Backup every non-skipped courses.
4d91f735 186 mtrace('Backing up '.$course->fullname.'...');
bac233d3 187
1c1ae7a7 188 // We have to send an email because we have included at least one backup.
bac233d3 189 $emailpending = true;
743fff98 190
1c1ae7a7 191 // Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error).
914442ae 192 if ($backupcourse->laststatus != self::BACKUP_STATUS_UNFINISHED) {
1c1ae7a7 193 // Set laststarttime.
bac233d3
SH
194 $starttime = time();
195
196 $backupcourse->laststarttime = time();
05e521c9 197 $backupcourse->laststatus = self::BACKUP_STATUS_UNFINISHED;
bac233d3
SH
198 $DB->update_record('backup_courses', $backupcourse);
199
200 $backupcourse->laststatus = backup_cron_automated_helper::launch_automated_backup($course, $backupcourse->laststarttime, $admin->id);
201 $backupcourse->lastendtime = time();
202 $backupcourse->nextstarttime = $nextstarttime;
203
204 $DB->update_record('backup_courses', $backupcourse);
205
05e521c9 206 if ($backupcourse->laststatus === self::BACKUP_STATUS_OK) {
bac233d3
SH
207 // Clean up any excess course backups now that we have
208 // taken a successful backup.
209 $removedcount = backup_cron_automated_helper::remove_excess_backups($course);
210 }
211 }
212
213 mtrace("complete - next execution: $showtime");
214 }
215 }
216 $rs->close();
217 }
218
219 //Send email to admin if necessary
220 if ($emailpending) {
221 mtrace("Sending email to admin");
222 $message = "";
223
224 $count = backup_cron_automated_helper::get_backup_status_array();
05e521c9 225 $haserrors = ($count[self::BACKUP_STATUS_ERROR] != 0 || $count[self::BACKUP_STATUS_UNFINISHED] != 0);
bac233d3
SH
226
227 //Build the message text
228 //Summary
229 $message .= get_string('summary')."\n";
230 $message .= "==================================================\n";
231 $message .= " ".get_string('courses').": ".array_sum($count)."\n";
05e521c9
FM
232 $message .= " ".get_string('ok').": ".$count[self::BACKUP_STATUS_OK]."\n";
233 $message .= " ".get_string('skipped').": ".$count[self::BACKUP_STATUS_SKIPPED]."\n";
234 $message .= " ".get_string('error').": ".$count[self::BACKUP_STATUS_ERROR]."\n";
235 $message .= " ".get_string('unfinished').": ".$count[self::BACKUP_STATUS_UNFINISHED]."\n";
236 $message .= " ".get_string('warning').": ".$count[self::BACKUP_STATUS_WARNING]."\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,
05e521c9 299 self::BACKUP_STATUS_WARNING => 0
bac233d3
SH
300 );
301
4cb18cb0 302 $statuses = $DB->get_records_sql('SELECT DISTINCT bc.laststatus, COUNT(bc.courseid) AS statuscount FROM {backup_courses} bc GROUP BY bc.laststatus');
bac233d3
SH
303
304 foreach ($statuses as $status) {
305 if (empty($status->statuscount)) {
306 $status->statuscount = 0;
307 }
308 $result[(int)$status->laststatus] += $status->statuscount;
309 }
310
311 return $result;
312 }
313
314 /**
315 * Works out the next time the automated backup should be run.
316 *
4d91f735
FM
317 * @param mixed $timezone user timezone
318 * @param int $now timestamp, should not be in the past, most likely time()
319 * @return int timestamp of the next execution at server time
bac233d3
SH
320 */
321 public static function calculate_next_automated_backup($timezone, $now) {
322
4d91f735 323 $result = 0;
bac233d3 324 $config = get_config('backup');
4d91f735
FM
325 $autohour = $config->backup_auto_hour;
326 $automin = $config->backup_auto_minute;
327
328 // Gets the user time relatively to the server time.
bac233d3 329 $date = usergetdate($now, $timezone);
4d91f735
FM
330 $usertime = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
331 $diff = $now - $usertime;
743fff98 332
4d91f735 333 // Get number of days (from user's today) to execute backups.
d4a49ba2 334 $automateddays = substr($config->backup_auto_weekdays, $date['wday']) . $config->backup_auto_weekdays;
4d91f735 335 $daysfromnow = strpos($automateddays, "1");
d4a49ba2 336
4d91f735
FM
337 // Error, there are no days to schedule the backup for.
338 if ($daysfromnow === false) {
339 return 0;
bac233d3
SH
340 }
341
4d91f735
FM
342 // Checks if the date would happen in the future (of the user).
343 $userresult = mktime($autohour, $automin, 0, $date['mon'], $date['mday'] + $daysfromnow, $date['year']);
344 if ($userresult <= $usertime) {
345 // If not, we skip the first scheduled day, that should fix it.
346 $daysfromnow = strpos($automateddays, "1", 1);
347 $userresult = mktime($autohour, $automin, 0, $date['mon'], $date['mday'] + $daysfromnow, $date['year']);
bac233d3
SH
348 }
349
4d91f735
FM
350 // Now we generate the time relative to the server.
351 $result = $userresult + $diff;
352
353 // If that time is past, call the function recursively to obtain the next valid day.
354 if ($result <= $now) {
355 // Checking time() in here works, but makes PHPUnit Tests extremely hard to predict.
356 // $now should never be earlier than time() anyway...
357 $result = self::calculate_next_automated_backup($timezone, $now + DAYSECS);
bac233d3
SH
358 }
359
360 return $result;
361 }
362
363 /**
364 * Launches a automated backup routine for the given course
365 *
366 * @param stdClass $course
367 * @param int $starttime
368 * @param int $userid
369 * @return bool
370 */
371 public static function launch_automated_backup($course, $starttime, $userid) {
372
05e521c9 373 $outcome = self::BACKUP_STATUS_OK;
bac233d3
SH
374 $config = get_config('backup');
375 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_AUTOMATED, $userid);
376
377 try {
378
379 $settings = array(
380 'users' => 'backup_auto_users',
0d5e5644 381 'role_assignments' => 'backup_auto_role_assignments',
bac233d3
SH
382 'activities' => 'backup_auto_activities',
383 'blocks' => 'backup_auto_blocks',
384 'filters' => 'backup_auto_filters',
385 'comments' => 'backup_auto_comments',
2832093f 386 'badges' => 'backup_auto_badges',
bac233d3
SH
387 'completion_information' => 'backup_auto_userscompletion',
388 'logs' => 'backup_auto_logs',
6507aaea
DP
389 'histories' => 'backup_auto_histories',
390 'questionbank' => 'backup_auto_questionbank'
bac233d3
SH
391 );
392 foreach ($settings as $setting => $configsetting) {
393 if ($bc->get_plan()->setting_exists($setting)) {
2d2489e5
DP
394 if (isset($config->{$configsetting})) {
395 $bc->get_plan()->get_setting($setting)->set_value($config->{$configsetting});
396 }
bac233d3
SH
397 }
398 }
399
400 // Set the default filename
401 $format = $bc->get_format();
402 $type = $bc->get_type();
403 $id = $bc->get_id();
404 $users = $bc->get_plan()->get_setting('users')->get_value();
405 $anonymised = $bc->get_plan()->get_setting('anonymize')->get_value();
406 $bc->get_plan()->get_setting('filename')->set_value(backup_plan_dbops::get_default_backup_filename($format, $type, $id, $users, $anonymised));
743fff98 407
bac233d3
SH
408 $bc->set_status(backup::STATUS_AWAITING);
409
fde4c609 410 $bc->execute_plan();
bac233d3 411 $results = $bc->get_results();
05e521c9 412 $outcome = self::outcome_from_results($results);
096702f6 413 $file = $results['backup_destination']; // may be empty if file already moved to target location
bac233d3
SH
414 $dir = $config->backup_auto_destination;
415 $storage = (int)$config->backup_auto_storage;
416 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
417 $dir = null;
418 }
096702f6 419 if ($file && !empty($dir) && $storage !== 0) {
66150286 420 $filename = backup_plan_dbops::get_default_backup_filename($format, $type, $course->id, $users, $anonymised, !$config->backup_shortname);
05e521c9
FM
421 if (!$file->copy_content_to($dir.'/'.$filename)) {
422 $outcome = self::BACKUP_STATUS_ERROR;
423 }
424 if ($outcome != self::BACKUP_STATUS_ERROR && $storage === 1) {
bac233d3
SH
425 $file->delete();
426 }
427 }
428
fde4c609
EL
429 } catch (moodle_exception $e) {
430 $bc->log('backup_auto_failed_on_course', backup::LOG_ERROR, $course->shortname); // Log error header.
431 $bc->log('Exception: ' . $e->errorcode, backup::LOG_ERROR, $e->a, 1); // Log original exception problem.
432 $bc->log('Debug: ' . $e->debuginfo, backup::LOG_DEBUG, null, 1); // Log original debug information.
05e521c9 433 $outcome = self::BACKUP_STATUS_ERROR;
bac233d3
SH
434 }
435
ca1292e0
SH
436 $bc->destroy();
437 unset($bc);
438
fde4c609 439 return $outcome;
bac233d3
SH
440 }
441
05e521c9
FM
442 /**
443 * Returns the backup outcome by analysing its results.
444 *
445 * @param array $results returned by a backup
446 * @return int {@link self::BACKUP_STATUS_OK} and other constants
447 */
448 public static function outcome_from_results($results) {
449 $outcome = self::BACKUP_STATUS_OK;
450 foreach ($results as $code => $value) {
451 // Each possible error and warning code has to be specified in this switch
452 // which basically analyses the results to return the correct backup status.
453 switch ($code) {
454 case 'missing_files_in_pool':
455 $outcome = self::BACKUP_STATUS_WARNING;
456 break;
457 }
458 // If we found the highest error level, we exit the loop.
459 if ($outcome == self::BACKUP_STATUS_ERROR) {
460 break;
461 }
462 }
463 return $outcome;
464 }
465
bac233d3
SH
466 /**
467 * Removes deleted courses fromn the backup_courses table so that we don't
468 * waste time backing them up.
469 *
470 * @global moodle_database $DB
471 * @return int
472 */
473 public static function remove_deleted_courses_from_schedule() {
474 global $DB;
475 $skipped = 0;
476 $sql = "SELECT bc.courseid FROM {backup_courses} bc WHERE bc.courseid NOT IN (SELECT c.id FROM {course} c)";
477 $rs = $DB->get_recordset_sql($sql);
478 foreach ($rs as $deletedcourse) {
479 //Doesn't exist, so delete from backup tables
480 $DB->delete_records('backup_courses', array('courseid'=>$deletedcourse->courseid));
481 $skipped++;
482 }
483 $rs->close();
484 return $skipped;
485 }
486
487 /**
488 * Gets the state of the automated backup system.
489 *
490 * @global moodle_database $DB
491 * @return int One of self::STATE_*
492 */
081c914b 493 public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) {
bac233d3
SH
494 global $DB;
495
496 $config = get_config('backup');
081c914b 497 $active = (int)$config->backup_auto_active;
4d91f735
FM
498 $weekdays = (string)$config->backup_auto_weekdays;
499
500 // In case of automated backup also check that it is scheduled for at least one weekday.
501 if ($active === self::AUTO_BACKUP_DISABLED ||
502 ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL) ||
503 ($rundirective == self::RUN_ON_SCHEDULE && strpos($weekdays, '1') === false)) {
bac233d3
SH
504 return self::STATE_DISABLED;
505 } else if (!empty($config->backup_auto_running)) {
beae4a66
EL
506 // Detect if the backup_auto_running semaphore is a valid one
507 // by looking for recent activity in the backup_controllers table
508 // for backups of type backup::MODE_AUTOMATED
509 $timetosee = 60 * 90; // Time to consider in order to clean the semaphore
510 $params = array( 'purpose' => backup::MODE_AUTOMATED, 'timetolook' => (time() - $timetosee));
511 if ($DB->record_exists_select('backup_controllers',
512 "operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook", $params)) {
513 return self::STATE_RUNNING; // Recent activity found, still running
514 } else {
515 // No recent activity found, let's clean the semaphore
516 mtrace('Automated backups activity not found in last ' . (int)$timetosee/60 . ' minutes. Cleaning running status');
517 backup_cron_automated_helper::set_state_running(false);
518 }
bac233d3
SH
519 }
520 return self::STATE_OK;
521 }
522
523 /**
524 * Sets the state of the automated backup system.
525 *
526 * @param bool $running
527 * @return bool
528 */
529 public static function set_state_running($running = true) {
530 if ($running === true) {
531 if (self::get_automated_backup_state() === self::STATE_RUNNING) {
532 throw new backup_exception('backup_automated_already_running');
533 }
534 set_config('backup_auto_running', '1', 'backup');
535 } else {
536 unset_config('backup_auto_running', 'backup');
537 }
538 return true;
539 }
540
541 /**
542 * Removes excess backups from the external system and the local file system.
543 *
db6c8b82 544 * The number of backups keep comes from $config->backup_auto_keep.
bac233d3 545 *
db6c8b82 546 * @param stdClass $course object
bac233d3
SH
547 * @return bool
548 */
549 public static function remove_excess_backups($course) {
550 $config = get_config('backup');
551 $keep = (int)$config->backup_auto_keep;
552 $storage = $config->backup_auto_storage;
553 $dir = $config->backup_auto_destination;
554
dbf7784e 555 if ($keep == 0) {
db6c8b82 556 // Means keep all backup files.
dbf7784e
PS
557 return true;
558 }
559
2f1e464a 560 $backupword = str_replace(' ', '_', core_text::strtolower(get_string('backupfilename')));
bac233d3
SH
561 $backupword = trim(clean_filename($backupword), '_');
562
563 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
564 $dir = null;
565 }
566
db6c8b82 567 // Clean up excess backups in the course backup filearea.
bac233d3
SH
568 if ($storage == 0 || $storage == 2) {
569 $fs = get_file_storage();
a689cd1d 570 $context = context_course::instance($course->id);
bac233d3
SH
571 $component = 'backup';
572 $filearea = 'automated';
573 $itemid = 0;
574 $files = array();
db6c8b82 575 // Store all the matching files into timemodified => stored_file array.
bac233d3
SH
576 foreach ($fs->get_area_files($context->id, $component, $filearea, $itemid) as $file) {
577 if (strpos($file->get_filename(), $backupword) !== 0) {
578 continue;
579 }
580 $files[$file->get_timemodified()] = $file;
581 }
8afbe44f 582 if (count($files) <= $keep) {
db6c8b82 583 // There are less matching files than the desired number to keep there is nothing to clean up.
8afbe44f
EL
584 return 0;
585 }
db6c8b82 586 // Sort by keys descending (newer to older filemodified).
8afbe44f 587 krsort($files);
bac233d3
SH
588 $remove = array_splice($files, $keep);
589 foreach ($remove as $file) {
590 $file->delete();
591 }
8afbe44f 592 //mtrace('Removed '.count($remove).' old backup file(s) from the automated filearea');
bac233d3
SH
593 }
594
db6c8b82 595 // Clean up excess backups in the specified external directory.
bac233d3 596 if (!empty($dir) && ($storage == 1 || $storage == 2)) {
8afbe44f 597 // Calculate backup filename regex, ignoring the date/time/info parts that can be
db6c8b82
FM
598 // variable, depending of languages, formats and automated backup settings.
599 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $course->id . '-';
8afbe44f 600 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
bac233d3 601
db6c8b82 602 // Store all the matching files into filename => timemodified array.
bac233d3
SH
603 $files = array();
604 foreach (scandir($dir) as $file) {
db6c8b82
FM
605 // Skip files not matching the naming convention.
606 if (!preg_match($regex, $file, $matches)) {
607 continue;
608 }
609
610 // Read the information contained in the backup itself.
611 try {
612 $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file);
613 } catch (backup_helper_exception $e) {
614 mtrace('Error: ' . $file . ' does not appear to be a valid backup (' . $e->errorcode . ')');
615 continue;
616 }
617
618 // Make sure this backup concerns the course and site we are looking for.
619 if ($bcinfo->format === backup::FORMAT_MOODLE &&
620 $bcinfo->type === backup::TYPE_1COURSE &&
621 $bcinfo->original_course_id == $course->id &&
622 backup_general_helper::backup_is_samesite($bcinfo)) {
623 $files[$file] = $bcinfo->backup_date;
bac233d3
SH
624 }
625 }
626 if (count($files) <= $keep) {
db6c8b82 627 // There are less matching files than the desired number to keep there is nothing to clean up.
bac233d3
SH
628 return 0;
629 }
db6c8b82 630 // Sort by values descending (newer to older filemodified).
bac233d3
SH
631 arsort($files);
632 $remove = array_splice($files, $keep);
633 foreach (array_keys($remove) as $file) {
8afbe44f 634 unlink($dir . '/' . $file);
bac233d3
SH
635 }
636 //mtrace('Removed '.count($remove).' old backup file(s) from external directory');
637 }
638
639 return true;
640 }
02cf6919 641}