xref: /webtrees/app/Services/UpgradeService.php (revision e364afe4ae4e316fc4ebd53eccbaff2d29e419a5)
10d11ac7eSGreg Roach<?php
20d11ac7eSGreg Roach/**
30d11ac7eSGreg Roach * webtrees: online genealogy
48fcd0d32SGreg Roach * Copyright (C) 2019 webtrees development team
50d11ac7eSGreg Roach * This program is free software: you can redistribute it and/or modify
60d11ac7eSGreg Roach * it under the terms of the GNU General Public License as published by
70d11ac7eSGreg Roach * the Free Software Foundation, either version 3 of the License, or
80d11ac7eSGreg Roach * (at your option) any later version.
90d11ac7eSGreg Roach * This program is distributed in the hope that it will be useful,
100d11ac7eSGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
110d11ac7eSGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
120d11ac7eSGreg Roach * GNU General Public License for more details.
130d11ac7eSGreg Roach * You should have received a copy of the GNU General Public License
140d11ac7eSGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
150d11ac7eSGreg Roach */
16e7f56f2aSGreg Roachdeclare(strict_types=1);
17e7f56f2aSGreg Roach
180d11ac7eSGreg Roachnamespace Fisharebest\Webtrees\Services;
190d11ac7eSGreg Roach
204459dc9aSGreg Roachuse Fisharebest\Webtrees\Carbon;
217def76c7SGreg Roachuse Fisharebest\Webtrees\Exceptions\InternalServerErrorException;
227def76c7SGreg Roachuse Fisharebest\Webtrees\I18N;
230d11ac7eSGreg Roachuse Fisharebest\Webtrees\Site;
248d0ebef0SGreg Roachuse Fisharebest\Webtrees\Webtrees;
250d11ac7eSGreg Roachuse GuzzleHttp\Client;
260d11ac7eSGreg Roachuse GuzzleHttp\Exception\RequestException;
277def76c7SGreg Roachuse Illuminate\Support\Collection;
287def76c7SGreg Roachuse League\Flysystem\Cached\CachedAdapter;
297def76c7SGreg Roachuse League\Flysystem\Cached\Storage\Memory;
307def76c7SGreg Roachuse League\Flysystem\Filesystem;
317def76c7SGreg Roachuse League\Flysystem\ZipArchive\ZipArchiveAdapter;
320d11ac7eSGreg Roachuse Symfony\Component\HttpFoundation\Response;
337def76c7SGreg Roachuse ZipArchive;
34fbb4b472SGreg Roachuse function rewind;
350d11ac7eSGreg Roach
360d11ac7eSGreg Roach/**
370d11ac7eSGreg Roach * Automatic upgrades.
380d11ac7eSGreg Roach */
390d11ac7eSGreg Roachclass UpgradeService
400d11ac7eSGreg Roach{
417def76c7SGreg Roach    // Options for fetching files using GuzzleHTTP
427def76c7SGreg Roach    private const GUZZLE_OPTIONS = [
437def76c7SGreg Roach        'connect_timeout' => 25,
447def76c7SGreg Roach        'read_timeout'    => 25,
457def76c7SGreg Roach        'timeout'         => 55,
467def76c7SGreg Roach    ];
477def76c7SGreg Roach
487def76c7SGreg Roach    // Transfer stream data in blocks of this number of bytes.
497def76c7SGreg Roach    private const READ_BLOCK_SIZE = 65535;
507def76c7SGreg Roach
517def76c7SGreg Roach    // Only check the webtrees server once per day.
5216d6367aSGreg Roach    private const CHECK_FOR_UPDATE_INTERVAL = 24 * 60 * 60;
530d11ac7eSGreg Roach
540d11ac7eSGreg Roach    // Fetch information about upgrades from here.
550d11ac7eSGreg Roach    // Note: earlier versions of webtrees used svn.webtrees.net, so we must maintain both URLs.
5616d6367aSGreg Roach    private const UPDATE_URL = 'https://dev.webtrees.net/build/latest-version.txt';
570d11ac7eSGreg Roach
587def76c7SGreg Roach    // Create this file to put the site into maintenance mode.
597def76c7SGreg Roach    private const LOCK_FILE = 'data/offline.txt';
607def76c7SGreg Roach
610d11ac7eSGreg Roach    // If the update server doesn't respond after this time, give up.
6216d6367aSGreg Roach    private const HTTP_TIMEOUT = 3.0;
630d11ac7eSGreg Roach
647def76c7SGreg Roach    /** @var TimeoutService */
657def76c7SGreg Roach    private $timeout_service;
667def76c7SGreg Roach
677def76c7SGreg Roach    /**
687def76c7SGreg Roach     * UpgradeService constructor.
697def76c7SGreg Roach     *
707def76c7SGreg Roach     * @param TimeoutService $timeout_service
717def76c7SGreg Roach     */
727def76c7SGreg Roach    public function __construct(TimeoutService $timeout_service)
737def76c7SGreg Roach    {
747def76c7SGreg Roach        $this->timeout_service = $timeout_service;
757def76c7SGreg Roach    }
767def76c7SGreg Roach
777def76c7SGreg Roach    /**
787def76c7SGreg Roach     * Unpack webtrees.zip.
797def76c7SGreg Roach     *
807def76c7SGreg Roach     * @param string $zip_file
817def76c7SGreg Roach     * @param string $target_folder
8225d7fe95SGreg Roach     *
8325d7fe95SGreg Roach     * @return void
847def76c7SGreg Roach     */
8525d7fe95SGreg Roach    public function extractWebtreesZip(string $zip_file, string $target_folder): void
867def76c7SGreg Roach    {
877def76c7SGreg Roach        // The Flysystem ZIP archive adapter is painfully slow, so use the native PHP library.
887def76c7SGreg Roach        $zip = new ZipArchive();
897def76c7SGreg Roach
907def76c7SGreg Roach        if ($zip->open($zip_file)) {
917def76c7SGreg Roach            $zip->extractTo($target_folder);
927def76c7SGreg Roach            $zip->close();
937def76c7SGreg Roach        } else {
947def76c7SGreg Roach            throw new InternalServerErrorException('Cannot read ZIP file. Is it corrupt?');
957def76c7SGreg Roach        }
967def76c7SGreg Roach    }
977def76c7SGreg Roach
987def76c7SGreg Roach    /**
997def76c7SGreg Roach     * Create a list of all the files in a webtrees .ZIP archive
1007def76c7SGreg Roach     *
1014db4b4a9SGreg Roach     * @param string $zip_file
1024db4b4a9SGreg Roach     *
1037def76c7SGreg Roach     * @return Collection
1047def76c7SGreg Roach     */
1054db4b4a9SGreg Roach    public function webtreesZipContents(string $zip_file): Collection
10623de9ab7SGreg Roach    {
1077def76c7SGreg Roach        $zip_adapter    = new ZipArchiveAdapter($zip_file, null, 'webtrees');
1087def76c7SGreg Roach        $zip_filesystem = new Filesystem(new CachedAdapter($zip_adapter, new Memory()));
1097def76c7SGreg Roach        $paths          = new Collection($zip_filesystem->listContents('', true));
1107def76c7SGreg Roach
1117def76c7SGreg Roach        return $paths->filter(function (array $path): bool {
1127def76c7SGreg Roach            return $path['type'] === 'file';
1137def76c7SGreg Roach        })
1147def76c7SGreg Roach            ->map(function (array $path): string {
1157def76c7SGreg Roach                return $path['path'];
1167def76c7SGreg Roach            });
1177def76c7SGreg Roach    }
1187def76c7SGreg Roach
1197def76c7SGreg Roach    /**
1207def76c7SGreg Roach     * Fetch a file from a URL and save it in a filesystem.
1217def76c7SGreg Roach     * Use streams so that we can copy files larger than our available memory.
1227def76c7SGreg Roach     *
1237def76c7SGreg Roach     * @param string     $url
1247def76c7SGreg Roach     * @param Filesystem $filesystem
1257def76c7SGreg Roach     * @param string     $path
1267def76c7SGreg Roach     *
1277def76c7SGreg Roach     * @return int The number of bytes downloaded
1287def76c7SGreg Roach     */
1297def76c7SGreg Roach    public function downloadFile(string $url, Filesystem $filesystem, string $path): int
1307def76c7SGreg Roach    {
1317def76c7SGreg Roach        // Overwrite any previous/partial/failed download.
1327def76c7SGreg Roach        if ($filesystem->has($path)) {
1337def76c7SGreg Roach            $filesystem->delete($path);
1347def76c7SGreg Roach        }
1357def76c7SGreg Roach
1367def76c7SGreg Roach        // We store the data in PHP temporary storage.
137*e364afe4SGreg Roach        $tmp = fopen('php://temp', 'wb+');
1387def76c7SGreg Roach
1397def76c7SGreg Roach        // Read from the URL
1407def76c7SGreg Roach        $client   = new Client();
1417def76c7SGreg Roach        $response = $client->get($url, self::GUZZLE_OPTIONS);
1427def76c7SGreg Roach        $stream   = $response->getBody();
1437def76c7SGreg Roach
1447def76c7SGreg Roach        // Download the file to temporary storage.
1457def76c7SGreg Roach        while (!$stream->eof()) {
1467def76c7SGreg Roach            fwrite($tmp, $stream->read(self::READ_BLOCK_SIZE));
1477def76c7SGreg Roach
148fbb4b472SGreg Roach            if ($this->timeout_service->isTimeNearlyUp()) {
1497def76c7SGreg Roach                throw new InternalServerErrorException(I18N::translate('The server’s time limit has been reached.'));
1507def76c7SGreg Roach            }
1517def76c7SGreg Roach        }
1527def76c7SGreg Roach
1537def76c7SGreg Roach        if (is_resource($stream)) {
1547def76c7SGreg Roach            fclose($stream);
1557def76c7SGreg Roach        }
1567def76c7SGreg Roach
1577def76c7SGreg Roach        // Copy from temporary storage to the file.
158fbb4b472SGreg Roach        $bytes = ftell($tmp);
1597def76c7SGreg Roach        rewind($tmp);
1607def76c7SGreg Roach        $filesystem->writeStream($path, $tmp);
1617def76c7SGreg Roach        fclose($tmp);
1627def76c7SGreg Roach
1637def76c7SGreg Roach        return $bytes;
1647def76c7SGreg Roach    }
1657def76c7SGreg Roach
1667def76c7SGreg Roach    /**
1677def76c7SGreg Roach     * Move (copy and delete) all files from one filesystem to another.
1687def76c7SGreg Roach     *
1697def76c7SGreg Roach     * @param Filesystem $source
1707def76c7SGreg Roach     * @param Filesystem $destination
17125d7fe95SGreg Roach     *
17225d7fe95SGreg Roach     * @return void
1737def76c7SGreg Roach     */
17425d7fe95SGreg Roach    public function moveFiles(Filesystem $source, Filesystem $destination): void
17523de9ab7SGreg Roach    {
1767def76c7SGreg Roach        foreach ($source->listContents() as $path) {
1777def76c7SGreg Roach            if ($path['type'] === 'file') {
1787def76c7SGreg Roach                $destination->put($path['path'], $source->read($path['path']));
1797def76c7SGreg Roach                $source->delete($path['path']);
1807def76c7SGreg Roach
181fbb4b472SGreg Roach                if ($this->timeout_service->isTimeNearlyUp()) {
1827def76c7SGreg Roach                    throw new InternalServerErrorException(I18N::translate('The server’s time limit has been reached.'));
1837def76c7SGreg Roach                }
1847def76c7SGreg Roach            }
1857def76c7SGreg Roach        }
1867def76c7SGreg Roach    }
1877def76c7SGreg Roach
1880d11ac7eSGreg Roach    /**
189fbb4b472SGreg Roach     * Delete files in $destination that aren't in $source.
190fbb4b472SGreg Roach     *
191fbb4b472SGreg Roach     * @param Filesystem $filesystem
192fbb4b472SGreg Roach     * @param Collection $folders_to_clean
193fbb4b472SGreg Roach     * @param Collection   $files_to_keep
19425d7fe95SGreg Roach     *
19525d7fe95SGreg Roach     * @return void
196fbb4b472SGreg Roach     */
19725d7fe95SGreg Roach    public function cleanFiles(Filesystem $filesystem, Collection $folders_to_clean, Collection $files_to_keep): void
198fbb4b472SGreg Roach    {
199fbb4b472SGreg Roach        foreach ($folders_to_clean as $folder_to_clean) {
200fbb4b472SGreg Roach            foreach ($filesystem->listContents($folder_to_clean, true) as $path) {
201fbb4b472SGreg Roach                if ($path['type'] === 'file' && !$files_to_keep->contains($path['path'])) {
202fbb4b472SGreg Roach                    $filesystem->delete($path['path']);
203fbb4b472SGreg Roach                }
204fbb4b472SGreg Roach
205fbb4b472SGreg Roach                // If we run out of time, then just stop.
206fbb4b472SGreg Roach                if ($this->timeout_service->isTimeNearlyUp()) {
207fbb4b472SGreg Roach                    return;
208fbb4b472SGreg Roach                }
209fbb4b472SGreg Roach            }
210fbb4b472SGreg Roach        }
211fbb4b472SGreg Roach    }
212fbb4b472SGreg Roach
213fbb4b472SGreg Roach    /**
2140d11ac7eSGreg Roach     * @return bool
2150d11ac7eSGreg Roach     */
2160d11ac7eSGreg Roach    public function isUpgradeAvailable(): bool
2170d11ac7eSGreg Roach    {
2180d11ac7eSGreg Roach        // If the latest version is unavailable, we will have an empty sting which equates to version 0.
2190d11ac7eSGreg Roach
2208d0ebef0SGreg Roach        return version_compare(Webtrees::VERSION, $this->fetchLatestVersion()) < 0;
2210d11ac7eSGreg Roach    }
2220d11ac7eSGreg Roach
2230d11ac7eSGreg Roach    /**
2240d11ac7eSGreg Roach     * What is the latest version of webtrees.
2250d11ac7eSGreg Roach     *
2260d11ac7eSGreg Roach     * @return string
2270d11ac7eSGreg Roach     */
2280d11ac7eSGreg Roach    public function latestVersion(): string
2290d11ac7eSGreg Roach    {
2300d11ac7eSGreg Roach        $latest_version = $this->fetchLatestVersion();
2310d11ac7eSGreg Roach
23265e02381SGreg Roach        [$version] = explode('|', $latest_version);
2330d11ac7eSGreg Roach
2340d11ac7eSGreg Roach        return $version;
2350d11ac7eSGreg Roach    }
2360d11ac7eSGreg Roach
2370d11ac7eSGreg Roach    /**
2380d11ac7eSGreg Roach     * Where can we download the latest version of webtrees.
2390d11ac7eSGreg Roach     *
2400d11ac7eSGreg Roach     * @return string
2410d11ac7eSGreg Roach     */
2420d11ac7eSGreg Roach    public function downloadUrl(): string
2430d11ac7eSGreg Roach    {
2440d11ac7eSGreg Roach        $latest_version = $this->fetchLatestVersion();
2450d11ac7eSGreg Roach
24665e02381SGreg Roach        [, , $url] = explode('|', $latest_version . '||');
2470d11ac7eSGreg Roach
2480d11ac7eSGreg Roach        return $url;
2490d11ac7eSGreg Roach    }
2500d11ac7eSGreg Roach
2517def76c7SGreg Roach    public function startMaintenanceMode(): void
2527def76c7SGreg Roach    {
2537def76c7SGreg Roach        $message = I18N::translate('This website is being upgraded. Try again in a few minutes.');
2547def76c7SGreg Roach
2557def76c7SGreg Roach        file_put_contents(WT_ROOT . self::LOCK_FILE, $message);
2567def76c7SGreg Roach    }
2577def76c7SGreg Roach
2587def76c7SGreg Roach    public function endMaintenanceMode(): void
2597def76c7SGreg Roach    {
2607def76c7SGreg Roach        if (file_exists(WT_ROOT . self::LOCK_FILE)) {
2617def76c7SGreg Roach            unlink(WT_ROOT . self::LOCK_FILE);
2627def76c7SGreg Roach        }
2637def76c7SGreg Roach    }
2647def76c7SGreg Roach
2650d11ac7eSGreg Roach    /**
2660d11ac7eSGreg Roach     * Check with the webtrees.net server for the latest version of webtrees.
2670d11ac7eSGreg Roach     * Fetching the remote file can be slow, so check infrequently, and cache the result.
2680d11ac7eSGreg Roach     * Pass the current versions of webtrees, PHP and MySQL, as the response
2690d11ac7eSGreg Roach     * may be different for each. The server logs are used to generate
2700d11ac7eSGreg Roach     * installation statistics which can be found at http://dev.webtrees.net/statistics.html
2710d11ac7eSGreg Roach     *
2720d11ac7eSGreg Roach     * @return string
2730d11ac7eSGreg Roach     */
2740d11ac7eSGreg Roach    private function fetchLatestVersion(): string
2750d11ac7eSGreg Roach    {
2760d11ac7eSGreg Roach        $last_update_timestamp = (int) Site::getPreference('LATEST_WT_VERSION_TIMESTAMP');
2770d11ac7eSGreg Roach
2784459dc9aSGreg Roach        $current_timestamp = Carbon::now()->unix();
279bf57b580SGreg Roach
280bf57b580SGreg Roach        if ($last_update_timestamp < $current_timestamp - self::CHECK_FOR_UPDATE_INTERVAL) {
2810d11ac7eSGreg Roach            try {
2820d11ac7eSGreg Roach                $client = new Client([
2830d11ac7eSGreg Roach                    'timeout' => self::HTTP_TIMEOUT,
2840d11ac7eSGreg Roach                ]);
2850d11ac7eSGreg Roach
2860d11ac7eSGreg Roach                $response = $client->get(self::UPDATE_URL, [
2870d11ac7eSGreg Roach                    'query' => $this->serverParameters(),
2880d11ac7eSGreg Roach                ]);
2890d11ac7eSGreg Roach
2900d11ac7eSGreg Roach                if ($response->getStatusCode() === Response::HTTP_OK) {
2910d11ac7eSGreg Roach                    Site::setPreference('LATEST_WT_VERSION', $response->getBody()->getContents());
292bf57b580SGreg Roach                    Site::setPreference('LATEST_WT_VERSION_TIMESTAMP', (string) $current_timestamp);
2930d11ac7eSGreg Roach                }
2940d11ac7eSGreg Roach            } catch (RequestException $ex) {
295c6a0ce5cSGreg Roach                // Can't connect to the server?
296c6a0ce5cSGreg Roach                // Use the existing information about latest versions.
2970d11ac7eSGreg Roach            }
2980d11ac7eSGreg Roach        }
2990d11ac7eSGreg Roach
3000d11ac7eSGreg Roach        return Site::getPreference('LATEST_WT_VERSION');
3010d11ac7eSGreg Roach    }
3020d11ac7eSGreg Roach
3030d11ac7eSGreg Roach    /**
3040d11ac7eSGreg Roach     * The upgrade server needs to know a little about this server.
3050d11ac7eSGreg Roach     */
3068f53f488SRico Sonntag    private function serverParameters(): array
3070d11ac7eSGreg Roach    {
3080d11ac7eSGreg Roach        $operating_system = DIRECTORY_SEPARATOR === '/' ? 'u' : 'w';
3090d11ac7eSGreg Roach
3100d11ac7eSGreg Roach        return [
3118d0ebef0SGreg Roach            'w' => Webtrees::VERSION,
3120d11ac7eSGreg Roach            'p' => PHP_VERSION,
3130d11ac7eSGreg Roach            'o' => $operating_system,
3140d11ac7eSGreg Roach        ];
3150d11ac7eSGreg Roach    }
3160d11ac7eSGreg Roach}
317