1<?php 2/** 3 * webtrees: online genealogy 4 * Copyright (C) 2019 webtrees development team 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * You should have received a copy of the GNU General Public License 14 * along with this program. If not, see <http://www.gnu.org/licenses/>. 15 */ 16declare(strict_types=1); 17 18namespace Fisharebest\Webtrees\Services; 19 20use Fisharebest\Webtrees\Carbon; 21use Fisharebest\Webtrees\Exceptions\InternalServerErrorException; 22use Fisharebest\Webtrees\I18N; 23use Fisharebest\Webtrees\Site; 24use Fisharebest\Webtrees\Webtrees; 25use GuzzleHttp\Client; 26use GuzzleHttp\Exception\RequestException; 27use Illuminate\Support\Collection; 28use League\Flysystem\Cached\CachedAdapter; 29use League\Flysystem\Cached\Storage\Memory; 30use League\Flysystem\Filesystem; 31use League\Flysystem\ZipArchive\ZipArchiveAdapter; 32use Symfony\Component\HttpFoundation\Response; 33use ZipArchive; 34use function rewind; 35 36/** 37 * Automatic upgrades. 38 */ 39class UpgradeService 40{ 41 // Options for fetching files using GuzzleHTTP 42 private const GUZZLE_OPTIONS = [ 43 'connect_timeout' => 25, 44 'read_timeout' => 25, 45 'timeout' => 55, 46 ]; 47 48 // Transfer stream data in blocks of this number of bytes. 49 private const READ_BLOCK_SIZE = 65535; 50 51 // Only check the webtrees server once per day. 52 private const CHECK_FOR_UPDATE_INTERVAL = 24 * 60 * 60; 53 54 // Fetch information about upgrades from here. 55 // Note: earlier versions of webtrees used svn.webtrees.net, so we must maintain both URLs. 56 private const UPDATE_URL = 'https://dev.webtrees.net/build/latest-version.txt'; 57 58 // Create this file to put the site into maintenance mode. 59 private const LOCK_FILE = 'data/offline.txt'; 60 61 // If the update server doesn't respond after this time, give up. 62 private const HTTP_TIMEOUT = 3.0; 63 64 /** @var TimeoutService */ 65 private $timeout_service; 66 67 /** 68 * UpgradeService constructor. 69 * 70 * @param TimeoutService $timeout_service 71 */ 72 public function __construct(TimeoutService $timeout_service) 73 { 74 $this->timeout_service = $timeout_service; 75 } 76 77 /** 78 * Unpack webtrees.zip. 79 * 80 * @param string $zip_file 81 * @param string $target_folder 82 */ 83 public function extractWebtreesZip(string $zip_file, string $target_folder) 84 { 85 // The Flysystem ZIP archive adapter is painfully slow, so use the native PHP library. 86 $zip = new ZipArchive(); 87 88 if ($zip->open($zip_file)) { 89 $zip->extractTo($target_folder); 90 $zip->close(); 91 } else { 92 throw new InternalServerErrorException('Cannot read ZIP file. Is it corrupt?'); 93 } 94 } 95 96 /** 97 * Create a list of all the files in a webtrees .ZIP archive 98 * 99 * @param string $zip_file 100 * 101 * @return Collection 102 */ 103 public function webtreesZipContents(string $zip_file): Collection 104 { 105 $zip_adapter = new ZipArchiveAdapter($zip_file, null, 'webtrees'); 106 $zip_filesystem = new Filesystem(new CachedAdapter($zip_adapter, new Memory())); 107 $paths = new Collection($zip_filesystem->listContents('', true)); 108 109 return $paths->filter(function (array $path): bool { 110 return $path['type'] === 'file'; 111 }) 112 ->map(function (array $path): string { 113 return $path['path']; 114 }); 115 } 116 117 /** 118 * Fetch a file from a URL and save it in a filesystem. 119 * Use streams so that we can copy files larger than our available memory. 120 * 121 * @param string $url 122 * @param Filesystem $filesystem 123 * @param string $path 124 * 125 * @return int The number of bytes downloaded 126 */ 127 public function downloadFile(string $url, Filesystem $filesystem, string $path): int 128 { 129 // Overwrite any previous/partial/failed download. 130 if ($filesystem->has($path)) { 131 $filesystem->delete($path); 132 } 133 134 // We store the data in PHP temporary storage. 135 $tmp = fopen('php://temp', 'w+'); 136 137 // Read from the URL 138 $client = new Client(); 139 $response = $client->get($url, self::GUZZLE_OPTIONS); 140 $stream = $response->getBody(); 141 142 // Download the file to temporary storage. 143 while (!$stream->eof()) { 144 fwrite($tmp, $stream->read(self::READ_BLOCK_SIZE)); 145 146 if ($this->timeout_service->isTimeNearlyUp()) { 147 throw new InternalServerErrorException(I18N::translate('The server’s time limit has been reached.')); 148 } 149 } 150 151 if (is_resource($stream)) { 152 fclose($stream); 153 } 154 155 // Copy from temporary storage to the file. 156 $bytes = ftell($tmp); 157 rewind($tmp); 158 $filesystem->writeStream($path, $tmp); 159 fclose($tmp); 160 161 return $bytes; 162 } 163 164 /** 165 * Move (copy and delete) all files from one filesystem to another. 166 * 167 * @param Filesystem $source 168 * @param Filesystem $destination 169 */ 170 public function moveFiles(Filesystem $source, Filesystem $destination) 171 { 172 foreach ($source->listContents() as $path) { 173 if ($path['type'] === 'file') { 174 $destination->put($path['path'], $source->read($path['path'])); 175 $source->delete($path['path']); 176 177 if ($this->timeout_service->isTimeNearlyUp()) { 178 throw new InternalServerErrorException(I18N::translate('The server’s time limit has been reached.')); 179 } 180 } 181 } 182 } 183 184 /** 185 * Delete files in $destination that aren't in $source. 186 * 187 * @param Filesystem $filesystem 188 * @param Collection $folders_to_clean 189 * @param Collection $files_to_keep 190 */ 191 public function cleanFiles(Filesystem $filesystem, Collection $folders_to_clean, Collection $files_to_keep) 192 { 193 foreach ($folders_to_clean as $folder_to_clean) { 194 foreach ($filesystem->listContents($folder_to_clean, true) as $path) { 195 if ($path['type'] === 'file' && !$files_to_keep->contains($path['path'])) { 196 $filesystem->delete($path['path']); 197 } 198 199 // If we run out of time, then just stop. 200 if ($this->timeout_service->isTimeNearlyUp()) { 201 return; 202 } 203 } 204 } 205 } 206 207 /** 208 * @return bool 209 */ 210 public function isUpgradeAvailable(): bool 211 { 212 // If the latest version is unavailable, we will have an empty sting which equates to version 0. 213 214 return version_compare(Webtrees::VERSION, $this->fetchLatestVersion()) < 0; 215 } 216 217 /** 218 * What is the latest version of webtrees. 219 * 220 * @return string 221 */ 222 public function latestVersion(): string 223 { 224 $latest_version = $this->fetchLatestVersion(); 225 226 [$version] = explode('|', $latest_version); 227 228 return $version; 229 } 230 231 /** 232 * Where can we download the latest version of webtrees. 233 * 234 * @return string 235 */ 236 public function downloadUrl(): string 237 { 238 $latest_version = $this->fetchLatestVersion(); 239 240 [, , $url] = explode('|', $latest_version . '||'); 241 242 return $url; 243 } 244 245 public function startMaintenanceMode(): void 246 { 247 $message = I18N::translate('This website is being upgraded. Try again in a few minutes.'); 248 249 file_put_contents(WT_ROOT . self::LOCK_FILE, $message); 250 } 251 252 public function endMaintenanceMode(): void 253 { 254 if (file_exists(WT_ROOT . self::LOCK_FILE)) { 255 unlink(WT_ROOT . self::LOCK_FILE); 256 } 257 } 258 259 /** 260 * Check with the webtrees.net server for the latest version of webtrees. 261 * Fetching the remote file can be slow, so check infrequently, and cache the result. 262 * Pass the current versions of webtrees, PHP and MySQL, as the response 263 * may be different for each. The server logs are used to generate 264 * installation statistics which can be found at http://dev.webtrees.net/statistics.html 265 * 266 * @return string 267 */ 268 private function fetchLatestVersion(): string 269 { 270 $last_update_timestamp = (int) Site::getPreference('LATEST_WT_VERSION_TIMESTAMP'); 271 272 $current_timestamp = Carbon::now()->unix(); 273 274 if ($last_update_timestamp < $current_timestamp - self::CHECK_FOR_UPDATE_INTERVAL) { 275 try { 276 $client = new Client([ 277 'timeout' => self::HTTP_TIMEOUT, 278 ]); 279 280 $response = $client->get(self::UPDATE_URL, [ 281 'query' => $this->serverParameters(), 282 ]); 283 284 if ($response->getStatusCode() === Response::HTTP_OK) { 285 Site::setPreference('LATEST_WT_VERSION', $response->getBody()->getContents()); 286 Site::setPreference('LATEST_WT_VERSION_TIMESTAMP', (string) $current_timestamp); 287 } 288 } catch (RequestException $ex) { 289 // Can't connect to the server? 290 // Use the existing information about latest versions. 291 } 292 } 293 294 return Site::getPreference('LATEST_WT_VERSION'); 295 } 296 297 /** 298 * The upgrade server needs to know a little about this server. 299 */ 300 private function serverParameters(): array 301 { 302 $operating_system = DIRECTORY_SEPARATOR === '/' ? 'u' : 'w'; 303 304 return [ 305 'w' => Webtrees::VERSION, 306 'p' => PHP_VERSION, 307 'o' => $operating_system, 308 ]; 309 } 310} 311