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\Facades\Log;
11 use Illuminate\Support\Str;
12 use League\Flysystem\Util;
13 use Symfony\Component\HttpFoundation\File\UploadedFile;
15 class AttachmentService
17 protected $fileSystem;
20 * AttachmentService constructor.
22 public function __construct(FileSystem $fileSystem)
24 $this->fileSystem = $fileSystem;
28 * Get the storage that will be used for storing files.
30 protected function getStorage(): FileSystemInstance
32 return $this->fileSystem->disk($this->getStorageDiskName());
36 * Get the name of the storage disk to use.
38 protected function getStorageDiskName(): string
40 $storageType = config('filesystems.attachments');
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';
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.
55 protected function adjustPathForStorageDisk(string $path): string
57 $path = Util::normalizePath(str_replace('uploads/files/', '', $path));
59 if ($this->getStorageDiskName() === 'local_secure_attachments') {
63 return 'uploads/files/' . $path;
67 * Get an attachment from storage.
69 * @throws FileNotFoundException
71 public function getAttachmentFromStorage(Attachment $attachment): string
73 return $this->getStorage()->get($this->adjustPathForStorageDisk($attachment->path));
77 * Store a new attachment upon user upload.
79 * @throws FileUploadException
81 public function saveNewUpload(UploadedFile $uploadedFile, int $pageId): Attachment
83 $attachmentName = $uploadedFile->getClientOriginalName();
84 $attachmentPath = $this->putFileInStorage($uploadedFile);
85 $largestExistingOrder = Attachment::query()->where('uploaded_to', '=', $pageId)->max('order');
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,
102 * Store an upload, saving to a file and deleting any existing uploads
103 * attached to that file.
105 * @throws FileUploadException
107 public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment): Attachment
109 if (!$attachment->external) {
110 $this->deleteFileInStorage($attachment);
113 $attachmentName = $uploadedFile->getClientOriginalName();
114 $attachmentPath = $this->putFileInStorage($uploadedFile);
116 $attachment->name = $attachmentName;
117 $attachment->path = $attachmentPath;
118 $attachment->external = false;
119 $attachment->extension = $uploadedFile->getClientOriginalExtension();
126 * Save a new File attachment from a given link and name.
128 public function saveNewFromLink(string $name, string $link, int $page_id): Attachment
130 $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
132 return Attachment::forceCreate([
137 'uploaded_to' => $page_id,
138 'created_by' => user()->id,
139 'updated_by' => user()->id,
140 'order' => $largestExistingOrder + 1,
145 * Updates the ordering for a listing of attached files.
147 public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId)
149 foreach ($attachmentOrder as $index => $attachmentId) {
150 Attachment::query()->where('uploaded_to', '=', $pageId)
151 ->where('id', '=', $attachmentId)
152 ->update(['order' => $index]);
157 * Update the details of a file.
159 public function updateFile(Attachment $attachment, array $requestData): Attachment
161 $attachment->name = $requestData['name'];
162 $link = trim($requestData['link'] ?? '');
165 if (!$attachment->external) {
166 $this->deleteFileInStorage($attachment);
167 $attachment->external = true;
168 $attachment->extension = '';
170 $attachment->path = $requestData['link'];
174 return $attachment->refresh();
178 * Delete a File from the database and storage.
182 public function deleteFile(Attachment $attachment)
184 if (!$attachment->external) {
185 $this->deleteFileInStorage($attachment);
188 $attachment->delete();
192 * Delete a file from the filesystem it sits on.
193 * Cleans any empty leftover folders.
195 protected function deleteFileInStorage(Attachment $attachment)
197 $storage = $this->getStorage();
198 $dirPath = $this->adjustPathForStorageDisk(dirname($attachment->path));
200 $storage->delete($this->adjustPathForStorageDisk($attachment->path));
201 if (count($storage->allFiles($dirPath)) === 0) {
202 $storage->deleteDirectory($dirPath);
207 * Store a file in storage with the given filename.
209 * @throws FileUploadException
211 protected function putFileInStorage(UploadedFile $uploadedFile): string
213 $attachmentData = file_get_contents($uploadedFile->getRealPath());
215 $storage = $this->getStorage();
216 $basePath = 'uploads/files/' . date('Y-m-M') . '/';
218 $uploadFileName = Str::random(16) . '.' . $uploadedFile->getClientOriginalExtension();
219 while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) {
220 $uploadFileName = Str::random(3) . $uploadFileName;
223 $attachmentPath = $basePath . $uploadFileName;
226 $storage->put($this->adjustPathForStorageDisk($attachmentPath), $attachmentData);
227 } catch (Exception $e) {
228 Log::error('Error when attempting file upload:' . $e->getMessage());
230 throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
233 return $attachmentPath;