Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.88% covered (success)
93.88%
46 / 49
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
DbBackupCommand
93.88% covered (success)
93.88%
46 / 49
66.67% covered (warning)
66.67%
2 / 3
12.03
0.00% covered (danger)
0.00%
0 / 1
 getAllowedAppEnvs
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle
91.43% covered (success)
91.43%
32 / 35
0.00% covered (danger)
0.00%
0 / 1
4.01
 pruneOldBackups
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
7
1<?php
2
3namespace Olz\Command;
4
5use Olz\Command\Common\OlzCommand;
6use Olz\Entity\Roles\Role;
7use Olz\Repository\Roles\PredefinedRole;
8use Symfony\Component\Console\Attribute\AsCommand;
9use Symfony\Component\Console\Command\Command;
10use Symfony\Component\Console\Input\InputInterface;
11use Symfony\Component\Console\Output\OutputInterface;
12use Symfony\Component\Mime\Email;
13use Symfony\Component\Mime\Part\DataPart;
14use Symfony\Component\Mime\Part\File;
15
16#[AsCommand(name: 'olz:db-backup')]
17class DbBackupCommand extends OlzCommand {
18    /** Number of days for which daily backups are kept. */
19    public const RETENTION_DAYS = 31;
20
21    public const BACKUP_FILENAME_REGEX = '/^backup-([0-9]{4}-[0-9]{2}-[0-9]{2})\.crypt\.json$/';
22
23    /** @return array<string> */
24    protected function getAllowedAppEnvs(): array {
25        return ['dev', 'test', 'staging', 'prod'];
26    }
27
28    protected function handle(InputInterface $input, OutputInterface $output): int {
29        $key = $this->envUtils()->getDatabaseBackupKey();
30        $backups_path = "{$this->envUtils()->getPrivatePath()}backups/";
31        if (!is_dir($backups_path)) {
32            mkdir($backups_path, 0o777, true);
33        }
34
35        $today = $this->dateUtils()->getIsoToday();
36        $file_path = "{$backups_path}backup-{$today}.crypt.json";
37        $this->devDataUtils()->writeDbBackup($key, $file_path);
38        $this->logAndOutput("Database backup written to {$file_path}.");
39
40        $num_pruned = $this->pruneOldBackups($backups_path);
41        $this->logAndOutput("Pruned {$num_pruned} old database backup(s).");
42
43        $day_of_month = intval(substr($today, 8, 2));
44        if ($day_of_month !== 1) {
45            $this->logAndOutput("Not the first of the month ({$today}). Not sending monthly backup email.", level: 'debug');
46            return Command::SUCCESS;
47        }
48
49        $role_repo = $this->entityManager()->getRepository(Role::class);
50        $role = $role_repo->getPredefinedRole(PredefinedRole::Sysadmin);
51        $role_name = $role?->getUsername();
52        if (!$role_name) {
53            $this->logAndOutput("No sysadmin role email found!", level: 'error');
54            return Command::SUCCESS;
55        }
56        $host = $this->envUtils()->getEmailForwardingHost();
57        $recipient_email = "{$role_name}@{$host}";
58
59        $text = <<<ZZZZZZZZZZ
60            Hallo,
61
62            Im Anhang findet ihr das monatliche Datenbank-Backup der OLZ-Webseite ({$today}).
63
64            Die Datei ist mit dem `database_backup_key` verschlüsselt und kann bei Bedarf
65            mit `tools/decrypt_backup/decrypt_backup.sh` wieder entschlüsselt werden.
66
67            Liebe Grüsse
68            OLZ-Website
69            ZZZZZZZZZZ;
70
71        $email = (new Email())
72            ->to($recipient_email)
73            ->subject("[OLZ] Monatliches Datenbank-Backup")
74            ->text($text)
75        ;
76        $email->addPart(new DataPart(new File($file_path), "olz-website-{$today}.crypt.bak"));
77        $this->emailUtils()->send($email);
78        $this->logAndOutput("Sent monthly database backup email to {$recipient_email}.");
79
80        return Command::SUCCESS;
81    }
82
83    protected function pruneOldBackups(string $backups_path): int {
84        $retention_seconds = 86400 * self::RETENTION_DAYS;
85        $cutoff = (strtotime("{$this->dateUtils()->getIsoToday()} 00:00:00") ?: 0) - $retention_seconds;
86        $num_pruned = 0;
87        $filenames = scandir($backups_path) ?: [];
88        foreach ($filenames as $filename) {
89            if (!preg_match(self::BACKUP_FILENAME_REGEX, $filename, $matches)) {
90                continue;
91            }
92            $backup_timestamp = strtotime($matches[1]);
93            if ($backup_timestamp === false || $backup_timestamp >= $cutoff) {
94                continue;
95            }
96            unlink("{$backups_path}{$filename}");
97            $num_pruned++;
98        }
99        return $num_pruned;
100    }
101}