| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469 |
- <?php
- declare(strict_types=1);
- class SimpleUpdater
- {
- private string $manifestUrl;
- private string $workDir;
- private string $backupDir;
- private string $currentVersion;
- private string $appRoot;
- private string $userAgent;
- /** @var string[] */
- private array $preservePaths;
- /** @var string[] */
- private array $requiredPackagePaths;
- /**
- * @param array{
- * manifest_url?: string,
- * work_dir?: string,
- * backup_dir?: string,
- * current_version?: string,
- * app_root?: string,
- * user_agent?: string,
- * preserve_paths?: string[],
- * required_package_paths?: string[]
- * } $config
- */
- public function __construct(array $config)
- {
- $this->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;
- }
- }
|