xref: /webtrees/app/Http/RequestHandlers/UpgradeWizardStep.php (revision d1da5ba430762bd82a5d57bc40552492431d11ee)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program 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 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22use Fig\Http\Message\StatusCodeInterface;
23use Fisharebest\Flysystem\Adapter\ChrootAdapter;
24use Fisharebest\Webtrees\Exceptions\HttpServerErrorException;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Registry;
27use Fisharebest\Webtrees\Services\GedcomExportService;
28use Fisharebest\Webtrees\Services\TreeService;
29use Fisharebest\Webtrees\Services\UpgradeService;
30use Fisharebest\Webtrees\Tree;
31use Fisharebest\Webtrees\Webtrees;
32use Illuminate\Database\Capsule\Manager as DB;
33use Illuminate\Support\Collection;
34use League\Flysystem\Filesystem;
35use League\Flysystem\FilesystemOperator;
36use Psr\Http\Message\ResponseInterface;
37use Psr\Http\Message\ServerRequestInterface;
38use Psr\Http\Server\RequestHandlerInterface;
39use RuntimeException;
40use Throwable;
41
42use function assert;
43use function date;
44use function e;
45use function fclose;
46use function fopen;
47use function fseek;
48use function intdiv;
49use function microtime;
50use function response;
51use function route;
52use function version_compare;
53use function view;
54
55/**
56 * Upgrade to a new version of webtrees.
57 */
58class UpgradeWizardStep implements RequestHandlerInterface
59{
60    // We make the upgrade in a number of small steps to keep within server time limits.
61    private const STEP_CHECK    = 'Check';
62    private const STEP_PREPARE  = 'Prepare';
63    private const STEP_PENDING  = 'Pending';
64    private const STEP_EXPORT   = 'Export';
65    private const STEP_DOWNLOAD = 'Download';
66    private const STEP_UNZIP    = 'Unzip';
67    private const STEP_COPY     = 'Copy';
68
69    // Where to store our temporary files.
70    private const UPGRADE_FOLDER = 'data/tmp/upgrade/';
71
72    // Where to store the downloaded ZIP archive.
73    private const ZIP_FILENAME = 'data/tmp/webtrees.zip';
74
75    // The ZIP archive stores everything inside this top-level folder.
76    private const ZIP_FILE_PREFIX = 'webtrees';
77
78    // Cruft can accumulate after upgrades.
79    private const FOLDERS_TO_CLEAN = [
80        'app',
81        'resources',
82        'vendor',
83    ];
84
85    private GedcomExportService $gedcom_export_service;
86
87    private UpgradeService $upgrade_service;
88
89    private TreeService $tree_service;
90
91    /**
92     * UpgradeController constructor.
93     *
94     * @param GedcomExportService $gedcom_export_service
95     * @param TreeService         $tree_service
96     * @param UpgradeService      $upgrade_service
97     */
98    public function __construct(
99        GedcomExportService $gedcom_export_service,
100        TreeService $tree_service,
101        UpgradeService $upgrade_service
102    ) {
103        $this->gedcom_export_service = $gedcom_export_service;
104        $this->tree_service          = $tree_service;
105        $this->upgrade_service       = $upgrade_service;
106    }
107
108    /**
109     * Perform one step of the wizard
110     *
111     * @param ServerRequestInterface $request
112     *
113     * @return ResponseInterface
114     */
115    public function handle(ServerRequestInterface $request): ResponseInterface
116    {
117        $root_filesystem = Registry::filesystem()->root();
118        $data_filesystem = Registry::filesystem()->data();
119
120        // Somewhere to unpack a .ZIP file
121        $temporary_filesystem = new Filesystem(new ChrootAdapter($root_filesystem, self::UPGRADE_FOLDER));
122
123        $zip_file   = Webtrees::ROOT_DIR . self::ZIP_FILENAME;
124        $zip_folder = Webtrees::ROOT_DIR . self::UPGRADE_FOLDER;
125
126
127        $step = $request->getQueryParams()['step'] ?? self::STEP_CHECK;
128
129        switch ($step) {
130            case self::STEP_CHECK:
131                return $this->wizardStepCheck();
132
133            case self::STEP_PREPARE:
134                return $this->wizardStepPrepare($root_filesystem);
135
136            case self::STEP_PENDING:
137                return $this->wizardStepPending();
138
139            case self::STEP_EXPORT:
140                $tree_name = $request->getQueryParams()['tree'] ?? '';
141                $tree      = $this->tree_service->all()[$tree_name];
142                assert($tree instanceof Tree);
143
144                return $this->wizardStepExport($tree, $data_filesystem);
145
146            case self::STEP_DOWNLOAD:
147                return $this->wizardStepDownload($root_filesystem);
148
149            case self::STEP_UNZIP:
150                return $this->wizardStepUnzip($zip_file, $zip_folder);
151
152            case self::STEP_COPY:
153                return $this->wizardStepCopyAndCleanUp($zip_file, $root_filesystem, $temporary_filesystem);
154
155            default:
156                return response('', StatusCodeInterface::STATUS_NO_CONTENT);
157        }
158    }
159
160    /**
161     * @return ResponseInterface
162     */
163    private function wizardStepCheck(): ResponseInterface
164    {
165        $latest_version = $this->upgrade_service->latestVersion();
166
167        if ($latest_version === '') {
168            throw new HttpServerErrorException(I18N::translate('No upgrade information is available.'));
169        }
170
171        if (version_compare(Webtrees::VERSION, $latest_version) >= 0) {
172            $message = I18N::translate('This is the latest version of webtrees. No upgrade is available.');
173            throw new HttpServerErrorException($message);
174        }
175
176        /* I18N: %s is a version number, such as 1.2.3 */
177        $alert = I18N::translate('Upgrade to webtrees %s.', e($latest_version));
178
179        return response(view('components/alert-success', [
180            'alert' => $alert,
181        ]));
182    }
183
184    /**
185     * Make sure the temporary folder exists.
186     *
187     * @param FilesystemOperator $root_filesystem
188     *
189     * @return ResponseInterface
190     */
191    private function wizardStepPrepare(FilesystemOperator $root_filesystem): ResponseInterface
192    {
193        $root_filesystem->deleteDirectory(self::UPGRADE_FOLDER);
194        $root_filesystem->createDirectory(self::UPGRADE_FOLDER);
195
196        return response(view('components/alert-success', [
197            'alert' => I18N::translate('The folder %s has been created.', e(self::UPGRADE_FOLDER)),
198        ]));
199    }
200
201    /**
202     * @return ResponseInterface
203     */
204    private function wizardStepPending(): ResponseInterface
205    {
206        $changes = DB::table('change')->where('status', '=', 'pending')->exists();
207
208        if ($changes) {
209            return response(view('components/alert-danger', [
210                'alert' => I18N::translate('You should accept or reject all pending changes before upgrading.'),
211            ]), StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
212        }
213
214        return response(view('components/alert-success', [
215            'alert' => I18N::translate('There are no pending changes.'),
216        ]));
217    }
218
219    /**
220     * @param Tree               $tree
221     * @param FilesystemOperator $data_filesystem
222     *
223     * @return ResponseInterface
224     */
225    private function wizardStepExport(Tree $tree, FilesystemOperator $data_filesystem): ResponseInterface
226    {
227        // We store the data in PHP temporary storage.
228        $stream = fopen('php://temp', 'wb+');
229
230        if ($stream === false) {
231            throw new RuntimeException('Failed to create temporary stream');
232        }
233
234        $filename = $tree->name() . date('-Y-m-d') . '.ged';
235
236        $this->gedcom_export_service->export($tree, $stream);
237
238        fseek($stream, 0);
239        $data_filesystem->writeStream($tree->name() . date('-Y-m-d') . '.ged', $stream);
240        fclose($stream);
241
242        return response(view('components/alert-success', [
243            'alert' => I18N::translate('The family tree has been exported to %s.', e($filename)),
244        ]));
245    }
246
247    /**
248     * @param FilesystemOperator $root_filesystem
249     *
250     * @return ResponseInterface
251     */
252    private function wizardStepDownload(FilesystemOperator $root_filesystem): ResponseInterface
253    {
254        $start_time   = microtime(true);
255        $download_url = $this->upgrade_service->downloadUrl();
256
257        try {
258            $bytes = $this->upgrade_service->downloadFile($download_url, $root_filesystem, self::ZIP_FILENAME);
259        } catch (Throwable $exception) {
260            throw new HttpServerErrorException($exception->getMessage());
261        }
262
263        $kb       = I18N::number(intdiv($bytes + 1023, 1024));
264        $end_time = microtime(true);
265        $seconds  = I18N::number($end_time - $start_time, 2);
266
267        return response(view('components/alert-success', [
268            'alert' => I18N::translate('%1$s KB were downloaded in %2$s seconds.', $kb, $seconds),
269        ]));
270    }
271
272    /**
273     * For performance reasons, we use direct filesystem access for this step.
274     *
275     * @param string $zip_file
276     * @param string $zip_folder
277     *
278     * @return ResponseInterface
279     */
280    private function wizardStepUnzip(string $zip_file, string $zip_folder): ResponseInterface
281    {
282        $start_time = microtime(true);
283        $this->upgrade_service->extractWebtreesZip($zip_file, $zip_folder);
284        $count    = $this->upgrade_service->webtreesZipContents($zip_file)->count();
285        $end_time = microtime(true);
286        $seconds  = I18N::number($end_time - $start_time, 2);
287
288        /* I18N: …from the .ZIP file, %2$s is a (fractional) number of seconds */
289        $alert = I18N::plural('%1$s file was extracted in %2$s seconds.', '%1$s files were extracted in %2$s seconds.', $count, I18N::number($count), $seconds);
290
291        return response(view('components/alert-success', [
292            'alert' => $alert,
293        ]));
294    }
295
296    /**
297     * @param string             $zip_file
298     * @param FilesystemOperator $root_filesystem
299     * @param FilesystemOperator $temporary_filesystem
300     *
301     * @return ResponseInterface
302     */
303    private function wizardStepCopyAndCleanUp(
304        string $zip_file,
305        FilesystemOperator $root_filesystem,
306        FilesystemOperator $temporary_filesystem
307    ): ResponseInterface {
308        $source_filesystem = new Filesystem(new ChrootAdapter($temporary_filesystem, self::ZIP_FILE_PREFIX));
309
310        $this->upgrade_service->startMaintenanceMode();
311        $this->upgrade_service->moveFiles($source_filesystem, $root_filesystem);
312        $this->upgrade_service->endMaintenanceMode();
313
314        // While we have time, clean up any old files.
315        $files_to_keep    = $this->upgrade_service->webtreesZipContents($zip_file);
316        $folders_to_clean = new Collection(self::FOLDERS_TO_CLEAN);
317
318        $this->upgrade_service->cleanFiles($root_filesystem, $folders_to_clean, $files_to_keep);
319
320        $url    = route(ControlPanel::class);
321        $alert  = I18N::translate('The upgrade is complete.');
322        $button = '<a href="' . e($url) . '" class="btn btn-primary">' . I18N::translate('continue') . '</a>';
323
324        return response(view('components/alert-success', [
325            'alert' => $alert . ' ' . $button,
326        ]));
327    }
328}
329