]> BookStack Code Mirror - bookstack/blob - app/Uploads/AttachmentService.php
Added streamed uploads for attachments
[bookstack] / app / Uploads / AttachmentService.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Exceptions\FileUploadException;
6 use Exception;
7 use Illuminate\Contracts\Filesystem\FileNotFoundException;
8 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
9 use Illuminate\Filesystem\FilesystemManager;
10 use Illuminate\Support\Facades\Log;
11 use Illuminate\Support\Str;
12 use League\Flysystem\Util;
13 use Symfony\Component\HttpFoundation\File\UploadedFile;
14
15 class AttachmentService
16 {
17     protected FilesystemManager $fileSystem;
18
19     /**
20      * AttachmentService constructor.
21      */
22     public function __construct(FilesystemManager $fileSystem)
23     {
24         $this->fileSystem = $fileSystem;
25     }
26
27     /**
28      * Get the storage that will be used for storing files.
29      */
30     protected function getStorageDisk(): Storage
31     {
32         return $this->fileSystem->disk($this->getStorageDiskName());
33     }
34
35     /**
36      * Get the name of the storage disk to use.
37      */
38     protected function getStorageDiskName(): string
39     {
40         $storageType = config('filesystems.attachments');
41
42         // Change to our secure-attachment disk if any of the local options
43         // are used to prevent escaping that location.
44         if ($storageType === 'local' || $storageType === 'local_secure') {
45             $storageType = 'local_secure_attachments';
46         }
47
48         return $storageType;
49     }
50
51     /**
52      * Change the originally provided path to fit any disk-specific requirements.
53      * This also ensures the path is kept to the expected root folders.
54      */
55     protected function adjustPathForStorageDisk(string $path): string
56     {
57         $path = Util::normalizePath(str_replace('uploads/files/', '', $path));
58
59         if ($this->getStorageDiskName() === 'local_secure_attachments') {
60             return $path;
61         }
62
63         return 'uploads/files/' . $path;
64     }
65
66     /**
67      * Get an attachment from storage.
68      *
69      * @throws FileNotFoundException
70      */
71     public function getAttachmentFromStorage(Attachment $attachment): string
72     {
73         return $this->getStorageDisk()->get($this->adjustPathForStorageDisk($attachment->path));
74     }
75
76     /**
77      * Stream an attachment from storage.
78      *
79      * @return resource|null
80      * @throws FileNotFoundException
81      */
82     public function streamAttachmentFromStorage(Attachment $attachment)
83     {
84
85         return $this->getStorageDisk()->readStream($this->adjustPathForStorageDisk($attachment->path));
86     }
87
88     /**
89      * Store a new attachment upon user upload.
90      *
91      * @throws FileUploadException
92      */
93     public function saveNewUpload(UploadedFile $uploadedFile, int $pageId): Attachment
94     {
95         $attachmentName = $uploadedFile->getClientOriginalName();
96         $attachmentPath = $this->putFileInStorage($uploadedFile);
97         $largestExistingOrder = Attachment::query()->where('uploaded_to', '=', $pageId)->max('order');
98
99         /** @var Attachment $attachment */
100         $attachment = Attachment::query()->forceCreate([
101             'name'        => $attachmentName,
102             'path'        => $attachmentPath,
103             'extension'   => $uploadedFile->getClientOriginalExtension(),
104             'uploaded_to' => $pageId,
105             'created_by'  => user()->id,
106             'updated_by'  => user()->id,
107             'order'       => $largestExistingOrder + 1,
108         ]);
109
110         return $attachment;
111     }
112
113     /**
114      * Store an upload, saving to a file and deleting any existing uploads
115      * attached to that file.
116      *
117      * @throws FileUploadException
118      */
119     public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment): Attachment
120     {
121         if (!$attachment->external) {
122             $this->deleteFileInStorage($attachment);
123         }
124
125         $attachmentName = $uploadedFile->getClientOriginalName();
126         $attachmentPath = $this->putFileInStorage($uploadedFile);
127
128         $attachment->name = $attachmentName;
129         $attachment->path = $attachmentPath;
130         $attachment->external = false;
131         $attachment->extension = $uploadedFile->getClientOriginalExtension();
132         $attachment->save();
133
134         return $attachment;
135     }
136
137     /**
138      * Save a new File attachment from a given link and name.
139      */
140     public function saveNewFromLink(string $name, string $link, int $page_id): Attachment
141     {
142         $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
143
144         return Attachment::forceCreate([
145             'name'        => $name,
146             'path'        => $link,
147             'external'    => true,
148             'extension'   => '',
149             'uploaded_to' => $page_id,
150             'created_by'  => user()->id,
151             'updated_by'  => user()->id,
152             'order'       => $largestExistingOrder + 1,
153         ]);
154     }
155
156     /**
157      * Updates the ordering for a listing of attached files.
158      */
159     public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId)
160     {
161         foreach ($attachmentOrder as $index => $attachmentId) {
162             Attachment::query()->where('uploaded_to', '=', $pageId)
163                 ->where('id', '=', $attachmentId)
164                 ->update(['order' => $index]);
165         }
166     }
167
168     /**
169      * Update the details of a file.
170      */
171     public function updateFile(Attachment $attachment, array $requestData): Attachment
172     {
173         $attachment->name = $requestData['name'];
174         $link = trim($requestData['link'] ?? '');
175
176         if (!empty($link)) {
177             if (!$attachment->external) {
178                 $this->deleteFileInStorage($attachment);
179                 $attachment->external = true;
180                 $attachment->extension = '';
181             }
182             $attachment->path = $requestData['link'];
183         }
184
185         $attachment->save();
186
187         return $attachment->refresh();
188     }
189
190     /**
191      * Delete a File from the database and storage.
192      *
193      * @throws Exception
194      */
195     public function deleteFile(Attachment $attachment)
196     {
197         if (!$attachment->external) {
198             $this->deleteFileInStorage($attachment);
199         }
200
201         $attachment->delete();
202     }
203
204     /**
205      * Delete a file from the filesystem it sits on.
206      * Cleans any empty leftover folders.
207      */
208     protected function deleteFileInStorage(Attachment $attachment)
209     {
210         $storage = $this->getStorageDisk();
211         $dirPath = $this->adjustPathForStorageDisk(dirname($attachment->path));
212
213         $storage->delete($this->adjustPathForStorageDisk($attachment->path));
214         if (count($storage->allFiles($dirPath)) === 0) {
215             $storage->deleteDirectory($dirPath);
216         }
217     }
218
219     /**
220      * Store a file in storage with the given filename.
221      *
222      * @throws FileUploadException
223      */
224     protected function putFileInStorage(UploadedFile $uploadedFile): string
225     {
226         $storage = $this->getStorageDisk();
227         $basePath = 'uploads/files/' . date('Y-m-M') . '/';
228
229         $uploadFileName = Str::random(16) . '-' . $uploadedFile->getClientOriginalExtension();
230         while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) {
231             $uploadFileName = Str::random(3) . $uploadFileName;
232         }
233
234         $attachmentStream = fopen($uploadedFile->getRealPath(), 'r');
235         $attachmentPath = $basePath . $uploadFileName;
236
237         try {
238             $storage->writeStream($this->adjustPathForStorageDisk($attachmentPath), $attachmentStream);
239         } catch (Exception $e) {
240             Log::error('Error when attempting file upload:' . $e->getMessage());
241
242             throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
243         }
244
245         return $attachmentPath;
246     }
247
248     /**
249      * Get the file validation rules for attachments.
250      */
251     public function getFileValidationRules(): array
252     {
253         return ['file', 'max:' . (config('app.upload_limit') * 1000)];
254     }
255 }