xref: /webtrees/app/Services/UpgradeService.php (revision 211018ab9ab6a5da13d161c40032525dfebcd13f)
10d11ac7eSGreg Roach<?php
23976b470SGreg Roach
30d11ac7eSGreg Roach/**
40d11ac7eSGreg Roach * webtrees: online genealogy
5d11be702SGreg Roach * Copyright (C) 2023 webtrees development team
60d11ac7eSGreg Roach * This program is free software: you can redistribute it and/or modify
70d11ac7eSGreg Roach * it under the terms of the GNU General Public License as published by
80d11ac7eSGreg Roach * the Free Software Foundation, either version 3 of the License, or
90d11ac7eSGreg Roach * (at your option) any later version.
100d11ac7eSGreg Roach * This program is distributed in the hope that it will be useful,
110d11ac7eSGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
120d11ac7eSGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
130d11ac7eSGreg Roach * GNU General Public License for more details.
140d11ac7eSGreg Roach * You should have received a copy of the GNU General Public License
1589f7189bSGreg Roach * along with this program. If not, see <https://www.gnu.org/licenses/>.
160d11ac7eSGreg Roach */
17fcfa147eSGreg Roach
18e7f56f2aSGreg Roachdeclare(strict_types=1);
19e7f56f2aSGreg Roach
200d11ac7eSGreg Roachnamespace Fisharebest\Webtrees\Services;
210d11ac7eSGreg Roach
226ccdf4f0SGreg Roachuse Fig\Http\Message\StatusCodeInterface;
23bfd5083cSGreg Roachuse Fisharebest\Webtrees\Contracts\TimestampInterface;
246f4ec3caSGreg Roachuse Fisharebest\Webtrees\DB;
2581b729d3SGreg Roachuse Fisharebest\Webtrees\Http\Exceptions\HttpServerErrorException;
267def76c7SGreg Roachuse Fisharebest\Webtrees\I18N;
272e464181SGreg Roachuse Fisharebest\Webtrees\Registry;
280d11ac7eSGreg Roachuse Fisharebest\Webtrees\Site;
298d0ebef0SGreg Roachuse Fisharebest\Webtrees\Webtrees;
300d11ac7eSGreg Roachuse GuzzleHttp\Client;
314022f21aSGreg Roachuse GuzzleHttp\Exception\GuzzleException;
327def76c7SGreg Roachuse Illuminate\Support\Collection;
337def76c7SGreg Roachuse League\Flysystem\Filesystem;
34f7cf8a15SGreg Roachuse League\Flysystem\FilesystemException;
35f7cf8a15SGreg Roachuse League\Flysystem\FilesystemOperator;
36782714c2SGreg Roachuse League\Flysystem\FilesystemReader;
37f7cf8a15SGreg Roachuse League\Flysystem\StorageAttributes;
38f0448b68SGreg Roachuse League\Flysystem\UnableToDeleteFile;
39f7cf8a15SGreg Roachuse League\Flysystem\ZipArchive\FilesystemZipArchiveProvider;
407def76c7SGreg Roachuse League\Flysystem\ZipArchive\ZipArchiveAdapter;
41783b32e3SGreg Roachuse RuntimeException;
427def76c7SGreg Roachuse ZipArchive;
433976b470SGreg Roach
443551ba8dSGreg Roachuse function explode;
453551ba8dSGreg Roachuse function fclose;
463551ba8dSGreg Roachuse function file_exists;
473551ba8dSGreg Roachuse function file_put_contents;
483551ba8dSGreg Roachuse function fopen;
493551ba8dSGreg Roachuse function ftell;
503551ba8dSGreg Roachuse function fwrite;
51fbb4b472SGreg Roachuse function rewind;
52783b32e3SGreg Roachuse function strlen;
53d97083feSGreg Roachuse function time;
543551ba8dSGreg Roachuse function unlink;
553551ba8dSGreg Roachuse function version_compare;
563551ba8dSGreg Roach
573551ba8dSGreg Roachuse const PHP_VERSION;
580d11ac7eSGreg Roach
590d11ac7eSGreg Roach/**
600d11ac7eSGreg Roach * Automatic upgrades.
610d11ac7eSGreg Roach */
620d11ac7eSGreg Roachclass UpgradeService
630d11ac7eSGreg Roach{
647def76c7SGreg Roach    // Options for fetching files using GuzzleHTTP
657def76c7SGreg Roach    private const GUZZLE_OPTIONS = [
667def76c7SGreg Roach        'connect_timeout' => 25,
677def76c7SGreg Roach        'read_timeout'    => 25,
687def76c7SGreg Roach        'timeout'         => 55,
697def76c7SGreg Roach    ];
707def76c7SGreg Roach
717def76c7SGreg Roach    // Transfer stream data in blocks of this number of bytes.
727def76c7SGreg Roach    private const READ_BLOCK_SIZE = 65535;
737def76c7SGreg Roach
747def76c7SGreg Roach    // Only check the webtrees server once per day.
7516d6367aSGreg Roach    private const CHECK_FOR_UPDATE_INTERVAL = 24 * 60 * 60;
760d11ac7eSGreg Roach
770d11ac7eSGreg Roach    // Fetch information about upgrades from here.
780d11ac7eSGreg Roach    // Note: earlier versions of webtrees used svn.webtrees.net, so we must maintain both URLs.
7916d6367aSGreg Roach    private const UPDATE_URL = 'https://dev.webtrees.net/build/latest-version.txt';
800d11ac7eSGreg Roach
810d11ac7eSGreg Roach    // If the update server doesn't respond after this time, give up.
8216d6367aSGreg Roach    private const HTTP_TIMEOUT = 3.0;
830d11ac7eSGreg Roach
8443f2f523SGreg Roach    private TimeoutService $timeout_service;
857def76c7SGreg Roach
867def76c7SGreg Roach    /**
877def76c7SGreg Roach     * @param TimeoutService $timeout_service
887def76c7SGreg Roach     */
897def76c7SGreg Roach    public function __construct(TimeoutService $timeout_service)
907def76c7SGreg Roach    {
917def76c7SGreg Roach        $this->timeout_service = $timeout_service;
927def76c7SGreg Roach    }
937def76c7SGreg Roach
947def76c7SGreg Roach    /**
957def76c7SGreg Roach     * Unpack webtrees.zip.
967def76c7SGreg Roach     *
977def76c7SGreg Roach     * @param string $zip_file
987def76c7SGreg Roach     * @param string $target_folder
9925d7fe95SGreg Roach     *
10025d7fe95SGreg Roach     * @return void
1017def76c7SGreg Roach     */
10225d7fe95SGreg Roach    public function extractWebtreesZip(string $zip_file, string $target_folder): void
1037def76c7SGreg Roach    {
1047def76c7SGreg Roach        // The Flysystem ZIP archive adapter is painfully slow, so use the native PHP library.
1057def76c7SGreg Roach        $zip = new ZipArchive();
1067def76c7SGreg Roach
107320f6a24SGreg Roach        if ($zip->open($zip_file) === true) {
1087def76c7SGreg Roach            $zip->extractTo($target_folder);
1097def76c7SGreg Roach            $zip->close();
1107def76c7SGreg Roach        } else {
111d501c45dSGreg Roach            throw new HttpServerErrorException('Cannot read ZIP file. Is it corrupt?');
1127def76c7SGreg Roach        }
1137def76c7SGreg Roach    }
1147def76c7SGreg Roach
1157def76c7SGreg Roach    /**
1167def76c7SGreg Roach     * Create a list of all the files in a webtrees .ZIP archive
1177def76c7SGreg Roach     *
1184db4b4a9SGreg Roach     * @param string $zip_file
1194db4b4a9SGreg Roach     *
12036779af1SGreg Roach     * @return Collection<int,string>
121f7cf8a15SGreg Roach     * @throws FilesystemException
1227def76c7SGreg Roach     */
1234db4b4a9SGreg Roach    public function webtreesZipContents(string $zip_file): Collection
12423de9ab7SGreg Roach    {
125f7cf8a15SGreg Roach        $zip_provider   = new FilesystemZipArchiveProvider($zip_file, 0755);
126f7cf8a15SGreg Roach        $zip_adapter    = new ZipArchiveAdapter($zip_provider, 'webtrees');
127f7cf8a15SGreg Roach        $zip_filesystem = new Filesystem($zip_adapter);
1287def76c7SGreg Roach
129782714c2SGreg Roach        $files = $zip_filesystem->listContents('', FilesystemReader::LIST_DEEP)
130f25fc0f9SGreg Roach            ->filter(static fn (StorageAttributes $attributes): bool => $attributes->isFile())
131f25fc0f9SGreg Roach            ->map(static fn (StorageAttributes $attributes): string => $attributes->path());
132f7cf8a15SGreg Roach
133f7cf8a15SGreg Roach        return new Collection($files);
1347def76c7SGreg Roach    }
1357def76c7SGreg Roach
1367def76c7SGreg Roach    /**
1377def76c7SGreg Roach     * Fetch a file from a URL and save it in a filesystem.
1387def76c7SGreg Roach     * Use streams so that we can copy files larger than our available memory.
1397def76c7SGreg Roach     *
1407def76c7SGreg Roach     * @param string             $url
141f7cf8a15SGreg Roach     * @param FilesystemOperator $filesystem
1427def76c7SGreg Roach     * @param string             $path
1437def76c7SGreg Roach     *
1447def76c7SGreg Roach     * @return int The number of bytes downloaded
1454022f21aSGreg Roach     * @throws GuzzleException
146f0448b68SGreg Roach     * @throws FilesystemException
1477def76c7SGreg Roach     */
148f7cf8a15SGreg Roach    public function downloadFile(string $url, FilesystemOperator $filesystem, string $path): int
1497def76c7SGreg Roach    {
1507def76c7SGreg Roach        // We store the data in PHP temporary storage.
151ea517a3bSGreg Roach        $tmp = fopen('php://memory', 'wb+');
1527def76c7SGreg Roach
1537def76c7SGreg Roach        // Read from the URL
1547def76c7SGreg Roach        $client   = new Client();
1557def76c7SGreg Roach        $response = $client->get($url, self::GUZZLE_OPTIONS);
1567def76c7SGreg Roach        $stream   = $response->getBody();
1577def76c7SGreg Roach
1587def76c7SGreg Roach        // Download the file to temporary storage.
1597def76c7SGreg Roach        while (!$stream->eof()) {
160783b32e3SGreg Roach            $data = $stream->read(self::READ_BLOCK_SIZE);
161783b32e3SGreg Roach
162783b32e3SGreg Roach            $bytes_written = fwrite($tmp, $data);
163783b32e3SGreg Roach
164783b32e3SGreg Roach            if ($bytes_written !== strlen($data)) {
165783b32e3SGreg Roach                throw new RuntimeException('Unable to write to stream.  Perhaps the disk is full?');
166783b32e3SGreg Roach            }
1677def76c7SGreg Roach
168fbb4b472SGreg Roach            if ($this->timeout_service->isTimeNearlyUp()) {
1693551ba8dSGreg Roach                $stream->close();
170d501c45dSGreg Roach                throw new HttpServerErrorException(I18N::translate('The server’s time limit has been reached.'));
1717def76c7SGreg Roach            }
1727def76c7SGreg Roach        }
1737def76c7SGreg Roach
1743551ba8dSGreg Roach        $stream->close();
1757def76c7SGreg Roach
1767def76c7SGreg Roach        // Copy from temporary storage to the file.
177fbb4b472SGreg Roach        $bytes = ftell($tmp);
1787def76c7SGreg Roach        rewind($tmp);
1797def76c7SGreg Roach        $filesystem->writeStream($path, $tmp);
1807def76c7SGreg Roach        fclose($tmp);
1817def76c7SGreg Roach
1827def76c7SGreg Roach        return $bytes;
1837def76c7SGreg Roach    }
1847def76c7SGreg Roach
1857def76c7SGreg Roach    /**
1867def76c7SGreg Roach     * Move (copy and delete) all files from one filesystem to another.
1877def76c7SGreg Roach     *
188f7cf8a15SGreg Roach     * @param FilesystemOperator $source
189f7cf8a15SGreg Roach     * @param FilesystemOperator $destination
19025d7fe95SGreg Roach     *
19125d7fe95SGreg Roach     * @return void
192f7cf8a15SGreg Roach     * @throws FilesystemException
1937def76c7SGreg Roach     */
194f7cf8a15SGreg Roach    public function moveFiles(FilesystemOperator $source, FilesystemOperator $destination): void
19523de9ab7SGreg Roach    {
196782714c2SGreg Roach        foreach ($source->listContents('', FilesystemReader::LIST_DEEP) as $attributes) {
197f7cf8a15SGreg Roach            if ($attributes->isFile()) {
198f7cf8a15SGreg Roach                $destination->write($attributes->path(), $source->read($attributes->path()));
199f7cf8a15SGreg Roach                $source->delete($attributes->path());
2007def76c7SGreg Roach
201fbb4b472SGreg Roach                if ($this->timeout_service->isTimeNearlyUp()) {
202d501c45dSGreg Roach                    throw new HttpServerErrorException(I18N::translate('The server’s time limit has been reached.'));
2037def76c7SGreg Roach                }
2047def76c7SGreg Roach            }
2057def76c7SGreg Roach        }
2067def76c7SGreg Roach    }
2077def76c7SGreg Roach
2080d11ac7eSGreg Roach    /**
209fbb4b472SGreg Roach     * Delete files in $destination that aren't in $source.
210fbb4b472SGreg Roach     *
211f7cf8a15SGreg Roach     * @param FilesystemOperator $filesystem
21236779af1SGreg Roach     * @param Collection<int,string> $folders_to_clean
21336779af1SGreg Roach     * @param Collection<int,string> $files_to_keep
21425d7fe95SGreg Roach     *
21525d7fe95SGreg Roach     * @return void
216fbb4b472SGreg Roach     */
217f7cf8a15SGreg Roach    public function cleanFiles(FilesystemOperator $filesystem, Collection $folders_to_clean, Collection $files_to_keep): void
218fbb4b472SGreg Roach    {
219fbb4b472SGreg Roach        foreach ($folders_to_clean as $folder_to_clean) {
220f0448b68SGreg Roach            try {
221782714c2SGreg Roach                foreach ($filesystem->listContents($folder_to_clean, FilesystemReader::LIST_DEEP) as $path) {
222fbb4b472SGreg Roach                    if ($path['type'] === 'file' && !$files_to_keep->contains($path['path'])) {
223f0448b68SGreg Roach                        try {
224fbb4b472SGreg Roach                            $filesystem->delete($path['path']);
22528d026adSGreg Roach                        } catch (FilesystemException | UnableToDeleteFile) {
226f0448b68SGreg Roach                            // Skip to the next file.
227f0448b68SGreg Roach                        }
228fbb4b472SGreg Roach                    }
229fbb4b472SGreg Roach
230fbb4b472SGreg Roach                    // If we run out of time, then just stop.
231fbb4b472SGreg Roach                    if ($this->timeout_service->isTimeNearlyUp()) {
232fbb4b472SGreg Roach                        return;
233fbb4b472SGreg Roach                    }
234fbb4b472SGreg Roach                }
23528d026adSGreg Roach            } catch (FilesystemException) {
236f0448b68SGreg Roach                // Skip to the next folder.
237f0448b68SGreg Roach            }
238fbb4b472SGreg Roach        }
239fbb4b472SGreg Roach    }
240fbb4b472SGreg Roach
241fbb4b472SGreg Roach    /**
242bfd5083cSGreg Roach     * @param bool $force
243bfd5083cSGreg Roach     *
2440d11ac7eSGreg Roach     * @return bool
2450d11ac7eSGreg Roach     */
246bfd5083cSGreg Roach    public function isUpgradeAvailable(bool $force = false): bool
2470d11ac7eSGreg Roach    {
24823927444SGreg Roach        // If the latest version is unavailable, we will have an empty string which equates to version 0.
2490d11ac7eSGreg Roach
250bfd5083cSGreg Roach        return version_compare(Webtrees::VERSION, $this->fetchLatestVersion($force)) < 0;
2510d11ac7eSGreg Roach    }
2520d11ac7eSGreg Roach
2530d11ac7eSGreg Roach    /**
2540d11ac7eSGreg Roach     * What is the latest version of webtrees.
2550d11ac7eSGreg Roach     *
2560d11ac7eSGreg Roach     * @return string
2570d11ac7eSGreg Roach     */
2580d11ac7eSGreg Roach    public function latestVersion(): string
2590d11ac7eSGreg Roach    {
260bfd5083cSGreg Roach        $latest_version = $this->fetchLatestVersion(false);
2610d11ac7eSGreg Roach
26265e02381SGreg Roach        [$version] = explode('|', $latest_version);
2630d11ac7eSGreg Roach
2640d11ac7eSGreg Roach        return $version;
2650d11ac7eSGreg Roach    }
2660d11ac7eSGreg Roach
2670d11ac7eSGreg Roach    /**
268bfd5083cSGreg Roach     * What, if any, error did we have when fetching the latest version of webtrees.
269bfd5083cSGreg Roach     *
270bfd5083cSGreg Roach     * @return string
271bfd5083cSGreg Roach     */
272bfd5083cSGreg Roach    public function latestVersionError(): string
273bfd5083cSGreg Roach    {
274bfd5083cSGreg Roach        return Site::getPreference('LATEST_WT_VERSION_ERROR');
275bfd5083cSGreg Roach    }
276bfd5083cSGreg Roach
277bfd5083cSGreg Roach    /**
278bfd5083cSGreg Roach     * When did we last try to fetch the latest version of webtrees.
279bfd5083cSGreg Roach     *
280bfd5083cSGreg Roach     * @return TimestampInterface
281bfd5083cSGreg Roach     */
282bfd5083cSGreg Roach    public function latestVersionTimestamp(): TimestampInterface
283bfd5083cSGreg Roach    {
284bfd5083cSGreg Roach        $latest_version_wt_timestamp = (int) Site::getPreference('LATEST_WT_VERSION_TIMESTAMP');
285bfd5083cSGreg Roach
286bfd5083cSGreg Roach        return Registry::timestampFactory()->make($latest_version_wt_timestamp);
287bfd5083cSGreg Roach    }
288bfd5083cSGreg Roach
289bfd5083cSGreg Roach    /**
2900d11ac7eSGreg Roach     * Where can we download the latest version of webtrees.
2910d11ac7eSGreg Roach     *
2920d11ac7eSGreg Roach     * @return string
2930d11ac7eSGreg Roach     */
2940d11ac7eSGreg Roach    public function downloadUrl(): string
2950d11ac7eSGreg Roach    {
296bfd5083cSGreg Roach        $latest_version = $this->fetchLatestVersion(false);
2970d11ac7eSGreg Roach
29865e02381SGreg Roach        [, , $url] = explode('|', $latest_version . '||');
2990d11ac7eSGreg Roach
3000d11ac7eSGreg Roach        return $url;
3010d11ac7eSGreg Roach    }
3020d11ac7eSGreg Roach
30392a78a2fSGreg Roach    /**
30492a78a2fSGreg Roach     * @return void
30592a78a2fSGreg Roach     */
3067def76c7SGreg Roach    public function startMaintenanceMode(): void
3077def76c7SGreg Roach    {
3087def76c7SGreg Roach        $message = I18N::translate('This website is being upgraded. Try again in a few minutes.');
3097def76c7SGreg Roach
310f397d0fdSGreg Roach        file_put_contents(Webtrees::OFFLINE_FILE, $message);
3117def76c7SGreg Roach    }
3127def76c7SGreg Roach
31392a78a2fSGreg Roach    /**
31492a78a2fSGreg Roach     * @return void
31592a78a2fSGreg Roach     */
3167def76c7SGreg Roach    public function endMaintenanceMode(): void
3177def76c7SGreg Roach    {
318f397d0fdSGreg Roach        if (file_exists(Webtrees::OFFLINE_FILE)) {
319f397d0fdSGreg Roach            unlink(Webtrees::OFFLINE_FILE);
3207def76c7SGreg Roach        }
3217def76c7SGreg Roach    }
3227def76c7SGreg Roach
3230d11ac7eSGreg Roach    /**
3240d11ac7eSGreg Roach     * Check with the webtrees.net server for the latest version of webtrees.
3250d11ac7eSGreg Roach     * Fetching the remote file can be slow, so check infrequently, and cache the result.
326bfd5083cSGreg Roach     * Pass the current versions of webtrees, PHP and database, as the response
3270d11ac7eSGreg Roach     * may be different for each. The server logs are used to generate
328ad3143ccSGreg Roach     * installation statistics which can be found at https://dev.webtrees.net/statistics.html
3290d11ac7eSGreg Roach     *
330bfd5083cSGreg Roach     * @param bool $force
331bfd5083cSGreg Roach     *
3320d11ac7eSGreg Roach     * @return string
3330d11ac7eSGreg Roach     */
334bfd5083cSGreg Roach    private function fetchLatestVersion(bool $force): string
3350d11ac7eSGreg Roach    {
3360d11ac7eSGreg Roach        $last_update_timestamp = (int) Site::getPreference('LATEST_WT_VERSION_TIMESTAMP');
3370d11ac7eSGreg Roach
338d97083feSGreg Roach        $current_timestamp = time();
339bf57b580SGreg Roach
340bfd5083cSGreg Roach        if ($force || $last_update_timestamp < $current_timestamp - self::CHECK_FOR_UPDATE_INTERVAL) {
341f260889cSGreg Roach            Site::setPreference('LATEST_WT_VERSION_TIMESTAMP', (string) $current_timestamp);
342f260889cSGreg Roach
3430d11ac7eSGreg Roach            try {
3440d11ac7eSGreg Roach                $client = new Client([
3450d11ac7eSGreg Roach                    'timeout' => self::HTTP_TIMEOUT,
3460d11ac7eSGreg Roach                ]);
3470d11ac7eSGreg Roach
3480d11ac7eSGreg Roach                $response = $client->get(self::UPDATE_URL, [
3490d11ac7eSGreg Roach                    'query' => $this->serverParameters(),
3500d11ac7eSGreg Roach                ]);
3510d11ac7eSGreg Roach
3526ccdf4f0SGreg Roach                if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
3530d11ac7eSGreg Roach                    Site::setPreference('LATEST_WT_VERSION', $response->getBody()->getContents());
354bfd5083cSGreg Roach                    Site::setPreference('LATEST_WT_VERSION_ERROR', '');
355bfd5083cSGreg Roach                } else {
356bfd5083cSGreg Roach                    Site::setPreference('LATEST_WT_VERSION_ERROR', 'HTTP' . $response->getStatusCode());
3570d11ac7eSGreg Roach                }
3584022f21aSGreg Roach            } catch (GuzzleException $ex) {
359c6a0ce5cSGreg Roach                // Can't connect to the server?
360c6a0ce5cSGreg Roach                // Use the existing information about latest versions.
361bfd5083cSGreg Roach                Site::setPreference('LATEST_WT_VERSION_ERROR', $ex->getMessage());
3620d11ac7eSGreg Roach            }
3630d11ac7eSGreg Roach        }
3640d11ac7eSGreg Roach
3650d11ac7eSGreg Roach        return Site::getPreference('LATEST_WT_VERSION');
3660d11ac7eSGreg Roach    }
3670d11ac7eSGreg Roach
3680d11ac7eSGreg Roach    /**
3690d11ac7eSGreg Roach     * The upgrade server needs to know a little about this server.
3705d4b7ec2SGreg Roach     *
3715d4b7ec2SGreg Roach     * @return array<string,string>
3720d11ac7eSGreg Roach     */
3738f53f488SRico Sonntag    private function serverParameters(): array
3740d11ac7eSGreg Roach    {
375c4cbcd7bSGreg Roach        $site_uuid = Site::getPreference('SITE_UUID');
376c4cbcd7bSGreg Roach
377c4cbcd7bSGreg Roach        if ($site_uuid === '') {
3782e464181SGreg Roach            $site_uuid = Registry::idFactory()->uuid();
379c4cbcd7bSGreg Roach            Site::setPreference('SITE_UUID', $site_uuid);
380c4cbcd7bSGreg Roach        }
381c4cbcd7bSGreg Roach
3820d11ac7eSGreg Roach        return [
3838d0ebef0SGreg Roach            'w' => Webtrees::VERSION,
3840d11ac7eSGreg Roach            'p' => PHP_VERSION,
385c4cbcd7bSGreg Roach            's' => $site_uuid,
386*211018abSGreg Roach            'd' => DB::driverName(),
3870d11ac7eSGreg Roach        ];
3880d11ac7eSGreg Roach    }
3890d11ac7eSGreg Roach}
390