]> BookStack Code Mirror - bookstack/blob - app/Uploads/FileStorage.php
CommentDisplayTest correct namespace
[bookstack] / app / Uploads / FileStorage.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Exceptions\FileUploadException;
6 use BookStack\Util\FilePathNormalizer;
7 use Exception;
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 Symfony\Component\HttpFoundation\File\UploadedFile;
13
14 class FileStorage
15 {
16     public function __construct(
17         protected FilesystemManager $fileSystem,
18     ) {
19     }
20
21     /**
22      * @return resource|null
23      */
24     public function getReadStream(string $path)
25     {
26         return $this->getStorageDisk()->readStream($this->adjustPathForStorageDisk($path));
27     }
28
29     public function getSize(string $path): int
30     {
31         return $this->getStorageDisk()->size($this->adjustPathForStorageDisk($path));
32     }
33
34     public function delete(string $path, bool $removeEmptyDir = false): void
35     {
36         $storage = $this->getStorageDisk();
37         $adjustedPath = $this->adjustPathForStorageDisk($path);
38         $dir = dirname($adjustedPath);
39
40         $storage->delete($adjustedPath);
41         if ($removeEmptyDir && count($storage->allFiles($dir)) === 0) {
42             $storage->deleteDirectory($dir);
43         }
44     }
45
46     /**
47      * @throws FileUploadException
48      */
49     public function uploadFile(UploadedFile $file, string $subDirectory, string $suffix, string $extension): string
50     {
51         $storage = $this->getStorageDisk();
52         $basePath = trim($subDirectory, '/') . '/';
53
54         $uploadFileName = Str::random(16) . ($suffix ? "-{$suffix}" : '') . ($extension ? ".{$extension}" : '');
55         while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) {
56             $uploadFileName = Str::random(3) . $uploadFileName;
57         }
58
59         $fileStream = fopen($file->getRealPath(), 'r');
60         $filePath = $basePath . $uploadFileName;
61
62         try {
63             $storage->writeStream($this->adjustPathForStorageDisk($filePath), $fileStream);
64         } catch (Exception $e) {
65             Log::error('Error when attempting file upload:' . $e->getMessage());
66
67             throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $filePath]));
68         }
69
70         return $filePath;
71     }
72
73     /**
74      * Check whether the configured storage is remote from the host of this app.
75      */
76     public function isRemote(): bool
77     {
78         return $this->getStorageDiskName() === 's3';
79     }
80
81     /**
82      * Get the actual path on system for the given relative file path.
83      */
84     public function getSystemPath(string $filePath): string
85     {
86         if ($this->isRemote()) {
87             return '';
88         }
89
90         return storage_path('uploads/files/' . ltrim($this->adjustPathForStorageDisk($filePath), '/'));
91     }
92
93     /**
94      * Get the storage that will be used for storing files.
95      */
96     protected function getStorageDisk(): Storage
97     {
98         return $this->fileSystem->disk($this->getStorageDiskName());
99     }
100
101     /**
102      * Get the name of the storage disk to use.
103      */
104     protected function getStorageDiskName(): string
105     {
106         $storageType = trim(strtolower(config('filesystems.attachments')));
107
108         // Change to our secure-attachment disk if any of the local options
109         // are used to prevent escaping that location.
110         if ($storageType === 'local' || $storageType === 'local_secure' || $storageType === 'local_secure_restricted') {
111             $storageType = 'local_secure_attachments';
112         }
113
114         return $storageType;
115     }
116
117     /**
118      * Change the originally provided path to fit any disk-specific requirements.
119      * This also ensures the path is kept to the expected root folders.
120      */
121     protected function adjustPathForStorageDisk(string $path): string
122     {
123         $trimmed = str_replace('uploads/files/', '', $path);
124         $normalized = FilePathNormalizer::normalize($trimmed);
125
126         if ($this->getStorageDiskName() === 'local_secure_attachments') {
127             return $normalized;
128         }
129
130         return 'uploads/files/' . $normalized;
131     }
132 }