1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2023 webtrees development team 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License as published by 8 * the Free Software Foundation, either version 3 of the License, or 9 * (at your option) any later version. 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <https://www.gnu.org/licenses/>. 16 */ 17 18declare(strict_types=1); 19 20namespace Fisharebest\Webtrees\Services; 21 22use Fig\Http\Message\StatusCodeInterface; 23use Fisharebest\Webtrees\Contracts\TimestampInterface; 24use Fisharebest\Webtrees\DB; 25use Fisharebest\Webtrees\Http\Exceptions\HttpServerErrorException; 26use Fisharebest\Webtrees\I18N; 27use Fisharebest\Webtrees\Registry; 28use Fisharebest\Webtrees\Site; 29use Fisharebest\Webtrees\Webtrees; 30use GuzzleHttp\Client; 31use GuzzleHttp\Exception\GuzzleException; 32use Illuminate\Support\Collection; 33use League\Flysystem\Filesystem; 34use League\Flysystem\FilesystemException; 35use League\Flysystem\FilesystemOperator; 36use League\Flysystem\FilesystemReader; 37use League\Flysystem\StorageAttributes; 38use League\Flysystem\UnableToDeleteFile; 39use League\Flysystem\ZipArchive\FilesystemZipArchiveProvider; 40use League\Flysystem\ZipArchive\ZipArchiveAdapter; 41use RuntimeException; 42use ZipArchive; 43 44use function explode; 45use function fclose; 46use function file_exists; 47use function file_put_contents; 48use function fopen; 49use function ftell; 50use function fwrite; 51use function rewind; 52use function strlen; 53use function time; 54use function unlink; 55use function version_compare; 56 57use const PHP_VERSION; 58 59/** 60 * Automatic upgrades. 61 */ 62class UpgradeService 63{ 64 // Options for fetching files using GuzzleHTTP 65 private const GUZZLE_OPTIONS = [ 66 'connect_timeout' => 25, 67 'read_timeout' => 25, 68 'timeout' => 55, 69 ]; 70 71 // Transfer stream data in blocks of this number of bytes. 72 private const READ_BLOCK_SIZE = 65535; 73 74 // Only check the webtrees server once per day. 75 private const CHECK_FOR_UPDATE_INTERVAL = 24 * 60 * 60; 76 77 // Fetch information about upgrades from here. 78 // Note: earlier versions of webtrees used svn.webtrees.net, so we must maintain both URLs. 79 private const UPDATE_URL = 'https://dev.webtrees.net/build/latest-version.txt'; 80 81 // If the update server doesn't respond after this time, give up. 82 private const HTTP_TIMEOUT = 3.0; 83 84 private TimeoutService $timeout_service; 85 86 /** 87 * @param TimeoutService $timeout_service 88 */ 89 public function __construct(TimeoutService $timeout_service) 90 { 91 $this->timeout_service = $timeout_service; 92 } 93 94 /** 95 * Unpack webtrees.zip. 96 * 97 * @param string $zip_file 98 * @param string $target_folder 99 * 100 * @return void 101 */ 102 public function extractWebtreesZip(string $zip_file, string $target_folder): void 103 { 104 // The Flysystem ZIP archive adapter is painfully slow, so use the native PHP library. 105 $zip = new ZipArchive(); 106 107 if ($zip->open($zip_file) === true) { 108 $zip->extractTo($target_folder); 109 $zip->close(); 110 } else { 111 throw new HttpServerErrorException('Cannot read ZIP file. Is it corrupt?'); 112 } 113 } 114 115 /** 116 * Create a list of all the files in a webtrees .ZIP archive 117 * 118 * @param string $zip_file 119 * 120 * @return Collection<int,string> 121 * @throws FilesystemException 122 */ 123 public function webtreesZipContents(string $zip_file): Collection 124 { 125 $zip_provider = new FilesystemZipArchiveProvider($zip_file, 0755); 126 $zip_adapter = new ZipArchiveAdapter($zip_provider, 'webtrees'); 127 $zip_filesystem = new Filesystem($zip_adapter); 128 129 $files = $zip_filesystem->listContents('', FilesystemReader::LIST_DEEP) 130 ->filter(static function (StorageAttributes $attributes): bool { 131 return $attributes->isFile(); 132 }) 133 ->map(static function (StorageAttributes $attributes): string { 134 return $attributes->path(); 135 }); 136 137 return new Collection($files); 138 } 139 140 /** 141 * Fetch a file from a URL and save it in a filesystem. 142 * Use streams so that we can copy files larger than our available memory. 143 * 144 * @param string $url 145 * @param FilesystemOperator $filesystem 146 * @param string $path 147 * 148 * @return int The number of bytes downloaded 149 * @throws GuzzleException 150 * @throws FilesystemException 151 */ 152 public function downloadFile(string $url, FilesystemOperator $filesystem, string $path): int 153 { 154 // We store the data in PHP temporary storage. 155 $tmp = fopen('php://memory', 'wb+'); 156 157 // Read from the URL 158 $client = new Client(); 159 $response = $client->get($url, self::GUZZLE_OPTIONS); 160 $stream = $response->getBody(); 161 162 // Download the file to temporary storage. 163 while (!$stream->eof()) { 164 $data = $stream->read(self::READ_BLOCK_SIZE); 165 166 $bytes_written = fwrite($tmp, $data); 167 168 if ($bytes_written !== strlen($data)) { 169 throw new RuntimeException('Unable to write to stream. Perhaps the disk is full?'); 170 } 171 172 if ($this->timeout_service->isTimeNearlyUp()) { 173 $stream->close(); 174 throw new HttpServerErrorException(I18N::translate('The server’s time limit has been reached.')); 175 } 176 } 177 178 $stream->close(); 179 180 // Copy from temporary storage to the file. 181 $bytes = ftell($tmp); 182 rewind($tmp); 183 $filesystem->writeStream($path, $tmp); 184 fclose($tmp); 185 186 return $bytes; 187 } 188 189 /** 190 * Move (copy and delete) all files from one filesystem to another. 191 * 192 * @param FilesystemOperator $source 193 * @param FilesystemOperator $destination 194 * 195 * @return void 196 * @throws FilesystemException 197 */ 198 public function moveFiles(FilesystemOperator $source, FilesystemOperator $destination): void 199 { 200 foreach ($source->listContents('', FilesystemReader::LIST_DEEP) as $attributes) { 201 if ($attributes->isFile()) { 202 $destination->write($attributes->path(), $source->read($attributes->path())); 203 $source->delete($attributes->path()); 204 205 if ($this->timeout_service->isTimeNearlyUp()) { 206 throw new HttpServerErrorException(I18N::translate('The server’s time limit has been reached.')); 207 } 208 } 209 } 210 } 211 212 /** 213 * Delete files in $destination that aren't in $source. 214 * 215 * @param FilesystemOperator $filesystem 216 * @param Collection<int,string> $folders_to_clean 217 * @param Collection<int,string> $files_to_keep 218 * 219 * @return void 220 */ 221 public function cleanFiles(FilesystemOperator $filesystem, Collection $folders_to_clean, Collection $files_to_keep): void 222 { 223 foreach ($folders_to_clean as $folder_to_clean) { 224 try { 225 foreach ($filesystem->listContents($folder_to_clean, FilesystemReader::LIST_DEEP) as $path) { 226 if ($path['type'] === 'file' && !$files_to_keep->contains($path['path'])) { 227 try { 228 $filesystem->delete($path['path']); 229 } catch (FilesystemException | UnableToDeleteFile) { 230 // Skip to the next file. 231 } 232 } 233 234 // If we run out of time, then just stop. 235 if ($this->timeout_service->isTimeNearlyUp()) { 236 return; 237 } 238 } 239 } catch (FilesystemException) { 240 // Skip to the next folder. 241 } 242 } 243 } 244 245 /** 246 * @param bool $force 247 * 248 * @return bool 249 */ 250 public function isUpgradeAvailable(bool $force = false): bool 251 { 252 // If the latest version is unavailable, we will have an empty string which equates to version 0. 253 254 return version_compare(Webtrees::VERSION, $this->fetchLatestVersion($force)) < 0; 255 } 256 257 /** 258 * What is the latest version of webtrees. 259 * 260 * @return string 261 */ 262 public function latestVersion(): string 263 { 264 $latest_version = $this->fetchLatestVersion(false); 265 266 [$version] = explode('|', $latest_version); 267 268 return $version; 269 } 270 271 /** 272 * What, if any, error did we have when fetching the latest version of webtrees. 273 * 274 * @return string 275 */ 276 public function latestVersionError(): string 277 { 278 return Site::getPreference('LATEST_WT_VERSION_ERROR'); 279 } 280 281 /** 282 * When did we last try to fetch the latest version of webtrees. 283 * 284 * @return TimestampInterface 285 */ 286 public function latestVersionTimestamp(): TimestampInterface 287 { 288 $latest_version_wt_timestamp = (int) Site::getPreference('LATEST_WT_VERSION_TIMESTAMP'); 289 290 return Registry::timestampFactory()->make($latest_version_wt_timestamp); 291 } 292 293 /** 294 * Where can we download the latest version of webtrees. 295 * 296 * @return string 297 */ 298 public function downloadUrl(): string 299 { 300 $latest_version = $this->fetchLatestVersion(false); 301 302 [, , $url] = explode('|', $latest_version . '||'); 303 304 return $url; 305 } 306 307 /** 308 * @return void 309 */ 310 public function startMaintenanceMode(): void 311 { 312 $message = I18N::translate('This website is being upgraded. Try again in a few minutes.'); 313 314 file_put_contents(Webtrees::OFFLINE_FILE, $message); 315 } 316 317 /** 318 * @return void 319 */ 320 public function endMaintenanceMode(): void 321 { 322 if (file_exists(Webtrees::OFFLINE_FILE)) { 323 unlink(Webtrees::OFFLINE_FILE); 324 } 325 } 326 327 /** 328 * Check with the webtrees.net server for the latest version of webtrees. 329 * Fetching the remote file can be slow, so check infrequently, and cache the result. 330 * Pass the current versions of webtrees, PHP and database, as the response 331 * may be different for each. The server logs are used to generate 332 * installation statistics which can be found at https://dev.webtrees.net/statistics.html 333 * 334 * @param bool $force 335 * 336 * @return string 337 */ 338 private function fetchLatestVersion(bool $force): string 339 { 340 $last_update_timestamp = (int) Site::getPreference('LATEST_WT_VERSION_TIMESTAMP'); 341 342 $current_timestamp = time(); 343 344 if ($force || $last_update_timestamp < $current_timestamp - self::CHECK_FOR_UPDATE_INTERVAL) { 345 Site::setPreference('LATEST_WT_VERSION_TIMESTAMP', (string) $current_timestamp); 346 347 try { 348 $client = new Client([ 349 'timeout' => self::HTTP_TIMEOUT, 350 ]); 351 352 $response = $client->get(self::UPDATE_URL, [ 353 'query' => $this->serverParameters(), 354 ]); 355 356 if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) { 357 Site::setPreference('LATEST_WT_VERSION', $response->getBody()->getContents()); 358 Site::setPreference('LATEST_WT_VERSION_ERROR', ''); 359 } else { 360 Site::setPreference('LATEST_WT_VERSION_ERROR', 'HTTP' . $response->getStatusCode()); 361 } 362 } catch (GuzzleException $ex) { 363 // Can't connect to the server? 364 // Use the existing information about latest versions. 365 Site::setPreference('LATEST_WT_VERSION_ERROR', $ex->getMessage()); 366 } 367 } 368 369 return Site::getPreference('LATEST_WT_VERSION'); 370 } 371 372 /** 373 * The upgrade server needs to know a little about this server. 374 * 375 * @return array<string,string> 376 */ 377 private function serverParameters(): array 378 { 379 $site_uuid = Site::getPreference('SITE_UUID'); 380 381 if ($site_uuid === '') { 382 $site_uuid = Registry::idFactory()->uuid(); 383 Site::setPreference('SITE_UUID', $site_uuid); 384 } 385 386 $database_type = DB::connection()->getDriverName(); 387 388 return [ 389 'w' => Webtrees::VERSION, 390 'p' => PHP_VERSION, 391 's' => $site_uuid, 392 'd' => $database_type, 393 ]; 394 } 395} 396