]> BookStack Code Mirror - system-cli/blob - src/Commands/RestoreCommand.php
Added main-path restore command testing
[system-cli] / src / Commands / RestoreCommand.php
1 <?php declare(strict_types=1);
2
3 namespace Cli\Commands;
4
5 use Cli\Services\AppLocator;
6 use Cli\Services\ArtisanRunner;
7 use Cli\Services\BackupZip;
8 use Cli\Services\EnvironmentLoader;
9 use Cli\Services\InteractiveConsole;
10 use Cli\Services\MySqlRunner;
11 use Cli\Services\ProgramRunner;
12 use Cli\Services\RequirementsValidator;
13 use RecursiveDirectoryIterator;
14 use RecursiveIteratorIterator;
15 use Symfony\Component\Console\Command\Command;
16 use Symfony\Component\Console\Input\InputArgument;
17 use Symfony\Component\Console\Input\InputInterface;
18 use Symfony\Component\Console\Input\InputOption;
19 use Symfony\Component\Console\Output\OutputInterface;
20
21 class RestoreCommand extends Command
22 {
23     protected function configure(): void
24     {
25         $this->setName('restore');
26         $this->addArgument('backup-zip', InputArgument::REQUIRED, 'Path to the ZIP file containing your backup.');
27         $this->setDescription('Restore data and files from a backup ZIP file.');
28         $this->addOption('app-directory', null, InputOption::VALUE_OPTIONAL, 'BookStack install directory to restore into', '');
29     }
30
31     /**
32      * @throws CommandError
33      * @throws \Exception
34      */
35     protected function execute(InputInterface $input, OutputInterface $output): int
36     {
37         $interactions = new InteractiveConsole($this->getHelper('question'), $input, $output);
38
39         $output->writeln("<info>Warning!</info>");
40         $output->writeln("<info>- A restore operation will overwrite and remove files & content from an existing instance.</info>");
41         $output->writeln("<info>- Any existing tables within the configured database will be dropped.</info>");
42         $output->writeln("<info>- You should only restore into an instance of the same or newer BookStack version.</info>");
43         $output->writeln("<info>- This command won't handle, restore or address any server configuration.</info>");
44
45         $appDir = AppLocator::require($input->getOption('app-directory'));
46         $output->writeln("<info>Checking system requirements...</info>");
47         RequirementsValidator::validate();
48         (new ProgramRunner('mysql', '/usr/bin/mysql'))->ensureFound();
49
50         $zipPath = realpath($input->getArgument('backup-zip'));
51         $zip = new BackupZip($zipPath);
52         $contents = $zip->getContentsOverview();
53
54         $output->writeln("\n<info>Contents found in the backup ZIP:</info>");
55         $hasContent = false;
56         foreach ($contents as $info) {
57             $output->writeln(($info['exists'] ? '✔ ' : '❌ ') . $info['desc']);
58             if ($info['exists']) {
59                 $hasContent = true;
60             }
61         }
62
63         if (!$hasContent) {
64             throw new CommandError("Provided ZIP backup [{$zipPath}] does not have any expected restore-able content.");
65         }
66
67         $output->writeln("<info>The checked elements will be restored into [{$appDir}].</info>");
68         $output->writeln("<info>Existing content may be overwritten.</info>");
69
70         if (!$interactions->confirm("Do you want to continue?")) {
71             $output->writeln("<info>Stopping restore operation.</info>");
72             return Command::SUCCESS;
73         }
74
75         $output->writeln("<info>Extracting ZIP into temporary directory...</info>");
76         $extractDir = $appDir . DIRECTORY_SEPARATOR . 'restore-temp-' . time();
77         if (!mkdir($extractDir)) {
78             throw new CommandError("Could not create temporary extraction directory at [{$extractDir}].");
79         }
80         $zip->extractInto($extractDir);
81
82         $envChanges = [];
83         if ($contents['env']['exists']) {
84             $output->writeln("<info>Restoring and merging .env file...</info>");
85             $envChanges = $this->restoreEnv($extractDir, $appDir, $output, $interactions);
86         }
87
88         $folderLocations = ['themes', 'public/uploads', 'storage/uploads'];
89         foreach ($folderLocations as $folderSubPath) {
90             if ($contents[$folderSubPath]['exists']) {
91                 $output->writeln("<info>Restoring {$folderSubPath} folder...</info>");
92                 $this->restoreFolder($folderSubPath, $appDir, $extractDir);
93             }
94         }
95
96         $artisan = (new ArtisanRunner($appDir));
97         if ($contents['db']['exists']) {
98             $output->writeln("<info>Restoring database from SQL dump...</info>");
99             $this->restoreDatabase($appDir, $extractDir);
100
101             $output->writeln("<info>Running database migrations...</info>");
102             $artisan->run(['migrate', '--force']);
103         }
104
105         if ($envChanges && $envChanges['old_url'] !== $envChanges['new_url']) {
106             $output->writeln("<info>App URL change made, Updating database with URL change...</info>");
107             $artisan->run([
108                 'bookstack:update-url',
109                 $envChanges['old_url'], $envChanges['new_url'],
110             ]);
111         }
112
113         $output->writeln("<info>Clearing app caches...</info>");
114         $artisan->run(['cache:clear']);
115         $artisan->run(['config:clear']);
116         $artisan->run(['view:clear']);
117
118         $output->writeln("<info>Cleaning up extract directory...</info>");
119         $this->deleteDirectoryAndContents($extractDir);
120
121         $output->writeln("<info>\nRestore operation complete!</info>");
122
123         return Command::SUCCESS;
124     }
125
126     protected function restoreEnv(string $extractDir, string $appDir, OutputInterface $output, InteractiveConsole $interactions): array
127     {
128         $oldEnv = EnvironmentLoader::load($extractDir);
129         $currentEnv = EnvironmentLoader::load($appDir);
130         $envContents = file_get_contents($extractDir . DIRECTORY_SEPARATOR . '.env');
131         $appEnvPath = $appDir . DIRECTORY_SEPARATOR . '.env';
132
133         $mysqlCurrent = MySqlRunner::fromEnvOptions($currentEnv);
134         $mysqlOld = MySqlRunner::fromEnvOptions($oldEnv);
135         if (!$mysqlOld->testConnection()) {
136             $currentWorking = $mysqlCurrent->testConnection();
137             if (!$currentWorking) {
138                 throw new CommandError("Could not find a working database configuration");
139             }
140
141             // Copy across new env details to old env
142             $currentEnvContents = file_get_contents($appEnvPath);
143             $currentEnvDbLines = array_values(array_filter(explode("\n", $currentEnvContents), function (string $line) {
144                 return str_starts_with($line, 'DB_');
145             }));
146             $oldEnvLines = array_values(array_filter(explode("\n", $currentEnvContents), function (string $line) {
147                 return !str_starts_with($line, 'DB_');
148             }));
149             $envContents = implode("\n", [
150                 '# Database credentials merged from existing .env file',
151                 ...$currentEnvDbLines,
152                 ...$oldEnvLines
153             ]);
154             copy($appEnvPath, $appEnvPath . '.backup');
155         }
156
157         $oldUrl = $oldEnv['APP_URL'] ?? '';
158         $newUrl = $currentEnv['APP_URL'] ?? '';
159         $returnData = [
160             'old_url' => $oldUrl,
161             'new_url' => $oldUrl,
162         ];
163
164         if ($oldUrl !== $newUrl) {
165             $output->writeln("Found different APP_URL values:");
166             $changedUrl = $interactions->choice('Which would you like to use?', array_filter([$oldUrl, $newUrl]));
167             $envContents = preg_replace('/^APP_URL=.*?$/', 'APP_URL="' . $changedUrl . '"', $envContents);
168             $returnData['new_url'] = $changedUrl;
169         }
170
171         file_put_contents($appDir . DIRECTORY_SEPARATOR . '.env', $envContents);
172
173         return $returnData;
174     }
175
176     protected function restoreFolder(string $folderSubPath, string $appDir, string $extractDir): void
177     {
178         $fullAppFolderPath = $appDir . DIRECTORY_SEPARATOR . $folderSubPath;
179         $this->deleteDirectoryAndContents($fullAppFolderPath);
180         rename($extractDir . DIRECTORY_SEPARATOR . $folderSubPath, $fullAppFolderPath);
181     }
182
183     protected function deleteDirectoryAndContents(string $dir)
184     {
185         $files = new RecursiveIteratorIterator(
186             new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
187             RecursiveIteratorIterator::CHILD_FIRST
188         );
189
190         foreach ($files as $fileinfo) {
191             $path = $fileinfo->getRealPath();
192             $fileinfo->isDir() ? rmdir($path) : unlink($path);
193         }
194
195         rmdir($dir);
196     }
197
198     protected function restoreDatabase(string $appDir, string $extractDir): void
199     {
200         $dbDump = $extractDir . DIRECTORY_SEPARATOR . 'db.sql';
201         $currentEnv = EnvironmentLoader::load($appDir);
202         $mysql = MySqlRunner::fromEnvOptions($currentEnv);
203
204         // Drop existing tables
205         $dropSqlTempFile = tempnam(sys_get_temp_dir(), 'bs-cli-restore');
206         file_put_contents($dropSqlTempFile, $mysql->dropTablesSql());
207         $mysql->importSqlFile($dropSqlTempFile);
208
209
210         $mysql->importSqlFile($dbDump);
211     }
212 }