3 namespace BookStack\Uploads;
5 use BookStack\Exceptions\FileUploadException;
7 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
8 use Illuminate\Filesystem\FilesystemManager;
9 use Illuminate\Support\Facades\Log;
10 use Illuminate\Support\Str;
11 use League\Flysystem\WhitespacePathNormalizer;
12 use Symfony\Component\HttpFoundation\File\UploadedFile;
14 class AttachmentService
16 protected FilesystemManager $fileSystem;
19 * AttachmentService constructor.
21 public function __construct(FilesystemManager $fileSystem)
23 $this->fileSystem = $fileSystem;
27 * Get the storage that will be used for storing files.
29 protected function getStorageDisk(): Storage
31 return $this->fileSystem->disk($this->getStorageDiskName());
35 * Get the name of the storage disk to use.
37 protected function getStorageDiskName(): string
39 $storageType = config('filesystems.attachments');
41 // Change to our secure-attachment disk if any of the local options
42 // are used to prevent escaping that location.
43 if ($storageType === 'local' || $storageType === 'local_secure' || $storageType === 'local_secure_restricted') {
44 $storageType = 'local_secure_attachments';
51 * Change the originally provided path to fit any disk-specific requirements.
52 * This also ensures the path is kept to the expected root folders.
54 protected function adjustPathForStorageDisk(string $path): string
56 $path = (new WhitespacePathNormalizer())->normalizePath(str_replace('uploads/files/', '', $path));
58 if ($this->getStorageDiskName() === 'local_secure_attachments') {
62 return 'uploads/files/' . $path;
66 * Stream an attachment from storage.
68 * @return resource|null
70 public function streamAttachmentFromStorage(Attachment $attachment)
72 return $this->getStorageDisk()->readStream($this->adjustPathForStorageDisk($attachment->path));
76 * Read the file size of an attachment from storage, in bytes.
78 public function getAttachmentFileSize(Attachment $attachment): int
80 return $this->getStorageDisk()->size($this->adjustPathForStorageDisk($attachment->path));
84 * Store a new attachment upon user upload.
86 * @throws FileUploadException
88 public function saveNewUpload(UploadedFile $uploadedFile, int $pageId): Attachment
90 $attachmentName = $uploadedFile->getClientOriginalName();
91 $attachmentPath = $this->putFileInStorage($uploadedFile);
92 $largestExistingOrder = Attachment::query()->where('uploaded_to', '=', $pageId)->max('order');
94 /** @var Attachment $attachment */
95 $attachment = Attachment::query()->forceCreate([
96 'name' => $attachmentName,
97 'path' => $attachmentPath,
98 'extension' => $uploadedFile->getClientOriginalExtension(),
99 'uploaded_to' => $pageId,
100 'created_by' => user()->id,
101 'updated_by' => user()->id,
102 'order' => $largestExistingOrder + 1,
109 * Store an upload, saving to a file and deleting any existing uploads
110 * attached to that file.
112 * @throws FileUploadException
114 public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment): Attachment
116 if (!$attachment->external) {
117 $this->deleteFileInStorage($attachment);
120 $attachmentName = $uploadedFile->getClientOriginalName();
121 $attachmentPath = $this->putFileInStorage($uploadedFile);
123 $attachment->name = $attachmentName;
124 $attachment->path = $attachmentPath;
125 $attachment->external = false;
126 $attachment->extension = $uploadedFile->getClientOriginalExtension();
133 * Save a new File attachment from a given link and name.
135 public function saveNewFromLink(string $name, string $link, int $page_id): Attachment
137 $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
139 return Attachment::forceCreate([
144 'uploaded_to' => $page_id,
145 'created_by' => user()->id,
146 'updated_by' => user()->id,
147 'order' => $largestExistingOrder + 1,
152 * Updates the ordering for a listing of attached files.
154 public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId)
156 foreach ($attachmentOrder as $index => $attachmentId) {
157 Attachment::query()->where('uploaded_to', '=', $pageId)
158 ->where('id', '=', $attachmentId)
159 ->update(['order' => $index]);
164 * Update the details of a file.
166 public function updateFile(Attachment $attachment, array $requestData): Attachment
168 $attachment->name = $requestData['name'];
169 $link = trim($requestData['link'] ?? '');
172 if (!$attachment->external) {
173 $this->deleteFileInStorage($attachment);
174 $attachment->external = true;
175 $attachment->extension = '';
177 $attachment->path = $requestData['link'];
182 return $attachment->refresh();
186 * Delete a File from the database and storage.
190 public function deleteFile(Attachment $attachment)
192 if (!$attachment->external) {
193 $this->deleteFileInStorage($attachment);
196 $attachment->delete();
200 * Delete a file from the filesystem it sits on.
201 * Cleans any empty leftover folders.
203 protected function deleteFileInStorage(Attachment $attachment)
205 $storage = $this->getStorageDisk();
206 $dirPath = $this->adjustPathForStorageDisk(dirname($attachment->path));
208 $storage->delete($this->adjustPathForStorageDisk($attachment->path));
209 if (count($storage->allFiles($dirPath)) === 0) {
210 $storage->deleteDirectory($dirPath);
215 * Store a file in storage with the given filename.
217 * @throws FileUploadException
219 protected function putFileInStorage(UploadedFile $uploadedFile): string
221 $storage = $this->getStorageDisk();
222 $basePath = 'uploads/files/' . date('Y-m-M') . '/';
224 $uploadFileName = Str::random(16) . '-' . $uploadedFile->getClientOriginalExtension();
225 while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) {
226 $uploadFileName = Str::random(3) . $uploadFileName;
229 $attachmentStream = fopen($uploadedFile->getRealPath(), 'r');
230 $attachmentPath = $basePath . $uploadFileName;
233 $storage->writeStream($this->adjustPathForStorageDisk($attachmentPath), $attachmentStream);
234 } catch (Exception $e) {
235 Log::error('Error when attempting file upload:' . $e->getMessage());
237 throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
240 return $attachmentPath;
244 * Get the file validation rules for attachments.
246 public function getFileValidationRules(): array
248 return ['file', 'max:' . (config('app.upload_limit') * 1000)];