Debian Codegraph @

vendor/ipl/html/src/FormElement/FileElement.php

raw
1 <?php
2
3 namespace ipl\Html\FormElement;
4
5 use GuzzleHttp\Psr7\UploadedFile;
6 use InvalidArgumentException;
7 use ipl\Html\Attributes;
8 use ipl\Html\Form;
9 use ipl\Html\HtmlDocument;
10 use ipl\Html\HtmlElement;
11 use ipl\Html\Text;
12 use ipl\I18n\Translation;
13 use ipl\Validator\FileValidator;
14 use ipl\Validator\ValidatorChain;
15 use Psr\Http\Message\UploadedFileInterface;
16 use ipl\Html\Common\MultipleAttribute;
17
18 use function ipl\Stdlib\get_php_type;
19
20 /**
21 * File upload element
22 *
23 * Once the file element is added to the form and the form attribute `enctype` is not set,
24 * it is automatically set to `multipart/form-data`.
25 */
26 class FileElement extends InputElement
27 {
28 use MultipleAttribute;
29 use Translation;
30
31 protected $type = 'file';
32
33 /** @var UploadedFileInterface|UploadedFileInterface[] */
34 protected $value;
35
36 /** @var UploadedFileInterface[] Files that are stored on disk */
37 protected $files = [];
38
39 /** @var string[] Files to be removed from disk */
40 protected $filesToRemove = [];
41
42 /** @var ?string Path to store files to preserve them across requests */
43 protected $destination;
44
45 /** @var int The default maximum file size */
46 protected static $defaultMaxFileSize;
47
48 public function __construct($name, $attributes = null)
49 {
50 $this->getAttributes()->get('accept')->setSeparator(', ');
51
52 parent::__construct($name, $attributes);
53 }
54
55 /**
56 * Get the path to store files to preserve them across requests
57 *
58 * @return string
59 */
60 public function getDestination(): ?string
61 {
62 return $this->destination;
63 }
64
65 /**
66 * Set the path to store files to preserve them across requests
67 *
68 * Uploaded files are moved to the given directory to
69 * retain the file through automatic form submissions and failed form validations.
70 *
71 * Please note that using file persistence currently has the following drawbacks:
72 *
73 * * Works only if the file element is added to the form during {@link Form::assemble()}.
74 * * Persisted files are not removed automatically.
75 * * Files with the same name override each other.
76 *
77 * @param string $path
78 *
79 * @return $this
80 */
81 public function setDestination(string $path): self
82 {
83 $this->destination = $path;
84
85 return $this;
86 }
87
88 public function getValueAttribute()
89 {
90 // Value attributes of file inputs are set only client-side.
91 return null;
92 }
93
94 public function getNameAttribute()
95 {
96 $name = $this->getName();
97
98 return $this->isMultiple() ? ($name . '[]') : $name;
99 }
100
101 public function hasValue()
102 {
103 if ($this->value === null) {
104 $files = $this->loadFiles();
105 if (empty($files)) {
106 return false;
107 }
108
109 if (! $this->isMultiple()) {
110 $files = $files[0];
111 }
112
113 $this->value = $files;
114 }
115
116 return $this->value !== null;
117 }
118
119 public function setValue($value)
120 {
121 if (! empty($value)) {
122 $fileToTest = $value;
123 if ($this->isMultiple()) {
124 $fileToTest = $value[0];
125 }
126
127 if (! $fileToTest instanceof UploadedFileInterface) {
128 throw new InvalidArgumentException(
129 sprintf('%s is not an uploaded file', get_php_type($fileToTest))
130 );
131 }
132
133 if ($fileToTest->getError() === UPLOAD_ERR_NO_FILE && ! $fileToTest->getClientFilename()) {
134 // This is checked here as it's only about file elements for which no value has been chosen
135 $value = null;
136 } else {
137 $files = $value;
138 if (! $this->isMultiple()) {
139 $files = [$files];
140 }
141
142 /** @var UploadedFileInterface[] $files */
143 $storedFiles = $this->storeFiles(...$files);
144 if (! $this->isMultiple()) {
145 $storedFiles = $storedFiles[0] ?? null;
146 }
147
148 $value = $storedFiles;
149 }
150 } else {
151 $value = null;
152 }
153
154 return parent::setValue($value);
155 }
156
157 /**
158 * Get whether there are any files stored on disk
159 *
160 * @return bool
161 */
162 protected function hasFiles(): bool
163 {
164 return $this->destination !== null && reset($this->files);
165 }
166
167 /**
168 * Load and return all files stored on disk
169 *
170 * @return UploadedFileInterface[]
171 */
172 protected function loadFiles(): array
173 {
174 if (empty($this->files) || $this->destination === null) {
175 return [];
176 }
177
178 foreach ($this->files as $name => $_) {
179 $filePath = $this->getFilePath($name);
180 if (! is_readable($filePath) || ! is_file($filePath)) {
181 // If one file isn't accessible, none is
182 return [];
183 }
184
185 if (in_array($name, $this->filesToRemove, true)) {
186 @unlink($filePath);
187 } else {
188 $this->files[$name] = new UploadedFile(
189 $filePath,
190 filesize($filePath) ?: null,
191 0,
192 $name,
193 mime_content_type($filePath) ?: null
194 );
195 }
196 }
197
198 $this->files = array_diff_key($this->files, array_flip($this->filesToRemove));
199
200 return array_values($this->files);
201 }
202
203 /**
204 * Store the given files on disk
205 *
206 * @param UploadedFileInterface ...$files
207 *
208 * @return UploadedFileInterface[]
209 */
210 protected function storeFiles(UploadedFileInterface ...$files): array
211 {
212 if ($this->destination === null || ! is_writable($this->destination)) {
213 return $files;
214 }
215
216 $storedFiles = [];
217 foreach ($files as $file) {
218 $name = $file->getClientFilename();
219 $path = $this->getFilePath($name);
220
221 if ($file->getError() !== UPLOAD_ERR_OK) {
222 // The file is still returned as otherwise it won't be validated
223 $storedFiles[] = $file;
224 continue;
225 }
226
227 $file->moveTo($path);
228
229 // Re-created to ensure moveTo() still works if called externally
230 $file = new UploadedFile(
231 $path,
232 $file->getSize(),
233 0,
234 $name,
235 $file->getClientMediaType()
236 );
237
238 $this->files[$name] = $file;
239 $storedFiles[] = $file;
240 }
241
242 return $storedFiles;
243 }
244
245 /**
246 * Get the file path on disk of the given file
247 *
248 * @param string $name
249 *
250 * @return string
251 */
252 protected function getFilePath(string $name): string
253 {
254 return implode(DIRECTORY_SEPARATOR, [$this->destination, sha1($name)]);
255 }
256
257 public function onRegistered(Form $form)
258 {
259 if (! $form->hasAttribute('enctype')) {
260 $form->setAttribute('enctype', 'multipart/form-data');
261 }
262
263 $chosenFiles = (array) $form->getPopulatedValue('chosen_file_' . $this->getName(), []);
264 foreach ($chosenFiles as $chosenFile) {
265 $this->files[$chosenFile] = null;
266 }
267
268 $this->filesToRemove = (array) $form->getPopulatedValue('remove_file_' . $this->getName(), []);
269 }
270
271 protected function addDefaultValidators(ValidatorChain $chain): void
272 {
273 $chain->add(new FileValidator([
274 'maxSize' => $this->getDefaultMaxFileSize(),
275 'mimeType' => array_filter(
276 (array) $this->getAttributes()->get('accept')->getValue(),
277 function ($type) {
278 // file inputs also allow file extensions in the accept attribute. These
279 // must not be passed as they don't resemble valid mime type definitions.
280 return is_string($type) && ltrim($type)[0] !== '.';
281 }
282 )
283 ]));
284 }
285
286 protected function registerAttributeCallbacks(Attributes $attributes)
287 {
288 parent::registerAttributeCallbacks($attributes);
289 $this->registerMultipleAttributeCallback($attributes);
290 $this->getAttributes()->registerAttributeCallback('destination', null, [$this, 'setDestination']);
291 }
292
293 /**
294 * Get the system's default maximum file upload size
295 *
296 * @return int
297 */
298 public function getDefaultMaxFileSize(): int
299 {
300 if (static::$defaultMaxFileSize === null) {
301 $ini = $this->convertIniToInteger(trim(static::getPostMaxSize()));
302 $max = $this->convertIniToInteger(trim(static::getUploadMaxFilesize()));
303 $min = max($ini, $max);
304 if ($ini > 0) {
305 $min = min($min, $ini);
306 }
307
308 if ($max > 0) {
309 $min = min($min, $max);
310 }
311
312 static::$defaultMaxFileSize = $min;
313 }
314
315 return static::$defaultMaxFileSize;
316 }
317
318 /**
319 * Converts a ini setting to a integer value
320 *
321 * @param string $setting
322 *
323 * @return int
324 */
325 private function convertIniToInteger(string $setting): int
326 {
327 if (! is_numeric($setting)) {
328 $type = strtoupper(substr($setting, -1));
329 $setting = (int) substr($setting, 0, -1);
330
331 switch ($type) {
332 case 'K':
333 $setting *= 1024;
334 break;
335
336 case 'M':
337 $setting *= 1024 * 1024;
338 break;
339
340 case 'G':
341 $setting *= 1024 * 1024 * 1024;
342 break;
343
344 default:
345 break;
346 }
347 }
348
349 return (int) $setting;
350 }
351
352 /**
353 * Get the `post_max_size` INI setting
354 *
355 * @return string
356 */
357 protected static function getPostMaxSize(): string
358 {
359 return ini_get('post_max_size') ?: '8M';
360 }
361
362 /**
363 * Get the `upload_max_filesize` INI setting
364 *
365 * @return string
366 */
367 protected static function getUploadMaxFilesize(): string
368 {
369 return ini_get('upload_max_filesize') ?: '2M';
370 }
371
372 protected function assemble()
373 {
374 $doc = new HtmlDocument();
375 if ($this->hasFiles()) {
376 foreach ($this->files as $file) {
377 $doc->addHtml(new HiddenElement('chosen_file_' . $this->getValueOfNameAttribute(), [
378 'value' => $file->getClientFilename()
379 ]));
380 }
381
382 $this->prependWrapper($doc);
383 }
384 }
385
386 public function renderUnwrapped()
387 {
388 if (! $this->hasValue() || ! $this->hasFiles()) {
389 return parent::renderUnwrapped();
390 }
391
392 $uploadedFiles = new HtmlElement('ul', Attributes::create(['class' => 'uploaded-files']));
393 foreach ($this->files as $file) {
394 $uploadedFiles->addHtml(new HtmlElement(
395 'li',
396 null,
397 (new ButtonElement('remove_file_' . $this->getValueOfNameAttribute(), Attributes::create([
398 'type' => 'submit',
399 'formnovalidate' => true,
400 'class' => 'remove-uploaded-file',
401 'value' => $file->getClientFilename(),
402 'title' => sprintf($this->translate('Remove file "%s"'), $file->getClientFilename())
403 ])))->addHtml(new HtmlElement(
404 'span',
405 null,
406 new HtmlElement('i', Attributes::create(['class' => ['icon', 'fa', 'fa-xmark']])),
407 Text::create($file->getClientFilename())
408 ))
409 ));
410 }
411
412 return $uploadedFiles->render();
413 }
414 }