]> BookStack Code Mirror - bookstack/blobdiff - app/Uploads/AttachmentService.php
ZIP Imports: Added API examples, finished testing
[bookstack] / app / Uploads / AttachmentService.php
index 72f78e347bf54cd61d5f084d3fd7a456e6d07c0d..dabd537292f4823eb7a93faada344f59cc2b2a93 100644 (file)
@@ -4,63 +4,13 @@ namespace BookStack\Uploads;
 
 use BookStack\Exceptions\FileUploadException;
 use Exception;
-use Illuminate\Contracts\Filesystem\FileNotFoundException;
-use Illuminate\Contracts\Filesystem\Filesystem as Storage;
-use Illuminate\Filesystem\FilesystemManager;
-use Illuminate\Support\Facades\Log;
-use Illuminate\Support\Str;
-use League\Flysystem\WhitespacePathNormalizer;
 use Symfony\Component\HttpFoundation\File\UploadedFile;
 
 class AttachmentService
 {
-    protected FilesystemManager $fileSystem;
-
-    /**
-     * AttachmentService constructor.
-     */
-    public function __construct(FilesystemManager $fileSystem)
-    {
-        $this->fileSystem = $fileSystem;
-    }
-
-    /**
-     * Get the storage that will be used for storing files.
-     */
-    protected function getStorageDisk(): Storage
-    {
-        return $this->fileSystem->disk($this->getStorageDiskName());
-    }
-
-    /**
-     * Get the name of the storage disk to use.
-     */
-    protected function getStorageDiskName(): string
-    {
-        $storageType = config('filesystems.attachments');
-
-        // Change to our secure-attachment disk if any of the local options
-        // are used to prevent escaping that location.
-        if ($storageType === 'local' || $storageType === 'local_secure' || $storageType === 'local_secure_restricted') {
-            $storageType = 'local_secure_attachments';
-        }
-
-        return $storageType;
-    }
-
-    /**
-     * Change the originally provided path to fit any disk-specific requirements.
-     * This also ensures the path is kept to the expected root folders.
-     */
-    protected function adjustPathForStorageDisk(string $path): string
-    {
-        $path = (new WhitespacePathNormalizer())->normalizePath(str_replace('uploads/files/', '', $path));
-
-        if ($this->getStorageDiskName() === 'local_secure_attachments') {
-            return $path;
-        }
-
-        return 'uploads/files/' . $path;
+    public function __construct(
+        protected FileStorage $storage,
+    ) {
     }
 
     /**
@@ -70,7 +20,7 @@ class AttachmentService
      */
     public function streamAttachmentFromStorage(Attachment $attachment)
     {
-        return $this->getStorageDisk()->readStream($this->adjustPathForStorageDisk($attachment->path));
+        return $this->storage->getReadStream($attachment->path);
     }
 
     /**
@@ -78,7 +28,7 @@ class AttachmentService
      */
     public function getAttachmentFileSize(Attachment $attachment): int
     {
-        return $this->getStorageDisk()->size($this->adjustPathForStorageDisk($attachment->path));
+        return $this->storage->getSize($attachment->path);
     }
 
     /**
@@ -166,16 +116,18 @@ class AttachmentService
      */
     public function updateFile(Attachment $attachment, array $requestData): Attachment
     {
-        $attachment->name = $requestData['name'];
-        $link = trim($requestData['link'] ?? '');
+        if (isset($requestData['name'])) {
+            $attachment->name = $requestData['name'];
+        }
 
+        $link = trim($requestData['link'] ?? '');
         if (!empty($link)) {
             if (!$attachment->external) {
                 $this->deleteFileInStorage($attachment);
                 $attachment->external = true;
                 $attachment->extension = '';
             }
-            $attachment->path = $requestData['link'];
+            $attachment->path = $link;
         }
 
         $attachment->save();
@@ -201,15 +153,9 @@ class AttachmentService
      * Delete a file from the filesystem it sits on.
      * Cleans any empty leftover folders.
      */
-    protected function deleteFileInStorage(Attachment $attachment)
+    public function deleteFileInStorage(Attachment $attachment): void
     {
-        $storage = $this->getStorageDisk();
-        $dirPath = $this->adjustPathForStorageDisk(dirname($attachment->path));
-
-        $storage->delete($this->adjustPathForStorageDisk($attachment->path));
-        if (count($storage->allFiles($dirPath)) === 0) {
-            $storage->deleteDirectory($dirPath);
-        }
+        $this->storage->delete($attachment->path);
     }
 
     /**
@@ -219,32 +165,20 @@ class AttachmentService
      */
     protected function putFileInStorage(UploadedFile $uploadedFile): string
     {
-        $storage = $this->getStorageDisk();
         $basePath = 'uploads/files/' . date('Y-m-M') . '/';
 
-        $uploadFileName = Str::random(16) . '-' . $uploadedFile->getClientOriginalExtension();
-        while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) {
-            $uploadFileName = Str::random(3) . $uploadFileName;
-        }
-
-        $attachmentStream = fopen($uploadedFile->getRealPath(), 'r');
-        $attachmentPath = $basePath . $uploadFileName;
-
-        try {
-            $storage->writeStream($this->adjustPathForStorageDisk($attachmentPath), $attachmentStream);
-        } catch (Exception $e) {
-            Log::error('Error when attempting file upload:' . $e->getMessage());
-
-            throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
-        }
-
-        return $attachmentPath;
+        return $this->storage->uploadFile(
+            $uploadedFile,
+            $basePath,
+            $uploadedFile->getClientOriginalExtension(),
+            ''
+        );
     }
 
     /**
      * Get the file validation rules for attachments.
      */
-    public function getFileValidationRules(): array
+    public static function getFileValidationRules(): array
     {
         return ['file', 'max:' . (config('app.upload_limit') * 1000)];
     }