You are here

function backup_migrate_schedule::smart_delete_backups in Backup and Migrate 6.3

Same name and namespace in other branches
  1. 8.3 includes/schedules.inc \backup_migrate_schedule::smart_delete_backups()
  2. 7.3 includes/schedules.inc \backup_migrate_schedule::smart_delete_backups()

Delete files keeping the specified number of hourly, daily, weekly and monthly backups.

1 call to backup_migrate_schedule::smart_delete_backups()
backup_migrate_schedule::remove_expired_backups in includes/schedules.inc
Remove older backups keeping only the number specified by the aministrator.

File

includes/schedules.inc, line 728
All of the schedule handling code needed for Backup and Migrate.

Class

backup_migrate_schedule
A schedule class for crud operations.

Code

function smart_delete_backups($destination, $files, $keep_subhourly = 3600, $keep_hourly = 24, $keep_daily = 14, $keep_weekly = PHP_INT_MAX, $keep_monthly = PHP_INT_MAX) {
  $now = time();
  $periods = array(
    'subhourly' => array(
      'delta' => 1,
      'keep' => $keep_subhourly,
      'last_time' => 0,
      'files' => array(),
    ),
    'hourly' => array(
      'delta' => 60 * 60,
      'keep' => $keep_hourly,
      'last_time' => 0,
      'files' => array(),
    ),
    'daily' => array(
      'delta' => 60 * 60 * 24,
      'keep' => $keep_daily,
      'last_time' => 0,
      'files' => array(),
    ),
    'weekly' => array(
      'delta' => 60 * 60 * 24 * 7,
      'keep' => $keep_weekly,
      'last_time' => 0,
      'files' => array(),
    ),
  );
  $keep_files = $filetimes = $times = $groups = $sorted = $saved = array();
  foreach ($files as $id => $file) {
    if ($file
      ->is_recognized_type()) {
      $time = $file
        ->info('filetime');
      $sorted[$id] = $time;
    }
  }
  arsort($sorted);
  $now = time();
  foreach ($periods as $i => $period) {
    foreach ($sorted as $id => $time) {
      if ($time < $now - $period['delta'] * $period['keep']) {
        break;
      }
      if ($period['last_time'] == 0 || $time <= $period['last_time'] - $period['delta']) {
        $period['last_time'] = $time;
        $keep_files[$id] = $id;
      }
    }

    // Keep oldest backup or it will get deleted if it doesn't fall on an exact multiple of the period
    if ($id) {
      $keep_files[$id] = $id;
    }
  }

  // Do the delete.
  foreach ($files as $id => $file) {
    if (!isset($keep_files[$id])) {
      $destination
        ->delete_file($file
        ->file_id());
    }
  }
}