]> BookStack Code Mirror - bookstack/blob - app/Uploads/AttachmentService.php
Update dompdf.php
[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 getStorage(): 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->getStorage()->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 $page_id): Attachment
82     {
83         $attachmentName = $uploadedFile->getClientOriginalName();
84         $attachmentPath = $this->putFileInStorage($uploadedFile);
85         $largestExistingOrder = Attachment::query()->where('uploaded_to', '=', $page_id)->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' => $page_id,
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
163         if (isset($requestData['link']) && trim($requestData['link']) !== '') {
164             $attachment->path = $requestData['link'];
165             if (!$attachment->external) {
166                 $this->deleteFileInStorage($attachment);
167                 $attachment->external = true;
168             }
169         }
170
171         $attachment->save();
172
173         return $attachment;
174     }
175
176     /**
177      * Delete a File from the database and storage.
178      *
179      * @throws Exception
180      */
181     public function deleteFile(Attachment $attachment)
182     {
183         if ($attachment->external) {
184             $attachment->delete();
185
186             return;
187         }
188
189         $this->deleteFileInStorage($attachment);
190         $attachment->delete();
191     }
192
193     /**
194      * Delete a file from the filesystem it sits on.
195      * Cleans any empty leftover folders.
196      */
197     protected function deleteFileInStorage(Attachment $attachment)
198     {
199         $storage = $this->getStorage();
200         $dirPath = $this->adjustPathForStorageDisk(dirname($attachment->path));
201
202         $storage->delete($this->adjustPathForStorageDisk($attachment->path));
203         if (count($storage->allFiles($dirPath)) === 0) {
204             $storage->deleteDirectory($dirPath);
205         }
206     }
207
208     /**
209      * Store a file in storage with the given filename.
210      *
211      * @throws FileUploadException
212      */
213     protected function putFileInStorage(UploadedFile $uploadedFile): string
214     {
215         $attachmentData = file_get_contents($uploadedFile->getRealPath());
216
217         $storage = $this->getStorage();
218         $basePath = 'uploads/files/' . date('Y-m-M') . '/';
219
220         $uploadFileName = Str::random(16) . '.' . $uploadedFile->getClientOriginalExtension();
221         while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) {
222             $uploadFileName = Str::random(3) . $uploadFileName;
223         }
224
225         $attachmentPath = $basePath . $uploadFileName;
226
227         try {
228             $storage->put($this->adjustPathForStorageDisk($attachmentPath), $attachmentData);
229         } catch (Exception $e) {
230             Log::error('Error when attempting file upload:' . $e->getMessage());
231
232             throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
233         }
234
235         return $attachmentPath;
236     }
237 }