]> BookStack Code Mirror - bookstack/blob - app/Uploads/FileStorage.php
e6ac368d000c20cd33c4b038438c5cc12228ec7a
[bookstack] / app / Uploads / FileStorage.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Exceptions\FileUploadException;
6 use Exception;
7 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
8 use Illuminate\Filesystem\FilesystemAdapter;
9 use Illuminate\Filesystem\FilesystemManager;
10 use Illuminate\Support\Facades\Log;
11 use Illuminate\Support\Str;
12 use League\Flysystem\WhitespacePathNormalizer;
13 use Symfony\Component\HttpFoundation\File\UploadedFile;
14
15 class FileStorage
16 {
17     public function __construct(
18         protected FilesystemManager $fileSystem,
19     ) {
20     }
21
22     /**
23      * @return resource|null
24      */
25     public function getReadStream(string $path)
26     {
27         return $this->getStorageDisk()->readStream($this->adjustPathForStorageDisk($path));
28     }
29
30     public function getSize(string $path): int
31     {
32         return $this->getStorageDisk()->size($this->adjustPathForStorageDisk($path));
33     }
34
35     public function delete(string $path, bool $removeEmptyDir = false): void
36     {
37         $storage = $this->getStorageDisk();
38         $adjustedPath = $this->adjustPathForStorageDisk($path);
39         $dir = dirname($adjustedPath);
40
41         $storage->delete($adjustedPath);
42         if ($removeEmptyDir && count($storage->allFiles($dir)) === 0) {
43             $storage->deleteDirectory($dir);
44         }
45     }
46
47     /**
48      * @throws FileUploadException
49      */
50     public function uploadFile(UploadedFile $file, string $subDirectory, string $suffix, string $extension): string
51     {
52         $storage = $this->getStorageDisk();
53         $basePath = trim($subDirectory, '/') . '/';
54
55         $uploadFileName = Str::random(16) . ($suffix ? "-{$suffix}" : '') . ($extension ? ".{$extension}" : '');
56         while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) {
57             $uploadFileName = Str::random(3) . $uploadFileName;
58         }
59
60         $fileStream = fopen($file->getRealPath(), 'r');
61         $filePath = $basePath . $uploadFileName;
62
63         try {
64             $storage->writeStream($this->adjustPathForStorageDisk($filePath), $fileStream);
65         } catch (Exception $e) {
66             Log::error('Error when attempting file upload:' . $e->getMessage());
67
68             throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $filePath]));
69         }
70
71         return $filePath;
72     }
73
74     /**
75      * Check whether the configured storage is remote from the host of this app.
76      */
77     public function isRemote(): bool
78     {
79         return $this->getStorageDiskName() === 's3';
80     }
81
82     /**
83      * Get the actual path on system for the given relative file path.
84      */
85     public function getSystemPath(string $filePath): string
86     {
87         if ($this->isRemote()) {
88             return '';
89         }
90
91         return storage_path('uploads/files/' . ltrim($this->adjustPathForStorageDisk($filePath), '/'));
92     }
93
94     /**
95      * Get the storage that will be used for storing files.
96      */
97     protected function getStorageDisk(): Storage
98     {
99         return $this->fileSystem->disk($this->getStorageDiskName());
100     }
101
102     /**
103      * Get the name of the storage disk to use.
104      */
105     protected function getStorageDiskName(): string
106     {
107         $storageType = trim(strtolower(config('filesystems.attachments')));
108
109         // Change to our secure-attachment disk if any of the local options
110         // are used to prevent escaping that location.
111         if ($storageType === 'local' || $storageType === 'local_secure' || $storageType === 'local_secure_restricted') {
112             $storageType = 'local_secure_attachments';
113         }
114
115         return $storageType;
116     }
117
118     /**
119      * Change the originally provided path to fit any disk-specific requirements.
120      * This also ensures the path is kept to the expected root folders.
121      */
122     protected function adjustPathForStorageDisk(string $path): string
123     {
124         $path = (new WhitespacePathNormalizer())->normalizePath(str_replace('uploads/files/', '', $path));
125
126         if ($this->getStorageDiskName() === 'local_secure_attachments') {
127             return $path;
128         }
129
130         return 'uploads/files/' . $path;
131     }
132 }