xref: /webtrees/app/Services/UpgradeService.php (revision ac71572d8462e396ed5a307f05b29381e49f9e6e)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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\Services;
21
22use Fig\Http\Message\StatusCodeInterface;
23use Fisharebest\Webtrees\Http\Exceptions\HttpServerErrorException;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Log;
26use Fisharebest\Webtrees\Registry;
27use Fisharebest\Webtrees\Site;
28use Fisharebest\Webtrees\Webtrees;
29use GuzzleHttp\Client;
30use GuzzleHttp\Exception\GuzzleException;
31use Illuminate\Database\Capsule\Manager as DB;
32use Illuminate\Support\Collection;
33use League\Flysystem\Filesystem;
34use League\Flysystem\FilesystemException;
35use League\Flysystem\FilesystemOperator;
36use League\Flysystem\FilesystemReader;
37use League\Flysystem\StorageAttributes;
38use League\Flysystem\UnableToDeleteFile;
39use League\Flysystem\ZipArchive\FilesystemZipArchiveProvider;
40use League\Flysystem\ZipArchive\ZipArchiveAdapter;
41use RuntimeException;
42use ZipArchive;
43
44use function explode;
45use function fclose;
46use function file_exists;
47use function file_put_contents;
48use function fopen;
49use function ftell;
50use function fwrite;
51use function rewind;
52use function strlen;
53use function time;
54use function unlink;
55use function version_compare;
56
57use const PHP_VERSION;
58
59/**
60 * Automatic upgrades.
61 */
62class UpgradeService
63{
64    // Options for fetching files using GuzzleHTTP
65    private const GUZZLE_OPTIONS = [
66        'connect_timeout' => 25,
67        'read_timeout'    => 25,
68        'timeout'         => 55,
69    ];
70
71    // Transfer stream data in blocks of this number of bytes.
72    private const READ_BLOCK_SIZE = 65535;
73
74    // Only check the webtrees server once per day.
75    private const CHECK_FOR_UPDATE_INTERVAL = 24 * 60 * 60;
76
77    // Fetch information about upgrades from here.
78    // Note: earlier versions of webtrees used svn.webtrees.net, so we must maintain both URLs.
79    private const UPDATE_URL = 'https://dev.webtrees.net/build/latest-version.txt';
80
81    // If the update server doesn't respond after this time, give up.
82    private const HTTP_TIMEOUT = 3.0;
83
84    private TimeoutService $timeout_service;
85
86    /**
87     * UpgradeService constructor.
88     *
89     * @param TimeoutService $timeout_service
90     */
91    public function __construct(TimeoutService $timeout_service)
92    {
93        $this->timeout_service = $timeout_service;
94    }
95
96    /**
97     * Unpack webtrees.zip.
98     *
99     * @param string $zip_file
100     * @param string $target_folder
101     *
102     * @return void
103     */
104    public function extractWebtreesZip(string $zip_file, string $target_folder): void
105    {
106        // The Flysystem ZIP archive adapter is painfully slow, so use the native PHP library.
107        $zip = new ZipArchive();
108
109        if ($zip->open($zip_file) === true) {
110            $zip->extractTo($target_folder);
111            $zip->close();
112        } else {
113            throw new HttpServerErrorException('Cannot read ZIP file. Is it corrupt?');
114        }
115    }
116
117    /**
118     * Create a list of all the files in a webtrees .ZIP archive
119     *
120     * @param string $zip_file
121     *
122     * @return Collection<int,string>
123     * @throws FilesystemException
124     */
125    public function webtreesZipContents(string $zip_file): Collection
126    {
127        $zip_provider   = new FilesystemZipArchiveProvider($zip_file, 0755);
128        $zip_adapter    = new ZipArchiveAdapter($zip_provider, 'webtrees');
129        $zip_filesystem = new Filesystem($zip_adapter);
130
131        $files = $zip_filesystem->listContents('', FilesystemReader::LIST_DEEP)
132            ->filter(static function (StorageAttributes $attributes): bool {
133                return $attributes->isFile();
134            })
135            ->map(static function (StorageAttributes $attributes): string {
136                return $attributes->path();
137            });
138
139        return new Collection($files);
140    }
141
142    /**
143     * Fetch a file from a URL and save it in a filesystem.
144     * Use streams so that we can copy files larger than our available memory.
145     *
146     * @param string             $url
147     * @param FilesystemOperator $filesystem
148     * @param string             $path
149     *
150     * @return int The number of bytes downloaded
151     * @throws GuzzleException
152     * @throws FilesystemException
153     */
154    public function downloadFile(string $url, FilesystemOperator $filesystem, string $path): int
155    {
156        // We store the data in PHP temporary storage.
157        $tmp = fopen('php://memory', 'wb+');
158
159        // Read from the URL
160        $client   = new Client();
161        $response = $client->get($url, self::GUZZLE_OPTIONS);
162        $stream   = $response->getBody();
163
164        // Download the file to temporary storage.
165        while (!$stream->eof()) {
166            $data = $stream->read(self::READ_BLOCK_SIZE);
167
168            $bytes_written = fwrite($tmp, $data);
169
170            if ($bytes_written !== strlen($data)) {
171                throw new RuntimeException('Unable to write to stream.  Perhaps the disk is full?');
172            }
173
174            if ($this->timeout_service->isTimeNearlyUp()) {
175                $stream->close();
176                throw new HttpServerErrorException(I18N::translate('The server’s time limit has been reached.'));
177            }
178        }
179
180        $stream->close();
181
182        // Copy from temporary storage to the file.
183        $bytes = ftell($tmp);
184        rewind($tmp);
185        $filesystem->writeStream($path, $tmp);
186        fclose($tmp);
187
188        return $bytes;
189    }
190
191    /**
192     * Move (copy and delete) all files from one filesystem to another.
193     *
194     * @param FilesystemOperator $source
195     * @param FilesystemOperator $destination
196     *
197     * @return void
198     * @throws FilesystemException
199     */
200    public function moveFiles(FilesystemOperator $source, FilesystemOperator $destination): void
201    {
202        foreach ($source->listContents('', FilesystemReader::LIST_DEEP) as $attributes) {
203            if ($attributes->isFile()) {
204                $destination->write($attributes->path(), $source->read($attributes->path()));
205                $source->delete($attributes->path());
206
207                if ($this->timeout_service->isTimeNearlyUp()) {
208                    throw new HttpServerErrorException(I18N::translate('The server’s time limit has been reached.'));
209                }
210            }
211        }
212    }
213
214    /**
215     * Delete files in $destination that aren't in $source.
216     *
217     * @param FilesystemOperator $filesystem
218     * @param Collection<int,string> $folders_to_clean
219     * @param Collection<int,string> $files_to_keep
220     *
221     * @return void
222     */
223    public function cleanFiles(FilesystemOperator $filesystem, Collection $folders_to_clean, Collection $files_to_keep): void
224    {
225        foreach ($folders_to_clean as $folder_to_clean) {
226            try {
227                foreach ($filesystem->listContents($folder_to_clean, FilesystemReader::LIST_DEEP) as $path) {
228                    if ($path['type'] === 'file' && !$files_to_keep->contains($path['path'])) {
229                        try {
230                            $filesystem->delete($path['path']);
231                        } catch (FilesystemException | UnableToDeleteFile $ex) {
232                            // Skip to the next file.
233                        }
234                    }
235
236                    // If we run out of time, then just stop.
237                    if ($this->timeout_service->isTimeNearlyUp()) {
238                        return;
239                    }
240                }
241            } catch (FilesystemException $ex) {
242                // Skip to the next folder.
243            }
244        }
245    }
246
247    /**
248     * @return bool
249     */
250    public function isUpgradeAvailable(): bool
251    {
252        // If the latest version is unavailable, we will have an empty string which equates to version 0.
253
254        return version_compare(Webtrees::VERSION, $this->fetchLatestVersion()) < 0;
255    }
256
257    /**
258     * What is the latest version of webtrees.
259     *
260     * @return string
261     */
262    public function latestVersion(): string
263    {
264        $latest_version = $this->fetchLatestVersion();
265
266        [$version] = explode('|', $latest_version);
267
268        return $version;
269    }
270
271    /**
272     * Where can we download the latest version of webtrees.
273     *
274     * @return string
275     */
276    public function downloadUrl(): string
277    {
278        $latest_version = $this->fetchLatestVersion();
279
280        [, , $url] = explode('|', $latest_version . '||');
281
282        return $url;
283    }
284
285    /**
286     * @return void
287     */
288    public function startMaintenanceMode(): void
289    {
290        $message = I18N::translate('This website is being upgraded. Try again in a few minutes.');
291
292        file_put_contents(Webtrees::OFFLINE_FILE, $message);
293    }
294
295    /**
296     * @return void
297     */
298    public function endMaintenanceMode(): void
299    {
300        if (file_exists(Webtrees::OFFLINE_FILE)) {
301            unlink(Webtrees::OFFLINE_FILE);
302        }
303    }
304
305    /**
306     * Check with the webtrees.net server for the latest version of webtrees.
307     * Fetching the remote file can be slow, so check infrequently, and cache the result.
308     * Pass the current versions of webtrees, PHP and MySQL, as the response
309     * may be different for each. The server logs are used to generate
310     * installation statistics which can be found at https://dev.webtrees.net/statistics.html
311     *
312     * @return string
313     */
314    private function fetchLatestVersion(): string
315    {
316        $last_update_timestamp = (int) Site::getPreference('LATEST_WT_VERSION_TIMESTAMP');
317
318        $current_timestamp = time();
319
320        if ($last_update_timestamp < $current_timestamp - self::CHECK_FOR_UPDATE_INTERVAL) {
321            try {
322                $client = new Client([
323                    'timeout' => self::HTTP_TIMEOUT,
324                ]);
325
326                $response = $client->get(self::UPDATE_URL, [
327                    'query' => $this->serverParameters(),
328                ]);
329
330                if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
331                    Site::setPreference('LATEST_WT_VERSION', $response->getBody()->getContents());
332                    Site::setPreference('LATEST_WT_VERSION_TIMESTAMP', (string) $current_timestamp);
333                }
334            } catch (GuzzleException $ex) {
335                // Can't connect to the server?
336                // Use the existing information about latest versions.
337                Log::addErrorLog('Cannot fetch latest webtrees version. ' . $ex->getMessage());
338            }
339        }
340
341        return Site::getPreference('LATEST_WT_VERSION');
342    }
343
344    /**
345     * The upgrade server needs to know a little about this server.
346     *
347     * @return array<string,string>
348     */
349    private function serverParameters(): array
350    {
351        $site_uuid = Site::getPreference('SITE_UUID');
352
353        if ($site_uuid === '') {
354            $site_uuid = Registry::idFactory()->uuid();
355            Site::setPreference('SITE_UUID', $site_uuid);
356        }
357
358        $database_type = DB::connection()->getDriverName();
359
360        return [
361            'w' => Webtrees::VERSION,
362            'p' => PHP_VERSION,
363            's' => $site_uuid,
364            'd' => $database_type,
365        ];
366    }
367}
368