-
Notifications
You must be signed in to change notification settings - Fork 176
/
GaufretteStorage.php
208 lines (173 loc) · 6.83 KB
/
GaufretteStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
<?php
declare(strict_types=1);
namespace Oneup\UploaderBundle\Uploader\Chunk\Storage;
use Gaufrette\Adapter\StreamFactory;
use Gaufrette\Exception\FileNotFound;
use Gaufrette\Filesystem;
use Gaufrette\FilesystemInterface;
use Oneup\UploaderBundle\Uploader\File\FilesystemFile;
use Oneup\UploaderBundle\Uploader\File\GaufretteFile;
use Oneup\UploaderBundle\Uploader\Gaufrette\StreamManager;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class GaufretteStorage extends StreamManager implements ChunkStorageInterface
{
/**
* @var array
*/
protected $unhandledChunk;
public function __construct(FilesystemInterface $filesystem, int $bufferSize, protected ?string $streamWrapperPrefix, protected string $prefix)
{
$base = interface_exists(FilesystemInterface::class)
? FilesystemInterface::class
: Filesystem::class;
if (!$filesystem instanceof $base) {
throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, $filesystem::class));
}
if ($filesystem instanceof Filesystem && !($filesystem->getAdapter() instanceof StreamFactory)) {
throw new \InvalidArgumentException('The filesystem used as chunk storage must implement StreamFactory');
}
$this->filesystem = $filesystem;
$this->buffersize = $bufferSize;
}
/**
* Clears files and folders older than $maxAge in $prefix
* $prefix must be passable so it can clean the orphanage too
* as it is forced to be the same filesystem.
*/
public function clear(int $maxAge, string $prefix = null): void
{
$prefix = $prefix ?: $this->prefix;
$matches = $this->filesystem->listKeys($prefix);
$now = time();
$toDelete = [];
// Collect the directories that are old,
// this also means the files inside are old
// but after the files are deleted the dirs
// would remain
foreach ($matches['dirs'] as $key) {
try {
if ($maxAge <= $now - $this->filesystem->mtime($key)) {
$toDelete[] = $key;
}
} catch (FileNotFound $exception) {
// ignore
}
}
// The same directory is returned for every file it contains
$toDelete = array_unique($toDelete);
foreach ($matches['keys'] as $key) {
try {
if ($maxAge <= $now - $this->filesystem->mtime($key)) {
$this->filesystem->delete($key);
}
} catch (FileNotFound $exception) {
// ignore
}
}
foreach ($toDelete as $key) {
// The filesystem will throw exceptions if
// a directory is not empty
try {
$this->filesystem->delete($key);
} catch (\Exception $e) {
continue;
}
}
}
/**
* Only saves the information about the chunk to avoid moving it
* forth-and-back to reassemble it. Load distribution is enforced
* for gaufrette based chunk storage therefore assembleChunks will
* be called in the same request.
*/
public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original): mixed
{
// Prevent path traversal attacks
$uuid = basename($uuid);
$this->unhandledChunk = [
'uuid' => $uuid,
'index' => $index,
'chunk' => $chunk,
'original' => $original,
];
return null;
}
/**
* @param array $chunks
*/
public function assembleChunks($chunks, bool $removeChunk, bool $renameChunk): GaufretteFile
{
// the index is only added to be in sync with the filesystem storage
$path = $this->prefix . '/' . $this->unhandledChunk['uuid'] . '/';
$filename = $this->unhandledChunk['index'] . '_' . $this->unhandledChunk['original'];
if (empty($chunks)) {
$target = $filename;
$this->ensureRemotePathExists($path . $target);
} else {
/*
* The array only contains items with matching prefix until the filename
* therefore the order will be decided depending on the filename
* It is only case-insensitive to be overly-careful.
*/
sort($chunks, \SORT_STRING | \SORT_FLAG_CASE);
$target = pathinfo($chunks[0], \PATHINFO_BASENAME);
}
$dst = $this->filesystem->createStream($path . $target);
if (0 === $this->unhandledChunk['index']) {
// if it's the first chunk overwrite the already existing part
// to avoid appending to earlier failed uploads
$this->openStream($dst, 'w');
} else {
$this->openStream($dst, 'a');
}
// Meet the interface requirements
$uploadedFile = new FilesystemFile($this->unhandledChunk['chunk']);
$this->stream($uploadedFile, $dst);
if ($renameChunk) {
$name = preg_replace('/^(\d+)_/', '', $target);
/* The name can only match if the same user in the same session is
* trying to upload a file under the same name AND the previous upload failed,
* somewhere between this function, and the cleanup call. If that happened
* the previous file is unaccessible by the user, but if it is not removed
* it will block the user from trying to re-upload it.
*/
if ($this->filesystem->has($path . $name)) {
$this->filesystem->delete($path . $name);
}
$this->filesystem->rename($path . $target, $path . $name);
$target = $name;
}
/** @var GaufretteFile $uploaded */
$uploaded = $this->filesystem->get($path . $target);
if (!$renameChunk) {
return $uploaded;
}
return new GaufretteFile($uploaded, $this->filesystem, $this->streamWrapperPrefix);
}
public function cleanup(string $path): void
{
$this->filesystem->delete($path);
}
public function getChunks(string $uuid): array
{
// Prevent path traversal attacks
$uuid = basename($uuid);
$results = $this->filesystem->listKeys($this->prefix . '/' . $uuid);
/* exclude files without an index, so if there is a completed file which
* failed to upload it will not get mixed together with new one's chunks.
*/
$chunks = preg_grep('/^.+\/(\d+)_/', $results['keys']);
if (false === $chunks) {
return [];
}
return $chunks;
}
public function getFilesystem(): FilesystemInterface
{
return $this->filesystem;
}
public function getStreamWrapperPrefix(): ?string
{
return $this->streamWrapperPrefix;
}
}