]> BookStack Code Mirror - bookstack/blobdiff - app/Uploads/AttachmentService.php
ZIP Imports: Added API examples, finished testing
[bookstack] / app / Uploads / AttachmentService.php
index b4cb1b88b15e26b0d982174b97fa5b80ed13c385..dabd537292f4823eb7a93faada344f59cc2b2a93 100644 (file)
@@ -4,71 +4,50 @@ namespace BookStack\Uploads;
 
 use BookStack\Exceptions\FileUploadException;
 use Exception;
-use Illuminate\Contracts\Filesystem\Factory as FileSystem;
-use Illuminate\Contracts\Filesystem\FileNotFoundException;
-use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
-use Illuminate\Support\Facades\Log;
-use Illuminate\Support\Str;
 use Symfony\Component\HttpFoundation\File\UploadedFile;
 
 class AttachmentService
 {
-    protected $fileSystem;
-
-    /**
-     * AttachmentService constructor.
-     */
-    public function __construct(FileSystem $fileSystem)
-    {
-        $this->fileSystem = $fileSystem;
+    public function __construct(
+        protected FileStorage $storage,
+    ) {
     }
 
     /**
-     * Get the storage that will be used for storing files.
+     * Stream an attachment from storage.
+     *
+     * @return resource|null
      */
-    protected function getStorage(): FileSystemInstance
+    public function streamAttachmentFromStorage(Attachment $attachment)
     {
-        $storageType = config('filesystems.attachments');
-
-        // Override default location if set to local public to ensure not visible.
-        if ($storageType === 'local') {
-            $storageType = 'local_secure';
-        }
-
-        return $this->fileSystem->disk($storageType);
+        return $this->storage->getReadStream($attachment->path);
     }
 
     /**
-     * Get an attachment from storage.
-     *
-     * @throws FileNotFoundException
+     * Read the file size of an attachment from storage, in bytes.
      */
-    public function getAttachmentFromStorage(Attachment $attachment): string
+    public function getAttachmentFileSize(Attachment $attachment): int
     {
-        return $this->getStorage()->get($attachment->path);
+        return $this->storage->getSize($attachment->path);
     }
 
     /**
      * Store a new attachment upon user upload.
      *
-     * @param UploadedFile $uploadedFile
-     * @param int          $page_id
-     *
      * @throws FileUploadException
-     *
-     * @return Attachment
      */
-    public function saveNewUpload(UploadedFile $uploadedFile, $page_id)
+    public function saveNewUpload(UploadedFile $uploadedFile, int $pageId): Attachment
     {
         $attachmentName = $uploadedFile->getClientOriginalName();
         $attachmentPath = $this->putFileInStorage($uploadedFile);
-        $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
+        $largestExistingOrder = Attachment::query()->where('uploaded_to', '=', $pageId)->max('order');
 
-        $attachment = Attachment::forceCreate([
+        /** @var Attachment $attachment */
+        $attachment = Attachment::query()->forceCreate([
             'name'        => $attachmentName,
             'path'        => $attachmentPath,
             'extension'   => $uploadedFile->getClientOriginalExtension(),
-            'uploaded_to' => $page_id,
+            'uploaded_to' => $pageId,
             'created_by'  => user()->id,
             'updated_by'  => user()->id,
             'order'       => $largestExistingOrder + 1,
@@ -78,17 +57,12 @@ class AttachmentService
     }
 
     /**
-     * Store a upload, saving to a file and deleting any existing uploads
+     * Store an upload, saving to a file and deleting any existing uploads
      * attached to that file.
      *
-     * @param UploadedFile $uploadedFile
-     * @param Attachment   $attachment
-     *
      * @throws FileUploadException
-     *
-     * @return Attachment
      */
-    public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment)
+    public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment): Attachment
     {
         if (!$attachment->external) {
             $this->deleteFileInStorage($attachment);
@@ -142,88 +116,70 @@ class AttachmentService
      */
     public function updateFile(Attachment $attachment, array $requestData): Attachment
     {
-        $attachment->name = $requestData['name'];
+        if (isset($requestData['name'])) {
+            $attachment->name = $requestData['name'];
+        }
 
-        if (isset($requestData['link']) && trim($requestData['link']) !== '') {
-            $attachment->path = $requestData['link'];
+        $link = trim($requestData['link'] ?? '');
+        if (!empty($link)) {
             if (!$attachment->external) {
                 $this->deleteFileInStorage($attachment);
                 $attachment->external = true;
+                $attachment->extension = '';
             }
+            $attachment->path = $link;
         }
 
         $attachment->save();
 
-        return $attachment;
+        return $attachment->refresh();
     }
 
     /**
      * Delete a File from the database and storage.
      *
-     * @param Attachment $attachment
-     *
      * @throws Exception
      */
     public function deleteFile(Attachment $attachment)
     {
-        if ($attachment->external) {
-            $attachment->delete();
-
-            return;
+        if (!$attachment->external) {
+            $this->deleteFileInStorage($attachment);
         }
 
-        $this->deleteFileInStorage($attachment);
         $attachment->delete();
     }
 
     /**
      * Delete a file from the filesystem it sits on.
      * Cleans any empty leftover folders.
-     *
-     * @param Attachment $attachment
      */
-    protected function deleteFileInStorage(Attachment $attachment)
+    public function deleteFileInStorage(Attachment $attachment): void
     {
-        $storage = $this->getStorage();
-        $dirPath = dirname($attachment->path);
-
-        $storage->delete($attachment->path);
-        if (count($storage->allFiles($dirPath)) === 0) {
-            $storage->deleteDirectory($dirPath);
-        }
+        $this->storage->delete($attachment->path);
     }
 
     /**
      * Store a file in storage with the given filename.
      *
-     * @param UploadedFile $uploadedFile
-     *
      * @throws FileUploadException
-     *
-     * @return string
      */
-    protected function putFileInStorage(UploadedFile $uploadedFile)
+    protected function putFileInStorage(UploadedFile $uploadedFile): string
     {
-        $attachmentData = file_get_contents($uploadedFile->getRealPath());
-
-        $storage = $this->getStorage();
         $basePath = 'uploads/files/' . date('Y-m-M') . '/';
 
-        $uploadFileName = Str::random(16) . '.' . $uploadedFile->getClientOriginalExtension();
-        while ($storage->exists($basePath . $uploadFileName)) {
-            $uploadFileName = Str::random(3) . $uploadFileName;
-        }
-
-        $attachmentPath = $basePath . $uploadFileName;
-
-        try {
-            $storage->put($attachmentPath, $attachmentData);
-        } catch (Exception $e) {
-            Log::error('Error when attempting file upload:' . $e->getMessage());
-
-            throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath]));
-        }
+        return $this->storage->uploadFile(
+            $uploadedFile,
+            $basePath,
+            $uploadedFile->getClientOriginalExtension(),
+            ''
+        );
+    }
 
-        return $attachmentPath;
+    /**
+     * Get the file validation rules for attachments.
+     */
+    public static function getFileValidationRules(): array
+    {
+        return ['file', 'max:' . (config('app.upload_limit') * 1000)];
     }
 }