manifestUrl = trim((string) ($config["manifest_url"] ?? "")); $this->workDir = rtrim((string) ($config["work_dir"] ?? ""), "/\\"); $this->backupDir = rtrim((string) ($config["backup_dir"] ?? ""), "/\\"); $this->currentVersion = trim((string) ($config["current_version"] ?? "")); $this->appRoot = rtrim((string) ($config["app_root"] ?? ""), "/\\"); $this->userAgent = trim((string) ($config["user_agent"] ?? "Simple-PHP-Updater")); if ($this->userAgent === "") { $this->userAgent = "Simple-PHP-Updater"; } $this->preservePaths = $this->normalizePathList($config["preserve_paths"] ?? null); if ($this->preservePaths === []) { $this->preservePaths = ["config.php", "data/", ".git/"]; } $this->requiredPackagePaths = $this->normalizePathList($config["required_package_paths"] ?? null); if ($this->requiredPackagePaths === []) { $this->requiredPackagePaths = ["index.php", "admin/", "includes/"]; } if ($this->workDir === "") { throw new InvalidArgumentException("Updater work directory is not configured."); } if ($this->backupDir === "") { throw new InvalidArgumentException("Updater backup directory is not configured."); } if ($this->currentVersion === "") { throw new InvalidArgumentException("Current application version is not configured."); } if ($this->appRoot === "" || !is_dir($this->appRoot)) { throw new InvalidArgumentException("Application root cannot be resolved."); } } public function getManifestUrl(): string { return $this->manifestUrl; } public function getCurrentVersion(): string { return $this->currentVersion; } public function fetchManifest(): array { if ($this->manifestUrl === "") { throw new RuntimeException("UPDATE_MANIFEST_URL is not configured."); } $body = $this->httpGet($this->manifestUrl, 15); $manifest = json_decode($body, true); if (!is_array($manifest)) { throw new RuntimeException("Manifest response is not valid JSON."); } $version = trim((string) ($manifest["version"] ?? $manifest["latest"] ?? "")); $packageUrl = trim((string) ($manifest["package_url"] ?? "")); $sha256 = strtolower(trim((string) ($manifest["sha256"] ?? ""))); $size = isset($manifest["size"]) ? (int) $manifest["size"] : 0; $publishedAt = trim((string) ($manifest["published_at"] ?? "")); if (!self::isVersion($version)) { throw new RuntimeException("Manifest version is invalid."); } if (!filter_var($packageUrl, FILTER_VALIDATE_URL)) { throw new RuntimeException("Manifest package URL is invalid."); } if (!preg_match('/^[a-f0-9]{64}$/', $sha256)) { throw new RuntimeException("Manifest checksum is invalid."); } return [ "version" => $version, "package_url" => $packageUrl, "sha256" => $sha256, "size" => $size, "published_at" => $publishedAt, ]; } public function updateAvailable(array $manifest): bool { return version_compare( self::versionToCompare((string) ($manifest["version"] ?? "")), self::versionToCompare($this->currentVersion), ">", ); } public function deploy(array $manifest): array { $version = (string) ($manifest["version"] ?? ""); if (!self::isVersion($version)) { throw new RuntimeException("Manifest version is invalid."); } $runId = date("Ymd-His"); $workDir = $this->workDir . DIRECTORY_SEPARATOR . $runId; $stageDir = $workDir . DIRECTORY_SEPARATOR . "stage"; $zipFile = $workDir . DIRECTORY_SEPARATOR . "package.zip"; $backupDir = $this->backupDir . DIRECTORY_SEPARATOR . $runId . "-" . $version; try { self::ensureDirectory($workDir); $this->downloadPackage($manifest, $zipFile); $this->extractPackage($zipFile, $stageDir); $result = $this->copyWithBackup($stageDir, $backupDir); } finally { self::removeDirectory($workDir); } $removedBackups = $this->cleanupOldBackups($backupDir); return [ "backup_dir" => $backupDir, "copied" => $result["copied"], "backed_up" => $result["backed_up"], "removed_backups" => $removedBackups, "skipped" => $result["skipped"], ]; } public static function versionToCompare(string $version): string { return ltrim(trim($version), "vV"); } public static function isVersion(string $version): bool { return preg_match('/^v\d+\.\d+\.\d+$/', $version) === 1; } public static function ensureDirectory(string $dir): void { if (!is_dir($dir) && !mkdir($dir, 02775, true) && !is_dir($dir)) { throw new RuntimeException("Directory cannot be created: " . $dir); } @chmod($dir, 02775); } public static function removeDirectory(string $dir): void { if (!is_dir($dir)) { return; } $items = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST, ); foreach ($items as $item) { if ($item->isDir()) { rmdir($item->getPathname()); } else { unlink($item->getPathname()); } } rmdir($dir); } private function httpGet(string $url, int $timeout): string { if (!filter_var($url, FILTER_VALIDATE_URL)) { throw new RuntimeException("Invalid URL: " . $url); } $context = stream_context_create([ "http" => [ "method" => "GET", "timeout" => $timeout, "ignore_errors" => true, "header" => "User-Agent: " . $this->userAgent . "\r\n", ], ]); $body = @file_get_contents($url, false, $context); $status = 0; $responseHeaders = function_exists("http_get_last_response_headers") ? http_get_last_response_headers() : []; if (is_array($responseHeaders)) { foreach ($responseHeaders as $header) { if (preg_match('/^HTTP\/\S+\s+(\d+)/', $header, $matches)) { $status = (int) $matches[1]; } } } if ($body === false || ($status >= 400 && $status < 600)) { throw new RuntimeException( "HTTP request failed" . ($status > 0 ? " with status " . $status : "") . ".", ); } return $body; } private function downloadPackage(array $manifest, string $targetFile): void { self::ensureDirectory(dirname($targetFile)); $data = $this->httpGet((string) $manifest["package_url"], 120); if ($data === "") { throw new RuntimeException("Downloaded package is empty."); } if (file_put_contents($targetFile, $data, LOCK_EX) === false) { throw new RuntimeException("Downloaded package cannot be written."); } if ((int) $manifest["size"] > 0 && filesize($targetFile) !== (int) $manifest["size"]) { unlink($targetFile); throw new RuntimeException("Downloaded package size mismatch."); } $actualHash = strtolower(hash_file("sha256", $targetFile) ?: ""); if ($actualHash !== (string) $manifest["sha256"]) { unlink($targetFile); throw new RuntimeException("Package checksum mismatch."); } } private function extractPackage(string $zipFile, string $stageDir): void { if (!class_exists("ZipArchive")) { throw new RuntimeException("PHP ZipArchive extension is not available."); } self::removeDirectory($stageDir); self::ensureDirectory($stageDir); $zip = new ZipArchive(); if ($zip->open($zipFile) !== true) { throw new RuntimeException("Downloaded package is not a readable ZIP file."); } $hasRequiredPath = false; for ($i = 0; $i < $zip->numFiles; $i++) { $name = (string) $zip->getNameIndex($i); if (!$this->validateZipEntry($name)) { $zip->close(); throw new RuntimeException("ZIP contains an unsafe path: " . $name); } if ($this->matchesAnyConfiguredPath($name, $this->requiredPackagePaths)) { $hasRequiredPath = true; } } if (!$hasRequiredPath) { $zip->close(); throw new RuntimeException("ZIP does not look like an app-root release package."); } if (!$zip->extractTo($stageDir)) { $zip->close(); throw new RuntimeException("ZIP package cannot be extracted."); } $zip->close(); } private function validateZipEntry(string $entry): bool { $entry = str_replace("\\", "/", $entry); $normalized = trim($entry, "/"); if ( $normalized === "" || str_contains($entry, "\0") || str_starts_with($entry, "/") || preg_match('/^[A-Za-z]:\//', $entry) ) { return false; } foreach (explode("/", $normalized) as $segment) { if ($segment === "" || $segment === "." || $segment === "..") { return false; } } return true; } private function copyWithBackup(string $stageDir, string $backupDir): array { self::ensureDirectory($backupDir); $copied = 0; $backedUp = 0; $skipped = 0; $items = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($stageDir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST, ); foreach ($items as $item) { $relativePath = $this->relativePath($item->getPathname(), $stageDir); if ($this->shouldPreservePath($relativePath)) { $skipped++; continue; } $targetPath = $this->appRoot . DIRECTORY_SEPARATOR . $relativePath; if ($item->isDir()) { self::ensureDirectory($targetPath); continue; } self::ensureDirectory(dirname($targetPath)); if (file_exists($targetPath)) { $backupPath = $backupDir . DIRECTORY_SEPARATOR . $relativePath; self::ensureDirectory(dirname($backupPath)); if (!copy($targetPath, $backupPath)) { throw new RuntimeException("Cannot back up file: " . $relativePath); } $backedUp++; } if (!copy($item->getPathname(), $targetPath)) { throw new RuntimeException("Cannot deploy file: " . $relativePath); } @chmod($targetPath, fileperms($item->getPathname()) & 0777); $copied++; } return [ "copied" => $copied, "backed_up" => $backedUp, "skipped" => $skipped, ]; } private function cleanupOldBackups(string $keepBackupDir): int { if (!is_dir($this->backupDir)) { return 0; } $keepRealPath = realpath($keepBackupDir); $backupRootRealPath = realpath($this->backupDir); if ($keepRealPath === false || $backupRootRealPath === false) { return 0; } $removed = 0; $items = new DirectoryIterator($backupRootRealPath); foreach ($items as $item) { if ($item->isDot() || !$item->isDir()) { continue; } $path = $item->getPathname(); if (realpath($path) === $keepRealPath) { continue; } self::removeDirectory($path); if (is_dir($path)) { throw new RuntimeException("Old backup directory could not be removed: " . $path); } $removed++; } return $removed; } private function shouldPreservePath(string $relativePath): bool { return $this->matchesAnyConfiguredPath($relativePath, $this->preservePaths); } private function matchesAnyConfiguredPath(string $path, array $configuredPaths): bool { $path = trim(str_replace("\\", "/", $path), "/"); if ($path === "") { return true; } foreach ($configuredPaths as $configuredPath) { $configuredPath = str_replace("\\", "/", $configuredPath); $isDirectoryMatch = str_ends_with($configuredPath, "/"); $configuredPath = trim($configuredPath, "/"); if ($configuredPath === "") { continue; } if ($path === $configuredPath) { return true; } if (($isDirectoryMatch || !str_contains($configuredPath, ".")) && str_starts_with($path, $configuredPath . "/") ) { return true; } } return false; } private function relativePath(string $path, string $baseDir): string { return ltrim(str_replace("\\", "/", substr($path, strlen($baseDir))), "/"); } /** * @param mixed $paths * @return string[] */ private function normalizePathList($paths): array { if (!is_array($paths)) { return []; } $normalized = []; foreach ($paths as $path) { $path = trim(str_replace("\\", "/", (string) $path)); if ($path !== "") { $normalized[] = $path; } } return $normalized; } }