1 <?php namespace BookStack\Uploads;
3 use BookStack\Exceptions\FileUploadException;
5 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
6 use Illuminate\Contracts\Filesystem\FileNotFoundException;
7 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
8 use Illuminate\Support\Str;
10 use Symfony\Component\HttpFoundation\File\UploadedFile;
12 class AttachmentService
15 protected $fileSystem;
18 * AttachmentService constructor.
20 public function __construct(FileSystem $fileSystem)
22 $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.
43 * @throws FileNotFoundException
45 public function getAttachmentFromStorage(Attachment $attachment): string
47 return $this->getStorage()->get($attachment->path);
51 * Store a new attachment upon user upload.
52 * @param UploadedFile $uploadedFile
55 * @throws FileUploadException
57 public function saveNewUpload(UploadedFile $uploadedFile, $page_id)
59 $attachmentName = $uploadedFile->getClientOriginalName();
60 $attachmentPath = $this->putFileInStorage($uploadedFile);
61 $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
63 $attachment = Attachment::forceCreate([
64 'name' => $attachmentName,
65 'path' => $attachmentPath,
66 'extension' => $uploadedFile->getClientOriginalExtension(),
67 'uploaded_to' => $page_id,
68 'created_by' => user()->id,
69 'updated_by' => user()->id,
70 'order' => $largestExistingOrder + 1
77 * Store a upload, saving to a file and deleting any existing uploads
78 * attached to that file.
79 * @param UploadedFile $uploadedFile
80 * @param Attachment $attachment
82 * @throws FileUploadException
84 public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment)
86 if (!$attachment->external) {
87 $this->deleteFileInStorage($attachment);
90 $attachmentName = $uploadedFile->getClientOriginalName();
91 $attachmentPath = $this->putFileInStorage($uploadedFile);
93 $attachment->name = $attachmentName;
94 $attachment->path = $attachmentPath;
95 $attachment->external = false;
96 $attachment->extension = $uploadedFile->getClientOriginalExtension();
102 * Save a new File attachment from a given link and name.
104 public function saveNewFromLink(string $name, string $link, int $page_id): Attachment
106 $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
107 return Attachment::forceCreate([
112 'uploaded_to' => $page_id,
113 'created_by' => user()->id,
114 'updated_by' => user()->id,
115 'order' => $largestExistingOrder + 1
120 * Updates the ordering for a listing of attached files.
122 public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId)
124 foreach ($attachmentOrder as $index => $attachmentId) {
125 Attachment::query()->where('uploaded_to', '=', $pageId)
126 ->where('id', '=', $attachmentId)
127 ->update(['order' => $index]);
133 * Update the details of a file.
135 public function updateFile(Attachment $attachment, array $requestData): Attachment
137 $attachment->name = $requestData['name'];
139 if (isset($requestData['link']) && trim($requestData['link']) !== '') {
140 $attachment->path = $requestData['link'];
141 if (!$attachment->external) {
142 $this->deleteFileInStorage($attachment);
143 $attachment->external = true;
152 * Delete a File from the database and storage.
153 * @param Attachment $attachment
156 public function deleteFile(Attachment $attachment)
158 if ($attachment->external) {
159 $attachment->delete();
163 $this->deleteFileInStorage($attachment);
164 $attachment->delete();
168 * Delete a file from the filesystem it sits on.
169 * Cleans any empty leftover folders.
170 * @param Attachment $attachment
172 protected function deleteFileInStorage(Attachment $attachment)
174 $storage = $this->getStorage();
175 $dirPath = dirname($attachment->path);
177 $storage->delete($attachment->path);
178 if (count($storage->allFiles($dirPath)) === 0) {
179 $storage->deleteDirectory($dirPath);
184 * Store a file in storage with the given filename
185 * @param UploadedFile $uploadedFile
187 * @throws FileUploadException
189 protected function putFileInStorage(UploadedFile $uploadedFile)
191 $attachmentData = file_get_contents($uploadedFile->getRealPath());
193 $storage = $this->getStorage();
194 $basePath = 'uploads/files/' . Date('Y-m-M') . '/';
196 $uploadFileName = Str::random(16) . '.' . $uploadedFile->getClientOriginalExtension();
197 while ($storage->exists($basePath . $uploadFileName)) {
198 $uploadFileName = Str::random(3) . $uploadFileName;
201 $attachmentPath = $basePath . $uploadFileName;
203 $storage->put($attachmentPath, $attachmentData);
204 } catch (Exception $e) {
205 Log::error('Error when attempting file upload:' . $e->getMessage());
206 throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
209 return $attachmentPath;