3 namespace BookStack\Uploads;
5 use BookStack\Exceptions\FileUploadException;
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\Str;
12 use Symfony\Component\HttpFoundation\File\UploadedFile;
14 class AttachmentService
16 protected $fileSystem;
19 * AttachmentService constructor.
21 public function __construct(FileSystem $fileSystem)
23 $this->fileSystem = $fileSystem;
27 * Get the storage that will be used for storing files.
29 protected function getStorage(): FileSystemInstance
31 $storageType = config('filesystems.attachments');
33 // Override default location if set to local public to ensure not visible.
34 if ($storageType === 'local') {
35 $storageType = 'local_secure';
38 return $this->fileSystem->disk($storageType);
42 * Get an attachment from storage.
44 * @throws FileNotFoundException
46 public function getAttachmentFromStorage(Attachment $attachment): string
48 return $this->getStorage()->get($attachment->path);
52 * Store a new attachment upon user upload.
54 * @param UploadedFile $uploadedFile
57 * @throws FileUploadException
61 public function saveNewUpload(UploadedFile $uploadedFile, $page_id)
63 $attachmentName = $uploadedFile->getClientOriginalName();
64 $attachmentPath = $this->putFileInStorage($uploadedFile);
65 $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
67 $attachment = Attachment::forceCreate([
68 'name' => $attachmentName,
69 'path' => $attachmentPath,
70 'extension' => $uploadedFile->getClientOriginalExtension(),
71 'uploaded_to' => $page_id,
72 'created_by' => user()->id,
73 'updated_by' => user()->id,
74 'order' => $largestExistingOrder + 1,
81 * Store a upload, saving to a file and deleting any existing uploads
82 * attached to that file.
84 * @param UploadedFile $uploadedFile
85 * @param Attachment $attachment
87 * @throws FileUploadException
91 public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment)
93 if (!$attachment->external) {
94 $this->deleteFileInStorage($attachment);
97 $attachmentName = $uploadedFile->getClientOriginalName();
98 $attachmentPath = $this->putFileInStorage($uploadedFile);
100 $attachment->name = $attachmentName;
101 $attachment->path = $attachmentPath;
102 $attachment->external = false;
103 $attachment->extension = $uploadedFile->getClientOriginalExtension();
110 * Save a new File attachment from a given link and name.
112 public function saveNewFromLink(string $name, string $link, int $page_id): Attachment
114 $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
116 return Attachment::forceCreate([
121 'uploaded_to' => $page_id,
122 'created_by' => user()->id,
123 'updated_by' => user()->id,
124 'order' => $largestExistingOrder + 1,
129 * Updates the ordering for a listing of attached files.
131 public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId)
133 foreach ($attachmentOrder as $index => $attachmentId) {
134 Attachment::query()->where('uploaded_to', '=', $pageId)
135 ->where('id', '=', $attachmentId)
136 ->update(['order' => $index]);
141 * Update the details of a file.
143 public function updateFile(Attachment $attachment, array $requestData): Attachment
145 $attachment->name = $requestData['name'];
147 if (isset($requestData['link']) && trim($requestData['link']) !== '') {
148 $attachment->path = $requestData['link'];
149 if (!$attachment->external) {
150 $this->deleteFileInStorage($attachment);
151 $attachment->external = true;
161 * Delete a File from the database and storage.
163 * @param Attachment $attachment
167 public function deleteFile(Attachment $attachment)
169 if ($attachment->external) {
170 $attachment->delete();
175 $this->deleteFileInStorage($attachment);
176 $attachment->delete();
180 * Delete a file from the filesystem it sits on.
181 * Cleans any empty leftover folders.
183 * @param Attachment $attachment
185 protected function deleteFileInStorage(Attachment $attachment)
187 $storage = $this->getStorage();
188 $dirPath = dirname($attachment->path);
190 $storage->delete($attachment->path);
191 if (count($storage->allFiles($dirPath)) === 0) {
192 $storage->deleteDirectory($dirPath);
197 * Store a file in storage with the given filename.
199 * @param UploadedFile $uploadedFile
201 * @throws FileUploadException
205 protected function putFileInStorage(UploadedFile $uploadedFile)
207 $attachmentData = file_get_contents($uploadedFile->getRealPath());
209 $storage = $this->getStorage();
210 $basePath = 'uploads/files/' . date('Y-m-M') . '/';
212 $uploadFileName = Str::random(16) . '.' . $uploadedFile->getClientOriginalExtension();
213 while ($storage->exists($basePath . $uploadFileName)) {
214 $uploadFileName = Str::random(3) . $uploadFileName;
217 $attachmentPath = $basePath . $uploadFileName;
220 $storage->put($attachmentPath, $attachmentData);
221 } catch (Exception $e) {
222 Log::error('Error when attempting file upload:' . $e->getMessage());
224 throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
227 return $attachmentPath;