]> BookStack Code Mirror - bookstack/blob - app/Uploads/AttachmentService.php
52954d24f976853b4e8cc8baf0adac8d93e0933e
[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\Factory as FileSystem;
8 use Illuminate\Contracts\Filesystem\FileNotFoundException;
9 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
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 $fileSystem;
18
19     /**
20      * AttachmentService constructor.
21      */
22     public function __construct(FileSystem $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(): FileSystemInstance
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      * Store a new attachment upon user upload.
78      *
79      * @throws FileUploadException
80      */
81     public function saveNewUpload(UploadedFile $uploadedFile, int $pageId): Attachment
82     {
83         $attachmentName = $uploadedFile->getClientOriginalName();
84         $attachmentPath = $this->putFileInStorage($uploadedFile);
85         $largestExistingOrder = Attachment::query()->where('uploaded_to', '=', $pageId)->max('order');
86
87         /** @var Attachment $attachment */
88         $attachment = Attachment::query()->forceCreate([
89             'name'        => $attachmentName,
90             'path'        => $attachmentPath,
91             'extension'   => $uploadedFile->getClientOriginalExtension(),
92             'uploaded_to' => $pageId,
93             'created_by'  => user()->id,
94             'updated_by'  => user()->id,
95             'order'       => $largestExistingOrder + 1,
96         ]);
97
98         return $attachment;
99     }
100
101     /**
102      * Store an upload, saving to a file and deleting any existing uploads
103      * attached to that file.
104      *
105      * @throws FileUploadException
106      */
107     public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment): Attachment
108     {
109         if (!$attachment->external) {
110             $this->deleteFileInStorage($attachment);
111         }
112
113         $attachmentName = $uploadedFile->getClientOriginalName();
114         $attachmentPath = $this->putFileInStorage($uploadedFile);
115
116         $attachment->name = $attachmentName;
117         $attachment->path = $attachmentPath;
118         $attachment->external = false;
119         $attachment->extension = $uploadedFile->getClientOriginalExtension();
120         $attachment->save();
121
122         return $attachment;
123     }
124
125     /**
126      * Save a new File attachment from a given link and name.
127      */
128     public function saveNewFromLink(string $name, string $link, int $page_id): Attachment
129     {
130         $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
131
132         return Attachment::forceCreate([
133             'name'        => $name,
134             'path'        => $link,
135             'external'    => true,
136             'extension'   => '',
137             'uploaded_to' => $page_id,
138             'created_by'  => user()->id,
139             'updated_by'  => user()->id,
140             'order'       => $largestExistingOrder + 1,
141         ]);
142     }
143
144     /**
145      * Updates the ordering for a listing of attached files.
146      */
147     public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId)
148     {
149         foreach ($attachmentOrder as $index => $attachmentId) {
150             Attachment::query()->where('uploaded_to', '=', $pageId)
151                 ->where('id', '=', $attachmentId)
152                 ->update(['order' => $index]);
153         }
154     }
155
156     /**
157      * Update the details of a file.
158      */
159     public function updateFile(Attachment $attachment, array $requestData): Attachment
160     {
161         $attachment->name = $requestData['name'];
162         $link = trim($requestData['link'] ?? '');
163
164         if (!empty($link)) {
165             if (!$attachment->external) {
166                 $this->deleteFileInStorage($attachment);
167                 $attachment->external = true;
168                 $attachment->extension = '';
169             }
170             $attachment->path = $requestData['link'];
171         }
172
173         $attachment->save();
174
175         return $attachment->refresh();
176     }
177
178     /**
179      * Delete a File from the database and storage.
180      *
181      * @throws Exception
182      */
183     public function deleteFile(Attachment $attachment)
184     {
185         if (!$attachment->external) {
186             $this->deleteFileInStorage($attachment);
187         }
188
189         $attachment->delete();
190     }
191
192     /**
193      * Delete a file from the filesystem it sits on.
194      * Cleans any empty leftover folders.
195      */
196     protected function deleteFileInStorage(Attachment $attachment)
197     {
198         $storage = $this->getStorageDisk();
199         $dirPath = $this->adjustPathForStorageDisk(dirname($attachment->path));
200
201         $storage->delete($this->adjustPathForStorageDisk($attachment->path));
202         if (count($storage->allFiles($dirPath)) === 0) {
203             $storage->deleteDirectory($dirPath);
204         }
205     }
206
207     /**
208      * Store a file in storage with the given filename.
209      *
210      * @throws FileUploadException
211      */
212     protected function putFileInStorage(UploadedFile $uploadedFile): string
213     {
214         $attachmentData = file_get_contents($uploadedFile->getRealPath());
215
216         $storage = $this->getStorageDisk();
217         $basePath = 'uploads/files/' . date('Y-m-M') . '/';
218
219         $uploadFileName = Str::random(16) . '-' . $uploadedFile->getClientOriginalExtension();
220         while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) {
221             $uploadFileName = Str::random(3) . $uploadFileName;
222         }
223
224         $attachmentPath = $basePath . $uploadFileName;
225
226         try {
227             $storage->put($this->adjustPathForStorageDisk($attachmentPath), $attachmentData);
228         } catch (Exception $e) {
229             Log::error('Error when attempting file upload:' . $e->getMessage());
230
231             throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
232         }
233
234         return $attachmentPath;
235     }
236 }