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 public function __construct(
17 protected FilesystemManager $fileSystem
22 * Get the storage that will be used for storing files.
24 protected function getStorageDisk(): Storage
26 return $this->fileSystem->disk($this->getStorageDiskName());
30 * Get the name of the storage disk to use.
32 protected function getStorageDiskName(): string
34 $storageType = config('filesystems.attachments');
36 // Change to our secure-attachment disk if any of the local options
37 // are used to prevent escaping that location.
38 if ($storageType === 'local' || $storageType === 'local_secure' || $storageType === 'local_secure_restricted') {
39 $storageType = 'local_secure_attachments';
46 * Change the originally provided path to fit any disk-specific requirements.
47 * This also ensures the path is kept to the expected root folders.
49 protected function adjustPathForStorageDisk(string $path): string
51 $path = (new WhitespacePathNormalizer())->normalizePath(str_replace('uploads/files/', '', $path));
53 if ($this->getStorageDiskName() === 'local_secure_attachments') {
57 return 'uploads/files/' . $path;
61 * Stream an attachment from storage.
63 * @return resource|null
65 public function streamAttachmentFromStorage(Attachment $attachment)
67 return $this->getStorageDisk()->readStream($this->adjustPathForStorageDisk($attachment->path));
71 * Read the file size of an attachment from storage, in bytes.
73 public function getAttachmentFileSize(Attachment $attachment): int
75 return $this->getStorageDisk()->size($this->adjustPathForStorageDisk($attachment->path));
79 * Store a new attachment upon user upload.
81 * @throws FileUploadException
83 public function saveNewUpload(UploadedFile $uploadedFile, int $pageId): Attachment
85 $attachmentName = $uploadedFile->getClientOriginalName();
86 $attachmentPath = $this->putFileInStorage($uploadedFile);
87 $largestExistingOrder = Attachment::query()->where('uploaded_to', '=', $pageId)->max('order');
89 /** @var Attachment $attachment */
90 $attachment = Attachment::query()->forceCreate([
91 'name' => $attachmentName,
92 'path' => $attachmentPath,
93 'extension' => $uploadedFile->getClientOriginalExtension(),
94 'uploaded_to' => $pageId,
95 'created_by' => user()->id,
96 'updated_by' => user()->id,
97 'order' => $largestExistingOrder + 1,
104 * Store an upload, saving to a file and deleting any existing uploads
105 * attached to that file.
107 * @throws FileUploadException
109 public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment): Attachment
111 if (!$attachment->external) {
112 $this->deleteFileInStorage($attachment);
115 $attachmentName = $uploadedFile->getClientOriginalName();
116 $attachmentPath = $this->putFileInStorage($uploadedFile);
118 $attachment->name = $attachmentName;
119 $attachment->path = $attachmentPath;
120 $attachment->external = false;
121 $attachment->extension = $uploadedFile->getClientOriginalExtension();
128 * Save a new File attachment from a given link and name.
130 public function saveNewFromLink(string $name, string $link, int $page_id): Attachment
132 $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
134 return Attachment::forceCreate([
139 'uploaded_to' => $page_id,
140 'created_by' => user()->id,
141 'updated_by' => user()->id,
142 'order' => $largestExistingOrder + 1,
147 * Updates the ordering for a listing of attached files.
149 public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId)
151 foreach ($attachmentOrder as $index => $attachmentId) {
152 Attachment::query()->where('uploaded_to', '=', $pageId)
153 ->where('id', '=', $attachmentId)
154 ->update(['order' => $index]);
159 * Update the details of a file.
161 public function updateFile(Attachment $attachment, array $requestData): Attachment
163 $attachment->name = $requestData['name'];
164 $link = trim($requestData['link'] ?? '');
167 if (!$attachment->external) {
168 $this->deleteFileInStorage($attachment);
169 $attachment->external = true;
170 $attachment->extension = '';
172 $attachment->path = $requestData['link'];
177 return $attachment->refresh();
181 * Delete a File from the database and storage.
185 public function deleteFile(Attachment $attachment)
187 if (!$attachment->external) {
188 $this->deleteFileInStorage($attachment);
191 $attachment->delete();
195 * Delete a file from the filesystem it sits on.
196 * Cleans any empty leftover folders.
198 protected function deleteFileInStorage(Attachment $attachment)
200 $storage = $this->getStorageDisk();
201 $dirPath = $this->adjustPathForStorageDisk(dirname($attachment->path));
203 $storage->delete($this->adjustPathForStorageDisk($attachment->path));
204 if (count($storage->allFiles($dirPath)) === 0) {
205 $storage->deleteDirectory($dirPath);
210 * Store a file in storage with the given filename.
212 * @throws FileUploadException
214 protected function putFileInStorage(UploadedFile $uploadedFile): string
216 $storage = $this->getStorageDisk();
217 $basePath = 'uploads/files/' . date('Y-m-M') . '/';
219 $uploadFileName = Str::random(16) . '-' . $uploadedFile->getClientOriginalExtension();
220 while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) {
221 $uploadFileName = Str::random(3) . $uploadFileName;
224 $attachmentStream = fopen($uploadedFile->getRealPath(), 'r');
225 $attachmentPath = $basePath . $uploadFileName;
228 $storage->writeStream($this->adjustPathForStorageDisk($attachmentPath), $attachmentStream);
229 } catch (Exception $e) {
230 Log::error('Error when attempting file upload:' . $e->getMessage());
232 throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
235 return $attachmentPath;
239 * Get the file validation rules for attachments.
241 public function getFileValidationRules(): array
243 return ['file', 'max:' . (config('app.upload_limit') * 1000)];