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