xref: /webtrees/app/Services/UpgradeService.php (revision 36779af1bd0601de7819554b13a393f6edb92507)
10d11ac7eSGreg Roach<?php
23976b470SGreg Roach
30d11ac7eSGreg Roach/**
40d11ac7eSGreg Roach * webtrees: online genealogy
589f7189bSGreg Roach * Copyright (C) 2021 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;
234459dc9aSGreg Roachuse Fisharebest\Webtrees\Carbon;
2481b729d3SGreg Roachuse Fisharebest\Webtrees\Http\Exceptions\HttpServerErrorException;
257def76c7SGreg Roachuse Fisharebest\Webtrees\I18N;
260d11ac7eSGreg Roachuse Fisharebest\Webtrees\Site;
278d0ebef0SGreg Roachuse Fisharebest\Webtrees\Webtrees;
280d11ac7eSGreg Roachuse GuzzleHttp\Client;
294022f21aSGreg Roachuse GuzzleHttp\Exception\GuzzleException;
307def76c7SGreg Roachuse Illuminate\Support\Collection;
317def76c7SGreg Roachuse League\Flysystem\Filesystem;
32f7cf8a15SGreg Roachuse League\Flysystem\FilesystemException;
33f7cf8a15SGreg Roachuse League\Flysystem\FilesystemOperator;
34782714c2SGreg Roachuse League\Flysystem\FilesystemReader;
35f7cf8a15SGreg Roachuse League\Flysystem\StorageAttributes;
36f0448b68SGreg Roachuse League\Flysystem\UnableToDeleteFile;
37f7cf8a15SGreg Roachuse League\Flysystem\ZipArchive\FilesystemZipArchiveProvider;
387def76c7SGreg Roachuse League\Flysystem\ZipArchive\ZipArchiveAdapter;
39783b32e3SGreg Roachuse RuntimeException;
407def76c7SGreg Roachuse ZipArchive;
413976b470SGreg Roach
423551ba8dSGreg Roachuse function explode;
433551ba8dSGreg Roachuse function fclose;
443551ba8dSGreg Roachuse function file_exists;
453551ba8dSGreg Roachuse function file_put_contents;
463551ba8dSGreg Roachuse function fopen;
473551ba8dSGreg Roachuse function ftell;
483551ba8dSGreg Roachuse function fwrite;
49fbb4b472SGreg Roachuse function rewind;
50783b32e3SGreg Roachuse function strlen;
513551ba8dSGreg Roachuse function unlink;
523551ba8dSGreg Roachuse function version_compare;
533551ba8dSGreg Roach
543551ba8dSGreg Roachuse const DIRECTORY_SEPARATOR;
553551ba8dSGreg Roachuse const PHP_VERSION;
560d11ac7eSGreg Roach
570d11ac7eSGreg Roach/**
580d11ac7eSGreg Roach * Automatic upgrades.
590d11ac7eSGreg Roach */
600d11ac7eSGreg Roachclass UpgradeService
610d11ac7eSGreg Roach{
627def76c7SGreg Roach    // Options for fetching files using GuzzleHTTP
637def76c7SGreg Roach    private const GUZZLE_OPTIONS = [
647def76c7SGreg Roach        'connect_timeout' => 25,
657def76c7SGreg Roach        'read_timeout'    => 25,
667def76c7SGreg Roach        'timeout'         => 55,
677def76c7SGreg Roach    ];
687def76c7SGreg Roach
697def76c7SGreg Roach    // Transfer stream data in blocks of this number of bytes.
707def76c7SGreg Roach    private const READ_BLOCK_SIZE = 65535;
717def76c7SGreg Roach
727def76c7SGreg Roach    // Only check the webtrees server once per day.
7316d6367aSGreg Roach    private const CHECK_FOR_UPDATE_INTERVAL = 24 * 60 * 60;
740d11ac7eSGreg Roach
750d11ac7eSGreg Roach    // Fetch information about upgrades from here.
760d11ac7eSGreg Roach    // Note: earlier versions of webtrees used svn.webtrees.net, so we must maintain both URLs.
7716d6367aSGreg Roach    private const UPDATE_URL = 'https://dev.webtrees.net/build/latest-version.txt';
780d11ac7eSGreg Roach
790d11ac7eSGreg Roach    // If the update server doesn't respond after this time, give up.
8016d6367aSGreg Roach    private const HTTP_TIMEOUT = 3.0;
810d11ac7eSGreg Roach
8243f2f523SGreg Roach    private TimeoutService $timeout_service;
837def76c7SGreg Roach
847def76c7SGreg Roach    /**
857def76c7SGreg Roach     * UpgradeService constructor.
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     *
120*36779af1SGreg 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)
130f7cf8a15SGreg Roach            ->filter(static function (StorageAttributes $attributes): bool {
131f7cf8a15SGreg Roach                return $attributes->isFile();
1327def76c7SGreg Roach            })
133f7cf8a15SGreg Roach            ->map(static function (StorageAttributes $attributes): string {
134f7cf8a15SGreg Roach                return $attributes->path();
1357def76c7SGreg Roach            });
136f7cf8a15SGreg Roach
137f7cf8a15SGreg Roach        return new Collection($files);
1387def76c7SGreg Roach    }
1397def76c7SGreg Roach
1407def76c7SGreg Roach    /**
1417def76c7SGreg Roach     * Fetch a file from a URL and save it in a filesystem.
1427def76c7SGreg Roach     * Use streams so that we can copy files larger than our available memory.
1437def76c7SGreg Roach     *
1447def76c7SGreg Roach     * @param string             $url
145f7cf8a15SGreg Roach     * @param FilesystemOperator $filesystem
1467def76c7SGreg Roach     * @param string             $path
1477def76c7SGreg Roach     *
1487def76c7SGreg Roach     * @return int The number of bytes downloaded
1494022f21aSGreg Roach     * @throws GuzzleException
150f0448b68SGreg Roach     * @throws FilesystemException
1517def76c7SGreg Roach     */
152f7cf8a15SGreg Roach    public function downloadFile(string $url, FilesystemOperator $filesystem, string $path): int
1537def76c7SGreg Roach    {
1547def76c7SGreg Roach        // We store the data in PHP temporary storage.
155ea517a3bSGreg Roach        $tmp = fopen('php://memory', 'wb+');
1567def76c7SGreg Roach
1577def76c7SGreg Roach        // Read from the URL
1587def76c7SGreg Roach        $client   = new Client();
1597def76c7SGreg Roach        $response = $client->get($url, self::GUZZLE_OPTIONS);
1607def76c7SGreg Roach        $stream   = $response->getBody();
1617def76c7SGreg Roach
1627def76c7SGreg Roach        // Download the file to temporary storage.
1637def76c7SGreg Roach        while (!$stream->eof()) {
164783b32e3SGreg Roach            $data = $stream->read(self::READ_BLOCK_SIZE);
165783b32e3SGreg Roach
166783b32e3SGreg Roach            $bytes_written = fwrite($tmp, $data);
167783b32e3SGreg Roach
168783b32e3SGreg Roach            if ($bytes_written !== strlen($data)) {
169783b32e3SGreg Roach                throw new RuntimeException('Unable to write to stream.  Perhaps the disk is full?');
170783b32e3SGreg Roach            }
1717def76c7SGreg Roach
172fbb4b472SGreg Roach            if ($this->timeout_service->isTimeNearlyUp()) {
1733551ba8dSGreg Roach                $stream->close();
174d501c45dSGreg Roach                throw new HttpServerErrorException(I18N::translate('The server’s time limit has been reached.'));
1757def76c7SGreg Roach            }
1767def76c7SGreg Roach        }
1777def76c7SGreg Roach
1783551ba8dSGreg Roach        $stream->close();
1797def76c7SGreg Roach
1807def76c7SGreg Roach        // Copy from temporary storage to the file.
181fbb4b472SGreg Roach        $bytes = ftell($tmp);
1827def76c7SGreg Roach        rewind($tmp);
1837def76c7SGreg Roach        $filesystem->writeStream($path, $tmp);
1847def76c7SGreg Roach        fclose($tmp);
1857def76c7SGreg Roach
1867def76c7SGreg Roach        return $bytes;
1877def76c7SGreg Roach    }
1887def76c7SGreg Roach
1897def76c7SGreg Roach    /**
1907def76c7SGreg Roach     * Move (copy and delete) all files from one filesystem to another.
1917def76c7SGreg Roach     *
192f7cf8a15SGreg Roach     * @param FilesystemOperator $source
193f7cf8a15SGreg Roach     * @param FilesystemOperator $destination
19425d7fe95SGreg Roach     *
19525d7fe95SGreg Roach     * @return void
196f7cf8a15SGreg Roach     * @throws FilesystemException
1977def76c7SGreg Roach     */
198f7cf8a15SGreg Roach    public function moveFiles(FilesystemOperator $source, FilesystemOperator $destination): void
19923de9ab7SGreg Roach    {
200782714c2SGreg Roach        foreach ($source->listContents('', FilesystemReader::LIST_DEEP) as $attributes) {
201f7cf8a15SGreg Roach            if ($attributes->isFile()) {
202f7cf8a15SGreg Roach                $destination->write($attributes->path(), $source->read($attributes->path()));
203f7cf8a15SGreg Roach                $source->delete($attributes->path());
2047def76c7SGreg Roach
205fbb4b472SGreg Roach                if ($this->timeout_service->isTimeNearlyUp()) {
206d501c45dSGreg Roach                    throw new HttpServerErrorException(I18N::translate('The server’s time limit has been reached.'));
2077def76c7SGreg Roach                }
2087def76c7SGreg Roach            }
2097def76c7SGreg Roach        }
2107def76c7SGreg Roach    }
2117def76c7SGreg Roach
2120d11ac7eSGreg Roach    /**
213fbb4b472SGreg Roach     * Delete files in $destination that aren't in $source.
214fbb4b472SGreg Roach     *
215f7cf8a15SGreg Roach     * @param FilesystemOperator $filesystem
216*36779af1SGreg Roach     * @param Collection<int,string> $folders_to_clean
217*36779af1SGreg Roach     * @param Collection<int,string> $files_to_keep
21825d7fe95SGreg Roach     *
21925d7fe95SGreg Roach     * @return void
220fbb4b472SGreg Roach     */
221f7cf8a15SGreg Roach    public function cleanFiles(FilesystemOperator $filesystem, Collection $folders_to_clean, Collection $files_to_keep): void
222fbb4b472SGreg Roach    {
223fbb4b472SGreg Roach        foreach ($folders_to_clean as $folder_to_clean) {
224f0448b68SGreg Roach            try {
225782714c2SGreg Roach                foreach ($filesystem->listContents($folder_to_clean, FilesystemReader::LIST_DEEP) as $path) {
226fbb4b472SGreg Roach                    if ($path['type'] === 'file' && !$files_to_keep->contains($path['path'])) {
227f0448b68SGreg Roach                        try {
228fbb4b472SGreg Roach                            $filesystem->delete($path['path']);
229f0448b68SGreg Roach                        } catch (FilesystemException | UnableToDeleteFile $ex) {
230f0448b68SGreg Roach                            // Skip to the next file.
231f0448b68SGreg Roach                        }
232fbb4b472SGreg Roach                    }
233fbb4b472SGreg Roach
234fbb4b472SGreg Roach                    // If we run out of time, then just stop.
235fbb4b472SGreg Roach                    if ($this->timeout_service->isTimeNearlyUp()) {
236fbb4b472SGreg Roach                        return;
237fbb4b472SGreg Roach                    }
238fbb4b472SGreg Roach                }
239f0448b68SGreg Roach            } catch (FilesystemException $ex) {
240f0448b68SGreg Roach                // Skip to the next folder.
241f0448b68SGreg Roach            }
242fbb4b472SGreg Roach        }
243fbb4b472SGreg Roach    }
244fbb4b472SGreg Roach
245fbb4b472SGreg Roach    /**
2460d11ac7eSGreg Roach     * @return bool
2470d11ac7eSGreg Roach     */
2480d11ac7eSGreg Roach    public function isUpgradeAvailable(): bool
2490d11ac7eSGreg Roach    {
2500d11ac7eSGreg Roach        // If the latest version is unavailable, we will have an empty sting which equates to version 0.
2510d11ac7eSGreg Roach
2528d0ebef0SGreg Roach        return version_compare(Webtrees::VERSION, $this->fetchLatestVersion()) < 0;
2530d11ac7eSGreg Roach    }
2540d11ac7eSGreg Roach
2550d11ac7eSGreg Roach    /**
2560d11ac7eSGreg Roach     * What is the latest version of webtrees.
2570d11ac7eSGreg Roach     *
2580d11ac7eSGreg Roach     * @return string
2590d11ac7eSGreg Roach     */
2600d11ac7eSGreg Roach    public function latestVersion(): string
2610d11ac7eSGreg Roach    {
2620d11ac7eSGreg Roach        $latest_version = $this->fetchLatestVersion();
2630d11ac7eSGreg Roach
26465e02381SGreg Roach        [$version] = explode('|', $latest_version);
2650d11ac7eSGreg Roach
2660d11ac7eSGreg Roach        return $version;
2670d11ac7eSGreg Roach    }
2680d11ac7eSGreg Roach
2690d11ac7eSGreg Roach    /**
2700d11ac7eSGreg Roach     * Where can we download the latest version of webtrees.
2710d11ac7eSGreg Roach     *
2720d11ac7eSGreg Roach     * @return string
2730d11ac7eSGreg Roach     */
2740d11ac7eSGreg Roach    public function downloadUrl(): string
2750d11ac7eSGreg Roach    {
2760d11ac7eSGreg Roach        $latest_version = $this->fetchLatestVersion();
2770d11ac7eSGreg Roach
27865e02381SGreg Roach        [, , $url] = explode('|', $latest_version . '||');
2790d11ac7eSGreg Roach
2800d11ac7eSGreg Roach        return $url;
2810d11ac7eSGreg Roach    }
2820d11ac7eSGreg Roach
2837def76c7SGreg Roach    public function startMaintenanceMode(): void
2847def76c7SGreg Roach    {
2857def76c7SGreg Roach        $message = I18N::translate('This website is being upgraded. Try again in a few minutes.');
2867def76c7SGreg Roach
287f397d0fdSGreg Roach        file_put_contents(Webtrees::OFFLINE_FILE, $message);
2887def76c7SGreg Roach    }
2897def76c7SGreg Roach
2907def76c7SGreg Roach    public function endMaintenanceMode(): void
2917def76c7SGreg Roach    {
292f397d0fdSGreg Roach        if (file_exists(Webtrees::OFFLINE_FILE)) {
293f397d0fdSGreg Roach            unlink(Webtrees::OFFLINE_FILE);
2947def76c7SGreg Roach        }
2957def76c7SGreg Roach    }
2967def76c7SGreg Roach
2970d11ac7eSGreg Roach    /**
2980d11ac7eSGreg Roach     * Check with the webtrees.net server for the latest version of webtrees.
2990d11ac7eSGreg Roach     * Fetching the remote file can be slow, so check infrequently, and cache the result.
3000d11ac7eSGreg Roach     * Pass the current versions of webtrees, PHP and MySQL, as the response
3010d11ac7eSGreg Roach     * may be different for each. The server logs are used to generate
302ad3143ccSGreg Roach     * installation statistics which can be found at https://dev.webtrees.net/statistics.html
3030d11ac7eSGreg Roach     *
3040d11ac7eSGreg Roach     * @return string
3050d11ac7eSGreg Roach     */
3060d11ac7eSGreg Roach    private function fetchLatestVersion(): string
3070d11ac7eSGreg Roach    {
3080d11ac7eSGreg Roach        $last_update_timestamp = (int) Site::getPreference('LATEST_WT_VERSION_TIMESTAMP');
3090d11ac7eSGreg Roach
3104459dc9aSGreg Roach        $current_timestamp = Carbon::now()->unix();
311bf57b580SGreg Roach
312bf57b580SGreg Roach        if ($last_update_timestamp < $current_timestamp - self::CHECK_FOR_UPDATE_INTERVAL) {
3130d11ac7eSGreg Roach            try {
3140d11ac7eSGreg Roach                $client = new Client([
3150d11ac7eSGreg Roach                    'timeout' => self::HTTP_TIMEOUT,
3160d11ac7eSGreg Roach                ]);
3170d11ac7eSGreg Roach
3180d11ac7eSGreg Roach                $response = $client->get(self::UPDATE_URL, [
3190d11ac7eSGreg Roach                    'query' => $this->serverParameters(),
3200d11ac7eSGreg Roach                ]);
3210d11ac7eSGreg Roach
3226ccdf4f0SGreg Roach                if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
3230d11ac7eSGreg Roach                    Site::setPreference('LATEST_WT_VERSION', $response->getBody()->getContents());
324bf57b580SGreg Roach                    Site::setPreference('LATEST_WT_VERSION_TIMESTAMP', (string) $current_timestamp);
3250d11ac7eSGreg Roach                }
3264022f21aSGreg Roach            } catch (GuzzleException $ex) {
327c6a0ce5cSGreg Roach                // Can't connect to the server?
328c6a0ce5cSGreg Roach                // Use the existing information about latest versions.
3290d11ac7eSGreg Roach            }
3300d11ac7eSGreg Roach        }
3310d11ac7eSGreg Roach
3320d11ac7eSGreg Roach        return Site::getPreference('LATEST_WT_VERSION');
3330d11ac7eSGreg Roach    }
3340d11ac7eSGreg Roach
3350d11ac7eSGreg Roach    /**
3360d11ac7eSGreg Roach     * The upgrade server needs to know a little about this server.
3375d4b7ec2SGreg Roach     *
3385d4b7ec2SGreg Roach     * @return array<string,string>
3390d11ac7eSGreg Roach     */
3408f53f488SRico Sonntag    private function serverParameters(): array
3410d11ac7eSGreg Roach    {
3420d11ac7eSGreg Roach        $operating_system = DIRECTORY_SEPARATOR === '/' ? 'u' : 'w';
3430d11ac7eSGreg Roach
3440d11ac7eSGreg Roach        return [
3458d0ebef0SGreg Roach            'w' => Webtrees::VERSION,
3460d11ac7eSGreg Roach            'p' => PHP_VERSION,
3470d11ac7eSGreg Roach            'o' => $operating_system,
3480d11ac7eSGreg Roach        ];
3490d11ac7eSGreg Roach    }
3500d11ac7eSGreg Roach}
351