3 namespace BookStack\Uploads;
5 use BookStack\Exceptions\FileUploadException;
7 use Illuminate\Contracts\Filesystem\FileNotFoundException;
8 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
9 use Illuminate\Filesystem\FilesystemManager;
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 FilesystemManager $fileSystem;
20 * AttachmentService constructor.
22 public function __construct(FilesystemManager $fileSystem)
24 $this->fileSystem = $fileSystem;
28 * Get the storage that will be used for storing files.
30 protected function getStorageDisk(): Storage
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->getStorageDisk()->get($this->adjustPathForStorageDisk($attachment->path));
77 * Stream an attachment from storage.
79 * @return resource|null
80 * @throws FileNotFoundException
82 public function streamAttachmentFromStorage(Attachment $attachment)
85 return $this->getStorageDisk()->readStream($this->adjustPathForStorageDisk($attachment->path));
89 * Store a new attachment upon user upload.
91 * @throws FileUploadException
93 public function saveNewUpload(UploadedFile $uploadedFile, int $pageId): Attachment
95 $attachmentName = $uploadedFile->getClientOriginalName();
96 $attachmentPath = $this->putFileInStorage($uploadedFile);
97 $largestExistingOrder = Attachment::query()->where('uploaded_to', '=', $pageId)->max('order');
99 /** @var Attachment $attachment */
100 $attachment = Attachment::query()->forceCreate([
101 'name' => $attachmentName,
102 'path' => $attachmentPath,
103 'extension' => $uploadedFile->getClientOriginalExtension(),
104 'uploaded_to' => $pageId,
105 'created_by' => user()->id,
106 'updated_by' => user()->id,
107 'order' => $largestExistingOrder + 1,
114 * Store an upload, saving to a file and deleting any existing uploads
115 * attached to that file.
117 * @throws FileUploadException
119 public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment): Attachment
121 if (!$attachment->external) {
122 $this->deleteFileInStorage($attachment);
125 $attachmentName = $uploadedFile->getClientOriginalName();
126 $attachmentPath = $this->putFileInStorage($uploadedFile);
128 $attachment->name = $attachmentName;
129 $attachment->path = $attachmentPath;
130 $attachment->external = false;
131 $attachment->extension = $uploadedFile->getClientOriginalExtension();
138 * Save a new File attachment from a given link and name.
140 public function saveNewFromLink(string $name, string $link, int $page_id): Attachment
142 $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
144 return Attachment::forceCreate([
149 'uploaded_to' => $page_id,
150 'created_by' => user()->id,
151 'updated_by' => user()->id,
152 'order' => $largestExistingOrder + 1,
157 * Updates the ordering for a listing of attached files.
159 public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId)
161 foreach ($attachmentOrder as $index => $attachmentId) {
162 Attachment::query()->where('uploaded_to', '=', $pageId)
163 ->where('id', '=', $attachmentId)
164 ->update(['order' => $index]);
169 * Update the details of a file.
171 public function updateFile(Attachment $attachment, array $requestData): Attachment
173 $attachment->name = $requestData['name'];
174 $link = trim($requestData['link'] ?? '');
177 if (!$attachment->external) {
178 $this->deleteFileInStorage($attachment);
179 $attachment->external = true;
180 $attachment->extension = '';
182 $attachment->path = $requestData['link'];
187 return $attachment->refresh();
191 * Delete a File from the database and storage.
195 public function deleteFile(Attachment $attachment)
197 if (!$attachment->external) {
198 $this->deleteFileInStorage($attachment);
201 $attachment->delete();
205 * Delete a file from the filesystem it sits on.
206 * Cleans any empty leftover folders.
208 protected function deleteFileInStorage(Attachment $attachment)
210 $storage = $this->getStorageDisk();
211 $dirPath = $this->adjustPathForStorageDisk(dirname($attachment->path));
213 $storage->delete($this->adjustPathForStorageDisk($attachment->path));
214 if (count($storage->allFiles($dirPath)) === 0) {
215 $storage->deleteDirectory($dirPath);
220 * Store a file in storage with the given filename.
222 * @throws FileUploadException
224 protected function putFileInStorage(UploadedFile $uploadedFile): string
226 $storage = $this->getStorageDisk();
227 $basePath = 'uploads/files/' . date('Y-m-M') . '/';
229 $uploadFileName = Str::random(16) . '-' . $uploadedFile->getClientOriginalExtension();
230 while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) {
231 $uploadFileName = Str::random(3) . $uploadFileName;
234 $attachmentStream = fopen($uploadedFile->getRealPath(), 'r');
235 $attachmentPath = $basePath . $uploadFileName;
238 $storage->writeStream($this->adjustPathForStorageDisk($attachmentPath), $attachmentStream);
239 } catch (Exception $e) {
240 Log::error('Error when attempting file upload:' . $e->getMessage());
242 throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
245 return $attachmentPath;
249 * Get the file validation rules for attachments.
251 public function getFileValidationRules(): array
253 return ['file', 'max:' . (config('app.upload_limit') * 1000)];