summaryrefslogtreecommitdiff
path: root/src/Services/VendorDownloader.php
blob: 389baf2b9b3ecc504033ece500e092441fdd1a44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
<?php declare(strict_types=1);

namespace Cli\Services;

use Cli\Commands\CommandError;
use Exception;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Symfony\Component\Console\Output\OutputInterface;
use ZipArchive;

class VendorDownloader
{
    public function __construct(
        protected string $appDir,
        protected OutputInterface $output
    ) {}

    public function download(): void
    {
        $this->output->writeln("<info>Checking app version...</info>");
        $version = AppLocator::getVersion($this->appDir);
        if (empty($version)) {
            throw new CommandError("Could not determine instance BookStack version.");
        }
        $targetChecksum = $this->getTargetChecksum();

        $this->output->writeln("<info>Downloading ZIP from files.bookstackapp.com...</info>");
        $zip = $this->downloadVendorZip($version);

        $this->output->writeln("<info>Validating downloaded ZIP...</info>");
        $this->verifyZipChecksum($zip, $targetChecksum);

        $this->output->writeln("<info>Deleting existing vendor/ directory...</info>");
        try {
            $this->deleteAppVendorFiles();
        } catch (Exception $exception) {
            unlink($zip);
            throw $exception;
        }

        $this->output->writeln("<info>Extracting ZIP into BookStack instance...</info>");
        $this->extractZip($zip);

        $this->output->writeln("<info>Cleaning up old app services...</info>");
        $cleaned = $this->cleanupAppServices();
        if (!$cleaned) {
            $this->output->writeln("<warning>Failed to remove exising app services file</warning>");
        }

        $this->output->writeln("<success>Successfully downloaded & extracted vendor files into BookStack instance!</success>");
    }

    protected function cleanupAppServices(): bool
    {
        $filesToClear = [
            implode(DIRECTORY_SEPARATOR, [$this->appDir, 'bootstrap', 'cache', 'services.php']),
            implode(DIRECTORY_SEPARATOR, [$this->appDir, 'bootstrap', 'cache', 'packages.php']),
        ];

        $status = true;

        foreach ($filesToClear as $file) {
            if (file_exists($file)) {
                if (@unlink($file) === false) {
                    $status = false;
                }
            }
        }

        return $status;
    }

    protected function extractZip(string $zipPath): void
    {
        $zip = new ZipArchive();
        $opened = $zip->open($zipPath, ZipArchive::RDONLY);
        $extracted = $zip->extractTo($this->appDir);
        $closed = $zip->close();

        unlink($zipPath);
        if (!$opened || !$extracted || !$closed) {
            throw new CommandError("Failed to extract ZIP files into {$this->appDir}");
        }
    }

    protected function deleteAppVendorFiles(): void
    {
        $targetDir = $this->appDir . DIRECTORY_SEPARATOR . 'vendor';
        if (!is_dir($targetDir)) {
            return;
        }

        $it = new RecursiveDirectoryIterator($targetDir, RecursiveDirectoryIterator::SKIP_DOTS);
        $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
        foreach($files as $file) {
            if ($file->isDir()){
                rmdir($file->getPathname());
            } else {
                unlink($file->getPathname());
            }
        }

        $deleted = rmdir($targetDir);
        if (!$deleted) {
            throw new CommandError("Could not delete existing app vendor directory.");
        }
    }

    protected function verifyZipChecksum(string $zipPath, string $targetChecksum): void
    {
        $zipChecksum = hash_file('sha256', $zipPath);
        if ($zipChecksum !== $targetChecksum) {
            unlink($zipPath);
            throw new CommandError("Checksum of downloaded ZIP does not match the expected checksum.");
        }
    }

    protected function downloadVendorZip(string $version): string
    {
        $tempFile = tempnam(sys_get_temp_dir(), 'bs-cli-vendor-zip');
        $targetUrl = "https://files.bookstackapp.com/vendor/{$version}.zip";

        $targetFile = @fopen($targetUrl, 'rb');
        if ($targetFile === false) {
            throw new CommandError("Failed to download ZIP file from $targetUrl");
        }

        file_put_contents($tempFile, $targetFile);

        return $tempFile;
    }

    /**
     * @throws CommandError
     */
    protected function getTargetChecksum(): string
    {
        $checksumFile = implode(DIRECTORY_SEPARATOR, [$this->appDir, 'dev', 'checksums', 'vendor']);
        $checksum = '';
        if (file_exists($checksumFile)) {
            $checksum = trim(file_get_contents($checksumFile));
        }

        if (empty($checksum)) {
            throw new CommandError("Could not find a vendor checksum for validation.");
        }

        return $checksum;
    }
}