| 40 | | class Upgrade extends AbstractSetup |
| 41 | | { |
| 42 | | final public const string GITHUB_PATH = 'thorsten/phpMyFAQ/releases/download/development-nightly-%s/'; |
| 43 | | |
| 44 | | private const string GITHUB_FILENAME = 'phpMyFAQ-nightly-%s.zip'; |
| 45 | | |
| 46 | | private const string PHPMYFAQ_FILENAME = 'phpMyFAQ-%s.zip'; |
| 47 | | |
| 48 | | public string $upgradeDirectory = PMF_CONTENT_DIR . '/upgrades'; |
| 49 | | |
| 50 | | private string $installationDirectory; |
| 51 | | |
| 52 | | private bool $isNightly; |
| 53 | | |
| 54 | | private HttpClientInterface $httpClient; |
| 55 | | |
| 56 | | public function __construct( |
| 57 | | protected System $system, |
| 58 | | private readonly Configuration $configuration, |
| 59 | | ?HttpClientInterface $httpClient = null, |
| 60 | | ) { |
| 61 | | parent::__construct($this->system); |
| 62 | | |
| 63 | | $this->installationDirectory = (string) PMF_ROOT_DIR; |
| 64 | | |
| 65 | | $this->isNightly = |
| 66 | | $this->configuration->get(item: 'upgrade.releaseEnvironment') === ReleaseType::NIGHTLY->value; |
| 67 | | |
| 68 | | $this->httpClient = $httpClient ?? HttpClient::create(['timeout' => 60]); |
| 69 | | } |
| 70 | | |
| 71 | | |
| 72 | | |
| 73 | | |
| 74 | | |
| 75 | | |
| 76 | | public function checkFilesystem(): bool |
| 77 | | { |
| 78 | | if (!is_dir($this->upgradeDirectory) && !mkdir($this->upgradeDirectory)) { |
| 79 | | throw new Exception(message: 'The folder ' . $this->upgradeDirectory . ' is missing.'); |
| 80 | | } |
| 81 | | |
| 82 | | if (!is_dir(PMF_CONTENT_DIR . '/user/attachments')) { |
| 83 | | throw new Exception(message: 'The folder /content/user/attachments is missing.'); |
| 84 | | } |
| 85 | | |
| 86 | | if (!is_dir(PMF_CONTENT_DIR . '/user/images')) { |
| 87 | | throw new Exception(message: 'The folder /content/user/images is missing.'); |
| 88 | | } |
| 89 | | |
| 90 | | if (!is_dir(PMF_CONTENT_DIR . '/core/data')) { |
| 91 | | throw new Exception(message: 'The folder /content/core/data is missing.'); |
| 92 | | } |
| 93 | | |
| 94 | | if (!is_dir((string) PMF_ROOT_DIR . '/assets/templates')) { |
| 95 | | throw new Exception(message: 'The folder /phpmyfaq/assets/templates is missing.'); |
| 96 | | } |
| 97 | | |
| 98 | | if ( |
| 99 | | !is_file(PMF_CONTENT_DIR . '/core/config/constants.php') |
| 100 | | || !is_file(PMF_CONTENT_DIR . '/core/config/database.php') |
| 101 | | ) { |
| 102 | | throw new Exception(message: 'The files /content/core/config/constant.php and' |
| 103 | | . ' /content/core/config/database.php are missing.'); |
| 104 | | } |
| 105 | | |
| 106 | | if ( |
| 107 | | $this->configuration->isElasticsearchActive() |
| 108 | | && !is_file(PMF_CONTENT_DIR . '/core/config/elasticsearch.php') |
| 109 | | ) { |
| 110 | | throw new Exception(message: 'The file /content/core/config/elasticsearch.php is missing.'); |
| 111 | | } |
| 112 | | |
| 113 | | if ($this->configuration->isLdapActive() && !is_file(PMF_CONTENT_DIR . '/core/config/ldap.php')) { |
| 114 | | throw new Exception(message: 'The file /content/core/config/ldap.php is missing.'); |
| 115 | | } |
| 116 | | |
| 117 | | if ( |
| 118 | | $this->configuration->isSignInWithMicrosoftActive() && !is_file(PMF_CONTENT_DIR . '/core/config/azure.php') |
| 119 | | ) { |
| 120 | | throw new Exception(message: 'The file /content/core/config/azure.php is missing.'); |
| 121 | | } |
| 122 | | |
| 123 | | |
| 124 | | |
| 125 | | |
| 126 | | |
| 127 | | |
| 128 | | $nonWritablePaths = WritablePathScanner::getNonWritablePaths( |
| 129 | | $this->installationDirectory, |
| 130 | | $this->upgradeDirectory, |
| 131 | | ); |
| 132 | | |
| 133 | | if ($nonWritablePaths !== []) { |
| 134 | | throw new Exception( |
| 135 | | message: 'The following files or directories are not writable for the web server: ' |
| 136 | | . WritablePathScanner::formatPathList($nonWritablePaths), |
| 137 | | ); |
| 138 | | } |
| 139 | | |
| 140 | | return true; |
| 141 | | } |
| 142 | | |
| 143 | | |
| 144 | | |
| 145 | | |
| 146 | | |
| 147 | | |
| 148 | | |
| 149 | | public function downloadPackage(string $version): string |
| 150 | | { |
| 151 | | $url = $this->getDownloadHost() . $this->getPath() . $this->getFilename($version); |
| 152 | | |
| 153 | | $attempts = 3; |
| 154 | | $lastExceptionMessage = null; |
| 155 | | |
| 156 | | for ($i = 0; $i < $attempts; $i++) { |
| 157 | | try { |
| 158 | | $response = $this->httpClient->request(method: 'GET', url: $url); |
| 159 | | |
| 160 | | if ($response->getStatusCode() !== 200) { |
| 161 | | throw new Exception( |
| 162 | | message: 'Cannot download package (HTTP Status: ' . $response->getStatusCode() . ').', |
| 163 | | ); |
| 164 | | } |
| 165 | | |
| 166 | | $package = $response->getContent(); |
| 167 | | |
| 168 | | $targetPath = $this->upgradeDirectory . DIRECTORY_SEPARATOR . $this->getFilename($version); |
| 169 | | file_put_contents($targetPath, $package); |
| 170 | | |
| 171 | | return $targetPath; |
| 172 | | } catch ( |
| 173 | | TransportExceptionInterface|ClientExceptionInterface|RedirectionExceptionInterface|ServerExceptionInterface $exception |
| 174 | | ) { |
| 175 | | $lastExceptionMessage = $exception->getMessage(); |
| 176 | | |
| 177 | | |
| 178 | | if ($i === ($attempts - 1)) { |
| 179 | | throw new Exception('Download failed after ' . $attempts . ' attempts: ' . $lastExceptionMessage); |
| 180 | | } |
| 181 | | |
| 182 | | |
| 183 | | usleep(microseconds: 250_000); |
| 184 | | } |
| 185 | | } |
| 186 | | |
| 187 | | |
| 188 | | throw new Exception('Download failed: ' . ($lastExceptionMessage ?? 'unknown error')); |
| 189 | | } |
| 190 | | |
| 191 | | |
| 192 | | |
| 193 | | |
| 194 | | |
| 195 | | |
| 196 | | |
| 197 | | |
| 198 | | public function verifyPackage(string $path, string $version): bool |
| 199 | | { |
| 200 | | $response = $this->httpClient->request( |
| 201 | | method: 'GET', |
| 202 | | url: DownloadHostType::PHPMYFAQ->value . 'info/' . $version, |
| 203 | | ); |
| 204 | | |
| 205 | | try { |
| 206 | | $responseContent = json_decode( |
| 207 | | $response->getContent(), |
| 208 | | associative: true, |
| 209 | | depth: 512, |
| 210 | | flags: JSON_THROW_ON_ERROR, |
| 211 | | ); |
| 212 | | |
| 213 | | $expectedMd5 = is_array($responseContent) ? $responseContent['zip']['md5'] ?? null : null; |
| 214 | | |
| 215 | | return is_string($expectedMd5) && md5_file($path) === $expectedMd5; |
| 216 | | } catch ( |
| 217 | | TransportExceptionInterface|ClientExceptionInterface|RedirectionExceptionInterface|ServerExceptionInterface $e |
| 218 | | ) { |
| 219 | | $this->configuration->getLogger()->log(Level::Error, $e->getMessage()); |
| 220 | | |
| 221 | | return false; |
| 222 | | } |
| 223 | | } |
| 224 | | |
| 225 | | |
| 226 | | |
| 227 | | |
| 228 | | |
| 229 | | |
| 230 | | |
| 231 | | public function extractPackage(string $path, callable $progressCallback): bool |
| 232 | | { |
| 233 | | $zipArchive = new ZipArchive(); |
| 234 | | |
| 235 | | if (!is_file($path)) { |
| 236 | | throw new Exception(message: 'Given path to download package is not valid.'); |
| 237 | | } |
| 238 | | |
| 239 | | |
| 240 | | |
| 241 | | |
| 242 | | |
| 243 | | $realPath = realpath($path); |
| 244 | | $realUpgradeDirectory = realpath($this->upgradeDirectory); |
| 245 | | |
| 246 | | if ( |
| 247 | | $realPath === false |
| 248 | | || $realUpgradeDirectory === false |
| 249 | | || !str_starts_with($realPath, $realUpgradeDirectory . DIRECTORY_SEPARATOR) |
| 250 | | ) { |
| 251 | | throw new Exception(message: 'Given path to download package is outside the upgrade directory.'); |
| 252 | | } |
| 253 | | |
| 254 | | $zipFile = $zipArchive->open($realPath); |
| 255 | | |
| 256 | | $zipArchive->registerProgressCallback(rate: 0.05, callback: static function (float $rate) use ( |
| 257 | | $progressCallback, |
| 258 | | ): void { |
| 259 | | $progress = (int) ($rate * 100) . '%'; |
| 260 | | $progressCallback($progress); |
| 261 | | }); |
| 262 | | |
| 263 | | if ($zipFile) { |
| 264 | | |
| 265 | | $extractPath = $this->upgradeDirectory . '/new/'; |
| 266 | | $this->secureExtractZip($zipArchive, $extractPath); |
| 267 | | return $zipArchive->close(); |
| 268 | | } |
| 269 | | |
| 270 | | throw new Exception(message: 'Cannot open zipped download package.'); |
| 271 | | } |
| 272 | | |
| 273 | | |
| 274 | | |
| 275 | | |
| 276 | | |
| 277 | | |
| 278 | | |
| 279 | | |
| 280 | | private function secureExtractZip(ZipArchive $zipArchive, string $destination): void |
| 281 | | { |
| 282 | | |
| 283 | | $resolvedDestination = realpath($destination); |
| 284 | | $destination = |
| 285 | | rtrim($resolvedDestination !== false ? $resolvedDestination : $destination, DIRECTORY_SEPARATOR) |
| 286 | | . DIRECTORY_SEPARATOR; |
| 287 | | |
| 288 | | |
| 289 | | if (!is_dir($destination)) { |
| 290 | | mkdir(directory: $destination, permissions: 0o755, recursive: true); |
| 291 | | } |
| 292 | | |
| 293 | | |
| 294 | | for ($i = 0; $i < $zipArchive->numFiles; $i++) { |
| 295 | | $entry = $zipArchive->getNameIndex($i); |
| 296 | | if ($entry === false) { |
| 297 | | continue; |
| 298 | | } |
| 299 | | |
| 300 | | |
| 301 | | if (!$this->isPathSafe($entry, $destination)) { |
| 302 | | $this->configuration->getLogger()->error('Zip Slip attack detected in package', [ |
| 303 | | 'malicious_entry' => $entry, |
| 304 | | ]); |
| 305 | | throw new Exception(message: sprintf('Malicious path detected in archive: %s', $entry)); |
| 306 | | } |
| 307 | | |
| 308 | | |
| 309 | | $zipArchive->extractTo($destination, $entry); |
| 310 | | } |
| 311 | | } |
| 312 | | |
| 313 | | |
| 314 | | |
| 315 | | |
| 316 | | |
| 317 | | |
| 318 | | |
| 319 | | |
| 320 | | private function isPathSafe(string $entryPath, string $destination): bool |
| 321 | | { |
| 322 | | |
| 323 | | $entryPath = str_replace(search: "\0", replace: '', subject: $entryPath); |
| 324 | | |
| 325 | | |
| 326 | | $fullPath = $destination . $entryPath; |
| 327 | | |
| 328 | | |
| 329 | | $realPath = realpath(dirname($fullPath)); |
| 330 | | if ($realPath === false) { |
| 331 | | |
| 332 | | $realPath = (string) realpath($destination) . DIRECTORY_SEPARATOR . dirname($entryPath); |
| 333 | | } |
| 334 | | |
| 335 | | |
| 336 | | $resolvedNormalizedDestination = realpath($destination); |
| 337 | | $normalizedDestination = rtrim( |
| 338 | | $resolvedNormalizedDestination !== false ? $resolvedNormalizedDestination : $destination, |
| 339 | | DIRECTORY_SEPARATOR, |
| 340 | | ); |
| 341 | | $normalizedPath = rtrim($realPath, DIRECTORY_SEPARATOR); |
| 342 | | |
| 343 | | |
| 344 | | if (!str_starts_with($normalizedPath, $normalizedDestination)) { |
| 345 | | return false; |
| 346 | | } |
| 347 | | |
| 348 | | |
| 349 | | if (preg_match('#(\.\./)|(\.\.)|(\./)|(^/)#', $entryPath)) { |
| 350 | | return false; |
| 351 | | } |
| 352 | | |
| 353 | | |
| 354 | | if (str_starts_with($entryPath, '/') || preg_match('#^[a-zA-Z]:#', $entryPath)) { |
| 355 | | return false; |
| 356 | | } |
| 357 | | |
| 358 | | return true; |
| 359 | | } |
| 360 | | |
| 361 | | |
| 362 | | |
| 363 | | |
| 364 | | |
| 365 | | |
| 366 | | |
| 367 | | public function createTemporaryBackup(string $backupName, callable $progressCallback): bool |
| 368 | | { |
| 369 | | $outputZipFile = $this->upgradeDirectory . DIRECTORY_SEPARATOR . $backupName; |
| 370 | | |
| 371 | | if (file_exists($outputZipFile)) { |
| 372 | | throw new Exception(message: 'Backup file already exists.'); |
| 373 | | } |
| 374 | | |
| 375 | | $zipArchive = new ZipArchive(); |
| 376 | | if ($zipArchive->open($outputZipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { |
| 377 | | throw new Exception(message: 'Cannot create backup file.'); |
| 378 | | } |
| 379 | | |
| 380 | | $sourceDir = (string) PMF_ROOT_DIR; |
| 381 | | $files = new RecursiveIteratorIterator( |
| 382 | | new RecursiveDirectoryIterator($sourceDir), |
| 383 | | RecursiveIteratorIterator::SELF_FIRST, |
| 384 | | ); |
| 385 | | |
| 386 | | $zipArchive->registerProgressCallback(rate: 0.05, callback: static function (float $rate) use ( |
| 387 | | $progressCallback, |
| 388 | | ): void { |
| 389 | | $progress = (int) ($rate * 100) . '%'; |
| 390 | | $progressCallback($progress); |
| 391 | | }); |
| 392 | | |
| 393 | | foreach ($files as $file) { |
| 394 | | if (!$file instanceof \SplFileInfo) { |
| 395 | | continue; |
| 396 | | } |
| 397 | | |
| 398 | | $filePath = $file->getRealPath(); |
| 399 | | if ($filePath === false) { |
| 400 | | continue; |
| 401 | | } |
| 402 | | |
| 403 | | if (str_contains($filePath, $this->upgradeDirectory . DIRECTORY_SEPARATOR)) { |
| 404 | | continue; |
| 405 | | } |
| 406 | | |
| 407 | | if (is_dir($filePath)) { |
| 408 | | $zipArchive->addEmptyDir(str_replace( |
| 409 | | $sourceDir . DIRECTORY_SEPARATOR, |
| 410 | | replace: '', |
| 411 | | subject: $filePath . DIRECTORY_SEPARATOR, |
| 412 | | )); |
| 413 | | continue; |
| 414 | | } |
| 415 | | |
| 416 | | if (!is_file($filePath)) { |
| 417 | | continue; |
| 418 | | } |
| 419 | | |
| 420 | | $zipArchive->addFile($filePath, str_replace( |
| 421 | | $sourceDir . DIRECTORY_SEPARATOR, |
| 422 | | replace: '', |
| 423 | | subject: $filePath, |
| 424 | | )); |
| 425 | | } |
| 426 | | |
| 427 | | $zipArchive->close(); |
| 428 | | |
| 429 | | return file_exists($outputZipFile); |
| 430 | | } |
| 431 | | |
| 432 | | |
| 433 | | |
| 434 | | |
| 435 | | |
| 436 | | |
| 437 | | |
| 438 | | |
| 439 | | public function installPackage(callable $progressCallback): bool |
| 440 | | { |
| 441 | | |
| 442 | | |
| 443 | | |
| 444 | | $sourceDir = realpath($this->upgradeDirectory . '/new/phpmyfaq'); |
| 445 | | |
| 446 | | if ($sourceDir === false) { |
| 447 | | throw new Exception(message: 'The extracted package is missing, please run the extract step again.'); |
| 448 | | } |
| 449 | | |
| 450 | | $destinationDir = $this->installationDirectory; |
| 451 | | |
| 452 | | $sourceDirIterator = new RecursiveIteratorIterator( |
| 453 | | new RecursiveDirectoryIterator($sourceDir, FilesystemIterator::SKIP_DOTS), |
| 454 | | RecursiveIteratorIterator::SELF_FIRST, |
| 455 | | ); |
| 456 | | |
| 457 | | $totalFiles = iterator_count($sourceDirIterator); |
| 458 | | $currentFile = 0; |
| 459 | | $failedPaths = []; |
| 460 | | |
| 461 | | |
| 462 | | |
| 463 | | |
| 464 | | set_error_handler(static fn(): bool => true); |
| 465 | | |
| 466 | | try { |
| 467 | | foreach ($sourceDirIterator as $item) { |
| 468 | | if (!$item instanceof \SplFileInfo) { |
| 469 | | continue; |
| 470 | | } |
| 471 | | |
| 472 | | $source = $item->getRealPath(); |
| 473 | | if ($source === false) { |
| 474 | | continue; |
| 475 | | } |
| 476 | | |
| 477 | | $relativePath = substr($source, strlen($sourceDir) + 1); |
| 478 | | $destination = $destinationDir . DIRECTORY_SEPARATOR . $relativePath; |
| 479 | | |
| 480 | | if ($item->isDir()) { |
| 481 | | if (!is_dir($destination) && !mkdir($destination, permissions: 0o755, recursive: true)) { |
| 482 | | $failedPaths[] = $relativePath; |
| 483 | | } |
| 484 | | } |
| 485 | | |
| 486 | | if (!$item->isDir() && !copy($source, $destination)) { |
| 487 | | $failedPaths[] = $relativePath; |
| 488 | | } |
| 489 | | |
| 490 | | ++$currentFile; |
| 491 | | if (($currentFile % 10) !== 0) { |
| 492 | | continue; |
| 493 | | } |
| 494 | | |
| 495 | | $progress = 100; |
| 496 | | if ($totalFiles > 0) { |
| 497 | | $progress = (int) (($currentFile / $totalFiles) * 100) . '%'; |
| 498 | | } |
| 499 | | |
| 500 | | $progressCallback($progress); |
| 501 | | } |
| 502 | | } finally { |
| 503 | | restore_error_handler(); |
| 504 | | } |
| 505 | | |
| 506 | | if ($failedPaths !== []) { |
| 507 | | throw new Exception(message: sprintf( |
| 508 | | 'Could not copy %d path(s) into the installation directory: %s.' |
| 509 | | . ' Please check the file permissions and run the update again.', |
| 510 | | count($failedPaths), |
| 511 | | WritablePathScanner::formatPathList($failedPaths), |
| 512 | | )); |
| 513 | | } |
| 514 | | |
| 515 | | $this->resetOpcache(); |
| 516 | | |
| 517 | | return true; |
| 518 | | } |
| 519 | | |
| 520 | | |
| 521 | | |
| 522 | | |
| 523 | | |
| 524 | | |
| 525 | | |
| 526 | | private function resetOpcache(): void |
| 527 | | { |
| 528 | | if (!function_exists('opcache_reset')) { |
| 529 | | return; |
| 530 | | } |
| 531 | | |
| 532 | | |
| 533 | | |
| 534 | | set_error_handler(static fn(): bool => true); |
| 535 | | |
| 536 | | try { |
| 537 | | opcache_reset(); |
| 538 | | } finally { |
| 539 | | restore_error_handler(); |
| 540 | | } |
| 541 | | } |
| 542 | | |
| 543 | | |
| 544 | | |
| 545 | | |
| 546 | | public function cleanUp(): bool |
| 547 | | { |
| 548 | | $directoryToDelete = $this->upgradeDirectory . '/new/phpmyfaq/'; |
| 549 | | |
| 550 | | $files = new RecursiveIteratorIterator( |
| 551 | | new RecursiveDirectoryIterator($directoryToDelete, FilesystemIterator::SKIP_DOTS), |
| 552 | | RecursiveIteratorIterator::CHILD_FIRST, |
| 553 | | ); |
| 554 | | |
| 555 | | foreach ($files as $file) { |
| 556 | | if (!$file instanceof \SplFileInfo) { |
| 557 | | continue; |
| 558 | | } |
| 559 | | |
| 560 | | $filePath = $file->getRealPath(); |
| 561 | | if ($filePath === false) { |
| 562 | | continue; |
| 563 | | } |
| 564 | | |
| 565 | | if ($file->isDir()) { |
| 566 | | rmdir($filePath); |
| 567 | | continue; |
| 568 | | } |
| 569 | | |
| 570 | | unlink($filePath); |
| 571 | | } |
| 572 | | |
| 573 | | return rmdir($directoryToDelete); |
| 574 | | } |
| 575 | | |
| 576 | | |
| 577 | | |
| 578 | | |
| 579 | | public function getDownloadHost(): string |
| 580 | | { |
| 581 | | if ($this->isNightly()) { |
| 582 | | return DownloadHostType::GITHUB->value; |
| 583 | | } |
| 584 | | |
| 585 | | return DownloadHostType::PHPMYFAQ->value; |
| 586 | | } |
| 587 | | |
| 588 | | |
| 589 | | |
| 590 | | |
| 591 | | public function getPath(): string |
| 592 | | { |
| 593 | | if ($this->isNightly()) { |
| 594 | | return sprintf(self::GITHUB_PATH, date(format: 'Y-m-d')); |
| 595 | | } |
| 596 | | |
| 597 | | return ''; |
| 598 | | } |
| 599 | | |
| 600 | | |
| 601 | | |
| 602 | | |
| 603 | | public function getFilename(string $version): string |
| 604 | | { |
| 605 | | if ($this->isNightly()) { |
| 606 | | return sprintf(self::GITHUB_FILENAME, date(format: 'Y-m-d')); |
| 607 | | } |
| 608 | | |
| 609 | | return sprintf(self::PHPMYFAQ_FILENAME, $version); |
| 610 | | } |
| 611 | | |
| 612 | | public function setUpgradeDirectory(string $upgradeDirectory): void |
| 613 | | { |
| 614 | | $this->upgradeDirectory = $upgradeDirectory; |
| 615 | | } |
| 616 | | |
| 617 | | public function setInstallationDirectory(string $installationDirectory): void |
| 618 | | { |
| 619 | | $this->installationDirectory = $installationDirectory; |
| 620 | | } |
| 621 | | |
| 622 | | public function isNightly(): bool |
| 623 | | { |
| 624 | | return $this->isNightly; |
| 625 | | } |
| 626 | | |
| 627 | | public function setIsNightly(bool $isNightly): void |
| 628 | | { |
| 629 | | $this->isNightly = $isNightly; |
| 630 | | } |
| 631 | | |
| 632 | | public function isMaintenanceEnabled(): bool |
| 633 | | { |
| 634 | | return true === $this->configuration->get(item: 'main.maintenanceMode'); |
| 635 | | } |
| 636 | | } |