1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2022 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\Http\Exceptions\HttpServerErrorException; 24use Fisharebest\Webtrees\I18N; 25use Fisharebest\Webtrees\Site; 26use Fisharebest\Webtrees\Webtrees; 27use GuzzleHttp\Client; 28use GuzzleHttp\Exception\GuzzleException; 29use Illuminate\Support\Collection; 30use League\Flysystem\Filesystem; 31use League\Flysystem\FilesystemException; 32use League\Flysystem\FilesystemOperator; 33use League\Flysystem\FilesystemReader; 34use League\Flysystem\StorageAttributes; 35use League\Flysystem\UnableToDeleteFile; 36use League\Flysystem\ZipArchive\FilesystemZipArchiveProvider; 37use League\Flysystem\ZipArchive\ZipArchiveAdapter; 38use RuntimeException; 39use ZipArchive; 40 41use function explode; 42use function fclose; 43use function file_exists; 44use function file_put_contents; 45use function fopen; 46use function ftell; 47use function fwrite; 48use function rewind; 49use function strlen; 50use function time; 51use function unlink; 52use function version_compare; 53 54use const DIRECTORY_SEPARATOR; 55use const PHP_VERSION; 56 57/** 58 * Automatic upgrades. 59 */ 60class UpgradeService 61{ 62 // Options for fetching files using GuzzleHTTP 63 private const GUZZLE_OPTIONS = [ 64 'connect_timeout' => 25, 65 'read_timeout' => 25, 66 'timeout' => 55, 67 ]; 68 69 // Transfer stream data in blocks of this number of bytes. 70 private const READ_BLOCK_SIZE = 65535; 71 72 // Only check the webtrees server once per day. 73 private const CHECK_FOR_UPDATE_INTERVAL = 24 * 60 * 60; 74 75 // Fetch information about upgrades from here. 76 // Note: earlier versions of webtrees used svn.webtrees.net, so we must maintain both URLs. 77 private const UPDATE_URL = 'https://dev.webtrees.net/build/latest-version.txt'; 78 79 // If the update server doesn't respond after this time, give up. 80 private const HTTP_TIMEOUT = 3.0; 81 82 private TimeoutService $timeout_service; 83 84 /** 85 * UpgradeService constructor. 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 $ex) { 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 $ex) { 240 // Skip to the next folder. 241 } 242 } 243 } 244 245 /** 246 * @return bool 247 */ 248 public function isUpgradeAvailable(): bool 249 { 250 // If the latest version is unavailable, we will have an empty sting which equates to version 0. 251 252 return version_compare(Webtrees::VERSION, $this->fetchLatestVersion()) < 0; 253 } 254 255 /** 256 * What is the latest version of webtrees. 257 * 258 * @return string 259 */ 260 public function latestVersion(): string 261 { 262 $latest_version = $this->fetchLatestVersion(); 263 264 [$version] = explode('|', $latest_version); 265 266 return $version; 267 } 268 269 /** 270 * Where can we download the latest version of webtrees. 271 * 272 * @return string 273 */ 274 public function downloadUrl(): string 275 { 276 $latest_version = $this->fetchLatestVersion(); 277 278 [, , $url] = explode('|', $latest_version . '||'); 279 280 return $url; 281 } 282 283 public function startMaintenanceMode(): void 284 { 285 $message = I18N::translate('This website is being upgraded. Try again in a few minutes.'); 286 287 file_put_contents(Webtrees::OFFLINE_FILE, $message); 288 } 289 290 public function endMaintenanceMode(): void 291 { 292 if (file_exists(Webtrees::OFFLINE_FILE)) { 293 unlink(Webtrees::OFFLINE_FILE); 294 } 295 } 296 297 /** 298 * Check with the webtrees.net server for the latest version of webtrees. 299 * Fetching the remote file can be slow, so check infrequently, and cache the result. 300 * Pass the current versions of webtrees, PHP and MySQL, as the response 301 * may be different for each. The server logs are used to generate 302 * installation statistics which can be found at https://dev.webtrees.net/statistics.html 303 * 304 * @return string 305 */ 306 private function fetchLatestVersion(): string 307 { 308 $last_update_timestamp = (int) Site::getPreference('LATEST_WT_VERSION_TIMESTAMP'); 309 310 $current_timestamp = time(); 311 312 if ($last_update_timestamp < $current_timestamp - self::CHECK_FOR_UPDATE_INTERVAL) { 313 try { 314 $client = new Client([ 315 'timeout' => self::HTTP_TIMEOUT, 316 ]); 317 318 $response = $client->get(self::UPDATE_URL, [ 319 'query' => $this->serverParameters(), 320 ]); 321 322 if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) { 323 Site::setPreference('LATEST_WT_VERSION', $response->getBody()->getContents()); 324 Site::setPreference('LATEST_WT_VERSION_TIMESTAMP', (string) $current_timestamp); 325 } 326 } catch (GuzzleException $ex) { 327 // Can't connect to the server? 328 // Use the existing information about latest versions. 329 } 330 } 331 332 return Site::getPreference('LATEST_WT_VERSION'); 333 } 334 335 /** 336 * The upgrade server needs to know a little about this server. 337 * 338 * @return array<string,string> 339 */ 340 private function serverParameters(): array 341 { 342 $operating_system = DIRECTORY_SEPARATOR === '/' ? 'u' : 'w'; 343 344 return [ 345 'w' => Webtrees::VERSION, 346 'p' => PHP_VERSION, 347 'o' => $operating_system, 348 ]; 349 } 350} 351