xref: /webtrees/app/Services/UpgradeService.php (revision 4459dc9a6d0c27769f8135175f3569e4fa287451)
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
20*4459dc9aSGreg 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
827def76c7SGreg Roach     */
837def76c7SGreg Roach    public function extractWebtreesZip(string $zip_file, string $target_folder)
847def76c7SGreg Roach    {
857def76c7SGreg Roach        // The Flysystem ZIP archive adapter is painfully slow, so use the native PHP library.
867def76c7SGreg Roach        $zip = new ZipArchive();
877def76c7SGreg Roach
887def76c7SGreg Roach        if ($zip->open($zip_file)) {
897def76c7SGreg Roach            $zip->extractTo($target_folder);
907def76c7SGreg Roach            $zip->close();
917def76c7SGreg Roach        } else {
927def76c7SGreg Roach            throw new InternalServerErrorException('Cannot read ZIP file. Is it corrupt?');
937def76c7SGreg Roach        }
947def76c7SGreg Roach    }
957def76c7SGreg Roach
967def76c7SGreg Roach    /**
977def76c7SGreg Roach     * Create a list of all the files in a webtrees .ZIP archive
987def76c7SGreg Roach     *
994db4b4a9SGreg Roach     * @param string $zip_file
1004db4b4a9SGreg Roach     *
1017def76c7SGreg Roach     * @return Collection
1027def76c7SGreg Roach     */
1034db4b4a9SGreg Roach    public function webtreesZipContents(string $zip_file): Collection
10423de9ab7SGreg Roach    {
1057def76c7SGreg Roach        $zip_adapter    = new ZipArchiveAdapter($zip_file, null, 'webtrees');
1067def76c7SGreg Roach        $zip_filesystem = new Filesystem(new CachedAdapter($zip_adapter, new Memory()));
1077def76c7SGreg Roach        $paths          = new Collection($zip_filesystem->listContents('', true));
1087def76c7SGreg Roach
1097def76c7SGreg Roach        return $paths->filter(function (array $path): bool {
1107def76c7SGreg Roach            return $path['type'] === 'file';
1117def76c7SGreg Roach        })
1127def76c7SGreg Roach            ->map(function (array $path): string {
1137def76c7SGreg Roach                return $path['path'];
1147def76c7SGreg Roach            });
1157def76c7SGreg Roach    }
1167def76c7SGreg Roach
1177def76c7SGreg Roach    /**
1187def76c7SGreg Roach     * Fetch a file from a URL and save it in a filesystem.
1197def76c7SGreg Roach     * Use streams so that we can copy files larger than our available memory.
1207def76c7SGreg Roach     *
1217def76c7SGreg Roach     * @param string     $url
1227def76c7SGreg Roach     * @param Filesystem $filesystem
1237def76c7SGreg Roach     * @param string     $path
1247def76c7SGreg Roach     *
1257def76c7SGreg Roach     * @return int The number of bytes downloaded
1267def76c7SGreg Roach     */
1277def76c7SGreg Roach    public function downloadFile(string $url, Filesystem $filesystem, string $path): int
1287def76c7SGreg Roach    {
1297def76c7SGreg Roach        // Overwrite any previous/partial/failed download.
1307def76c7SGreg Roach        if ($filesystem->has($path)) {
1317def76c7SGreg Roach            $filesystem->delete($path);
1327def76c7SGreg Roach        }
1337def76c7SGreg Roach
1347def76c7SGreg Roach        // We store the data in PHP temporary storage.
1357def76c7SGreg Roach        $tmp = fopen('php://temp', 'w+');
1367def76c7SGreg Roach
1377def76c7SGreg Roach        // Read from the URL
1387def76c7SGreg Roach        $client   = new Client();
1397def76c7SGreg Roach        $response = $client->get($url, self::GUZZLE_OPTIONS);
1407def76c7SGreg Roach        $stream   = $response->getBody();
1417def76c7SGreg Roach
1427def76c7SGreg Roach        // Download the file to temporary storage.
1437def76c7SGreg Roach        while (!$stream->eof()) {
1447def76c7SGreg Roach            fwrite($tmp, $stream->read(self::READ_BLOCK_SIZE));
1457def76c7SGreg Roach
146fbb4b472SGreg Roach            if ($this->timeout_service->isTimeNearlyUp()) {
1477def76c7SGreg Roach                throw new InternalServerErrorException(I18N::translate('The server’s time limit has been reached.'));
1487def76c7SGreg Roach            }
1497def76c7SGreg Roach        }
1507def76c7SGreg Roach
1517def76c7SGreg Roach        if (is_resource($stream)) {
1527def76c7SGreg Roach            fclose($stream);
1537def76c7SGreg Roach        }
1547def76c7SGreg Roach
1557def76c7SGreg Roach        // Copy from temporary storage to the file.
156fbb4b472SGreg Roach        $bytes = ftell($tmp);
1577def76c7SGreg Roach        rewind($tmp);
1587def76c7SGreg Roach        $filesystem->writeStream($path, $tmp);
1597def76c7SGreg Roach        fclose($tmp);
1607def76c7SGreg Roach
1617def76c7SGreg Roach        return $bytes;
1627def76c7SGreg Roach    }
1637def76c7SGreg Roach
1647def76c7SGreg Roach    /**
1657def76c7SGreg Roach     * Move (copy and delete) all files from one filesystem to another.
1667def76c7SGreg Roach     *
1677def76c7SGreg Roach     * @param Filesystem $source
1687def76c7SGreg Roach     * @param Filesystem $destination
1697def76c7SGreg Roach     */
17023de9ab7SGreg Roach    public function moveFiles(Filesystem $source, Filesystem $destination)
17123de9ab7SGreg Roach    {
1727def76c7SGreg Roach        foreach ($source->listContents() as $path) {
1737def76c7SGreg Roach            if ($path['type'] === 'file') {
1747def76c7SGreg Roach                $destination->put($path['path'], $source->read($path['path']));
1757def76c7SGreg Roach                $source->delete($path['path']);
1767def76c7SGreg Roach
177fbb4b472SGreg Roach                if ($this->timeout_service->isTimeNearlyUp()) {
1787def76c7SGreg Roach                    throw new InternalServerErrorException(I18N::translate('The server’s time limit has been reached.'));
1797def76c7SGreg Roach                }
1807def76c7SGreg Roach            }
1817def76c7SGreg Roach        }
1827def76c7SGreg Roach    }
1837def76c7SGreg Roach
1840d11ac7eSGreg Roach    /**
185fbb4b472SGreg Roach     * Delete files in $destination that aren't in $source.
186fbb4b472SGreg Roach     *
187fbb4b472SGreg Roach     * @param Filesystem $filesystem
188fbb4b472SGreg Roach     * @param Collection $folders_to_clean
189fbb4b472SGreg Roach     * @param Collection   $files_to_keep
190fbb4b472SGreg Roach     */
191fbb4b472SGreg Roach    public function cleanFiles(Filesystem $filesystem, Collection $folders_to_clean, Collection $files_to_keep)
192fbb4b472SGreg Roach    {
193fbb4b472SGreg Roach        foreach ($folders_to_clean as $folder_to_clean) {
194fbb4b472SGreg Roach            foreach ($filesystem->listContents($folder_to_clean, true) as $path) {
195fbb4b472SGreg Roach                if ($path['type'] === 'file' && !$files_to_keep->contains($path['path'])) {
196fbb4b472SGreg Roach                    $filesystem->delete($path['path']);
197fbb4b472SGreg Roach                }
198fbb4b472SGreg Roach
199fbb4b472SGreg Roach                // If we run out of time, then just stop.
200fbb4b472SGreg Roach                if ($this->timeout_service->isTimeNearlyUp()) {
201fbb4b472SGreg Roach                    return;
202fbb4b472SGreg Roach                }
203fbb4b472SGreg Roach            }
204fbb4b472SGreg Roach        }
205fbb4b472SGreg Roach    }
206fbb4b472SGreg Roach
207fbb4b472SGreg Roach    /**
2080d11ac7eSGreg Roach     * @return bool
2090d11ac7eSGreg Roach     */
2100d11ac7eSGreg Roach    public function isUpgradeAvailable(): bool
2110d11ac7eSGreg Roach    {
2120d11ac7eSGreg Roach        // If the latest version is unavailable, we will have an empty sting which equates to version 0.
2130d11ac7eSGreg Roach
2148d0ebef0SGreg Roach        return version_compare(Webtrees::VERSION, $this->fetchLatestVersion()) < 0;
2150d11ac7eSGreg Roach    }
2160d11ac7eSGreg Roach
2170d11ac7eSGreg Roach    /**
2180d11ac7eSGreg Roach     * What is the latest version of webtrees.
2190d11ac7eSGreg Roach     *
2200d11ac7eSGreg Roach     * @return string
2210d11ac7eSGreg Roach     */
2220d11ac7eSGreg Roach    public function latestVersion(): string
2230d11ac7eSGreg Roach    {
2240d11ac7eSGreg Roach        $latest_version = $this->fetchLatestVersion();
2250d11ac7eSGreg Roach
22665e02381SGreg Roach        [$version] = explode('|', $latest_version);
2270d11ac7eSGreg Roach
2280d11ac7eSGreg Roach        return $version;
2290d11ac7eSGreg Roach    }
2300d11ac7eSGreg Roach
2310d11ac7eSGreg Roach    /**
2320d11ac7eSGreg Roach     * Where can we download the latest version of webtrees.
2330d11ac7eSGreg Roach     *
2340d11ac7eSGreg Roach     * @return string
2350d11ac7eSGreg Roach     */
2360d11ac7eSGreg Roach    public function downloadUrl(): string
2370d11ac7eSGreg Roach    {
2380d11ac7eSGreg Roach        $latest_version = $this->fetchLatestVersion();
2390d11ac7eSGreg Roach
24065e02381SGreg Roach        [, , $url] = explode('|', $latest_version . '||');
2410d11ac7eSGreg Roach
2420d11ac7eSGreg Roach        return $url;
2430d11ac7eSGreg Roach    }
2440d11ac7eSGreg Roach
2457def76c7SGreg Roach    public function startMaintenanceMode(): void
2467def76c7SGreg Roach    {
2477def76c7SGreg Roach        $message = I18N::translate('This website is being upgraded. Try again in a few minutes.');
2487def76c7SGreg Roach
2497def76c7SGreg Roach        file_put_contents(WT_ROOT . self::LOCK_FILE, $message);
2507def76c7SGreg Roach    }
2517def76c7SGreg Roach
2527def76c7SGreg Roach    public function endMaintenanceMode(): void
2537def76c7SGreg Roach    {
2547def76c7SGreg Roach        if (file_exists(WT_ROOT . self::LOCK_FILE)) {
2557def76c7SGreg Roach            unlink(WT_ROOT . self::LOCK_FILE);
2567def76c7SGreg Roach        }
2577def76c7SGreg Roach    }
2587def76c7SGreg Roach
2590d11ac7eSGreg Roach    /**
2600d11ac7eSGreg Roach     * Check with the webtrees.net server for the latest version of webtrees.
2610d11ac7eSGreg Roach     * Fetching the remote file can be slow, so check infrequently, and cache the result.
2620d11ac7eSGreg Roach     * Pass the current versions of webtrees, PHP and MySQL, as the response
2630d11ac7eSGreg Roach     * may be different for each. The server logs are used to generate
2640d11ac7eSGreg Roach     * installation statistics which can be found at http://dev.webtrees.net/statistics.html
2650d11ac7eSGreg Roach     *
2660d11ac7eSGreg Roach     * @return string
2670d11ac7eSGreg Roach     */
2680d11ac7eSGreg Roach    private function fetchLatestVersion(): string
2690d11ac7eSGreg Roach    {
2700d11ac7eSGreg Roach        $last_update_timestamp = (int) Site::getPreference('LATEST_WT_VERSION_TIMESTAMP');
2710d11ac7eSGreg Roach
272*4459dc9aSGreg Roach        $current_timestamp = Carbon::now()->unix();
273bf57b580SGreg Roach
274bf57b580SGreg Roach        if ($last_update_timestamp < $current_timestamp - self::CHECK_FOR_UPDATE_INTERVAL) {
2750d11ac7eSGreg Roach            try {
2760d11ac7eSGreg Roach                $client = new Client([
2770d11ac7eSGreg Roach                    'timeout' => self::HTTP_TIMEOUT,
2780d11ac7eSGreg Roach                ]);
2790d11ac7eSGreg Roach
2800d11ac7eSGreg Roach                $response = $client->get(self::UPDATE_URL, [
2810d11ac7eSGreg Roach                    'query' => $this->serverParameters(),
2820d11ac7eSGreg Roach                ]);
2830d11ac7eSGreg Roach
2840d11ac7eSGreg Roach                if ($response->getStatusCode() === Response::HTTP_OK) {
2850d11ac7eSGreg Roach                    Site::setPreference('LATEST_WT_VERSION', $response->getBody()->getContents());
286bf57b580SGreg Roach                    Site::setPreference('LATEST_WT_VERSION_TIMESTAMP', (string) $current_timestamp);
2870d11ac7eSGreg Roach                }
2880d11ac7eSGreg Roach            } catch (RequestException $ex) {
289c6a0ce5cSGreg Roach                // Can't connect to the server?
290c6a0ce5cSGreg Roach                // Use the existing information about latest versions.
2910d11ac7eSGreg Roach            }
2920d11ac7eSGreg Roach        }
2930d11ac7eSGreg Roach
2940d11ac7eSGreg Roach        return Site::getPreference('LATEST_WT_VERSION');
2950d11ac7eSGreg Roach    }
2960d11ac7eSGreg Roach
2970d11ac7eSGreg Roach    /**
2980d11ac7eSGreg Roach     * The upgrade server needs to know a little about this server.
2990d11ac7eSGreg Roach     */
3008f53f488SRico Sonntag    private function serverParameters(): array
3010d11ac7eSGreg Roach    {
3020d11ac7eSGreg Roach        $operating_system = DIRECTORY_SEPARATOR === '/' ? 'u' : 'w';
3030d11ac7eSGreg Roach
3040d11ac7eSGreg Roach        return [
3058d0ebef0SGreg Roach            'w' => Webtrees::VERSION,
3060d11ac7eSGreg Roach            'p' => PHP_VERSION,
3070d11ac7eSGreg Roach            'o' => $operating_system,
3080d11ac7eSGreg Roach        ];
3090d11ac7eSGreg Roach    }
3100d11ac7eSGreg Roach}
311