]> BookStack Code Mirror - bookstack/blob - app/Uploads/AttachmentService.php
Merge branch 'create-content-meta-tags' of https://github.com/james-geiger/BookStack...
[bookstack] / app / Uploads / AttachmentService.php
1 <?php namespace BookStack\Uploads;
2
3 use BookStack\Exceptions\FileUploadException;
4 use Exception;
5 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
6 use Illuminate\Contracts\Filesystem\FileNotFoundException;
7 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
8 use Illuminate\Support\Str;
9 use Log;
10 use Symfony\Component\HttpFoundation\File\UploadedFile;
11
12 class AttachmentService
13 {
14
15     protected $fileSystem;
16
17     /**
18      * AttachmentService constructor.
19      */
20     public function __construct(FileSystem $fileSystem)
21     {
22         $this->fileSystem = $fileSystem;
23     }
24
25
26     /**
27      * Get the storage that will be used for storing files.
28      */
29     protected function getStorage(): FileSystemInstance
30     {
31         $storageType = config('filesystems.attachments');
32
33         // Override default location if set to local public to ensure not visible.
34         if ($storageType === 'local') {
35             $storageType = 'local_secure';
36         }
37
38         return $this->fileSystem->disk($storageType);
39     }
40
41     /**
42      * Get an attachment from storage.
43      * @throws FileNotFoundException
44      */
45     public function getAttachmentFromStorage(Attachment $attachment): string
46     {
47         return $this->getStorage()->get($attachment->path);
48     }
49
50     /**
51      * Store a new attachment upon user upload.
52      * @param UploadedFile $uploadedFile
53      * @param int $page_id
54      * @return Attachment
55      * @throws FileUploadException
56      */
57     public function saveNewUpload(UploadedFile $uploadedFile, $page_id)
58     {
59         $attachmentName = $uploadedFile->getClientOriginalName();
60         $attachmentPath = $this->putFileInStorage($uploadedFile);
61         $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
62
63         $attachment = Attachment::forceCreate([
64             'name' => $attachmentName,
65             'path' => $attachmentPath,
66             'extension' => $uploadedFile->getClientOriginalExtension(),
67             'uploaded_to' => $page_id,
68             'created_by' => user()->id,
69             'updated_by' => user()->id,
70             'order' => $largestExistingOrder + 1
71         ]);
72
73         return $attachment;
74     }
75
76     /**
77      * Store a upload, saving to a file and deleting any existing uploads
78      * attached to that file.
79      * @param UploadedFile $uploadedFile
80      * @param Attachment $attachment
81      * @return Attachment
82      * @throws FileUploadException
83      */
84     public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment)
85     {
86         if (!$attachment->external) {
87             $this->deleteFileInStorage($attachment);
88         }
89
90         $attachmentName = $uploadedFile->getClientOriginalName();
91         $attachmentPath = $this->putFileInStorage($uploadedFile);
92
93         $attachment->name = $attachmentName;
94         $attachment->path = $attachmentPath;
95         $attachment->external = false;
96         $attachment->extension = $uploadedFile->getClientOriginalExtension();
97         $attachment->save();
98         return $attachment;
99     }
100
101     /**
102      * Save a new File attachment from a given link and name.
103      */
104     public function saveNewFromLink(string $name, string $link, int $page_id): Attachment
105     {
106         $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
107         return Attachment::forceCreate([
108             'name' => $name,
109             'path' => $link,
110             'external' => true,
111             'extension' => '',
112             'uploaded_to' => $page_id,
113             'created_by' => user()->id,
114             'updated_by' => user()->id,
115             'order' => $largestExistingOrder + 1
116         ]);
117     }
118
119     /**
120      * Updates the ordering for a listing of attached files.
121      */
122     public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId)
123     {
124         foreach ($attachmentOrder as $index => $attachmentId) {
125             Attachment::query()->where('uploaded_to', '=', $pageId)
126                 ->where('id', '=', $attachmentId)
127                 ->update(['order' => $index]);
128         }
129     }
130
131
132     /**
133      * Update the details of a file.
134      */
135     public function updateFile(Attachment $attachment, array $requestData): Attachment
136     {
137         $attachment->name = $requestData['name'];
138
139         if (isset($requestData['link']) && trim($requestData['link']) !== '') {
140             $attachment->path = $requestData['link'];
141             if (!$attachment->external) {
142                 $this->deleteFileInStorage($attachment);
143                 $attachment->external = true;
144             }
145         }
146
147         $attachment->save();
148         return $attachment;
149     }
150
151     /**
152      * Delete a File from the database and storage.
153      * @param Attachment $attachment
154      * @throws Exception
155      */
156     public function deleteFile(Attachment $attachment)
157     {
158         if ($attachment->external) {
159             $attachment->delete();
160             return;
161         }
162         
163         $this->deleteFileInStorage($attachment);
164         $attachment->delete();
165     }
166
167     /**
168      * Delete a file from the filesystem it sits on.
169      * Cleans any empty leftover folders.
170      * @param Attachment $attachment
171      */
172     protected function deleteFileInStorage(Attachment $attachment)
173     {
174         $storage = $this->getStorage();
175         $dirPath = dirname($attachment->path);
176
177         $storage->delete($attachment->path);
178         if (count($storage->allFiles($dirPath)) === 0) {
179             $storage->deleteDirectory($dirPath);
180         }
181     }
182
183     /**
184      * Store a file in storage with the given filename
185      * @param UploadedFile $uploadedFile
186      * @return string
187      * @throws FileUploadException
188      */
189     protected function putFileInStorage(UploadedFile $uploadedFile)
190     {
191         $attachmentData = file_get_contents($uploadedFile->getRealPath());
192
193         $storage = $this->getStorage();
194         $basePath = 'uploads/files/' . Date('Y-m-M') . '/';
195
196         $uploadFileName = Str::random(16) . '.' . $uploadedFile->getClientOriginalExtension();
197         while ($storage->exists($basePath . $uploadFileName)) {
198             $uploadFileName = Str::random(3) . $uploadFileName;
199         }
200
201         $attachmentPath = $basePath . $uploadFileName;
202         try {
203             $storage->put($attachmentPath, $attachmentData);
204         } catch (Exception $e) {
205             Log::error('Error when attempting file upload:' . $e->getMessage());
206             throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
207         }
208
209         return $attachmentPath;
210     }
211 }